babylon.max.js 3.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. if (this.x !== this.y) {
  1403. return true;
  1404. }
  1405. if (this.x !== this.z) {
  1406. return true;
  1407. }
  1408. if (this.y !== this.z) {
  1409. return true;
  1410. }
  1411. return false;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. // Properties
  1417. /**
  1418. * Returns the length of the Vector3 (float).
  1419. */
  1420. Vector3.prototype.length = function () {
  1421. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1422. };
  1423. /**
  1424. * Returns the squared length of the Vector3 (float).
  1425. */
  1426. Vector3.prototype.lengthSquared = function () {
  1427. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1428. };
  1429. // Methods
  1430. /**
  1431. * Normalize the current Vector3.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.normalize = function () {
  1435. var len = this.length();
  1436. if (len === 0 || len === 1.0)
  1437. return this;
  1438. var num = 1.0 / len;
  1439. this.x *= num;
  1440. this.y *= num;
  1441. this.z *= num;
  1442. return this;
  1443. };
  1444. /**
  1445. * Returns a new Vector3 copied from the current Vector3.
  1446. */
  1447. Vector3.prototype.clone = function () {
  1448. return new Vector3(this.x, this.y, this.z);
  1449. };
  1450. /**
  1451. * Copies the passed vector coordinates to the current Vector3 ones.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.copyFrom = function (source) {
  1455. this.x = source.x;
  1456. this.y = source.y;
  1457. this.z = source.z;
  1458. return this;
  1459. };
  1460. /**
  1461. * Copies the passed floats to the current Vector3 coordinates.
  1462. * Returns the updated Vector3.
  1463. */
  1464. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1465. this.x = x;
  1466. this.y = y;
  1467. this.z = z;
  1468. return this;
  1469. };
  1470. /**
  1471. * Copies the passed floats to the current Vector3 coordinates.
  1472. * Returns the updated Vector3.
  1473. */
  1474. Vector3.prototype.set = function (x, y, z) {
  1475. return this.copyFromFloats(x, y, z);
  1476. };
  1477. // Statics
  1478. /**
  1479. *
  1480. */
  1481. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1482. var d0 = Vector3.Dot(vector0, axis) - size;
  1483. var d1 = Vector3.Dot(vector1, axis) - size;
  1484. var s = d0 / (d0 - d1);
  1485. return s;
  1486. };
  1487. /**
  1488. * Returns a new Vector3 set from the index "offset" of the passed array.
  1489. */
  1490. Vector3.FromArray = function (array, offset) {
  1491. if (!offset) {
  1492. offset = 0;
  1493. }
  1494. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1495. };
  1496. /**
  1497. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1498. * This function is deprecated. Use FromArray instead.
  1499. */
  1500. Vector3.FromFloatArray = function (array, offset) {
  1501. return Vector3.FromArray(array, offset);
  1502. };
  1503. /**
  1504. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1505. */
  1506. Vector3.FromArrayToRef = function (array, offset, result) {
  1507. result.x = array[offset];
  1508. result.y = array[offset + 1];
  1509. result.z = array[offset + 2];
  1510. };
  1511. /**
  1512. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1513. * This function is deprecated. Use FromArrayToRef instead.
  1514. */
  1515. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1516. return Vector3.FromArrayToRef(array, offset, result);
  1517. };
  1518. /**
  1519. * Sets the passed vector "result" with the passed floats.
  1520. */
  1521. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1522. result.x = x;
  1523. result.y = y;
  1524. result.z = z;
  1525. };
  1526. /**
  1527. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1528. */
  1529. Vector3.Zero = function () {
  1530. return new Vector3(0.0, 0.0, 0.0);
  1531. };
  1532. /**
  1533. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1534. */
  1535. Vector3.One = function () {
  1536. return new Vector3(1.0, 1.0, 1.0);
  1537. };
  1538. /**
  1539. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1540. */
  1541. Vector3.Up = function () {
  1542. return new Vector3(0.0, 1.0, 0.0);
  1543. };
  1544. /**
  1545. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1546. */
  1547. Vector3.Forward = function () {
  1548. return new Vector3(0.0, 0.0, 1.0);
  1549. };
  1550. /**
  1551. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1552. */
  1553. Vector3.Right = function () {
  1554. return new Vector3(1.0, 0.0, 0.0);
  1555. };
  1556. /**
  1557. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1558. */
  1559. Vector3.Left = function () {
  1560. return new Vector3(-1.0, 0.0, 0.0);
  1561. };
  1562. /**
  1563. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1564. * This method computes tranformed coordinates only, not transformed direction vectors.
  1565. */
  1566. Vector3.TransformCoordinates = function (vector, transformation) {
  1567. var result = Vector3.Zero();
  1568. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1569. return result;
  1570. };
  1571. /**
  1572. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1573. * This method computes tranformed coordinates only, not transformed direction vectors.
  1574. */
  1575. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1576. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1577. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1578. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1579. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1580. result.x = x / w;
  1581. result.y = y / w;
  1582. result.z = z / w;
  1583. };
  1584. /**
  1585. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1586. * This method computes tranformed coordinates only, not transformed direction vectors.
  1587. */
  1588. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1589. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1590. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1591. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1592. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1593. result.x = rx / rw;
  1594. result.y = ry / rw;
  1595. result.z = rz / rw;
  1596. };
  1597. /**
  1598. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1599. * This methods computes transformed normalized direction vectors only.
  1600. */
  1601. Vector3.TransformNormal = function (vector, transformation) {
  1602. var result = Vector3.Zero();
  1603. Vector3.TransformNormalToRef(vector, transformation, result);
  1604. return result;
  1605. };
  1606. /**
  1607. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1608. * This methods computes transformed normalized direction vectors only.
  1609. */
  1610. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1611. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1612. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1613. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1614. result.x = x;
  1615. result.y = y;
  1616. result.z = z;
  1617. };
  1618. /**
  1619. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1620. * This methods computes transformed normalized direction vectors only.
  1621. */
  1622. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1623. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1624. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1625. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1626. };
  1627. /**
  1628. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1629. */
  1630. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1631. var squared = amount * amount;
  1632. var cubed = amount * squared;
  1633. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1634. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1635. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1636. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1637. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1638. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1639. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1640. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1641. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1642. return new Vector3(x, y, z);
  1643. };
  1644. /**
  1645. * 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".
  1646. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1647. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1648. */
  1649. Vector3.Clamp = function (value, min, max) {
  1650. var x = value.x;
  1651. x = (x > max.x) ? max.x : x;
  1652. x = (x < min.x) ? min.x : x;
  1653. var y = value.y;
  1654. y = (y > max.y) ? max.y : y;
  1655. y = (y < min.y) ? min.y : y;
  1656. var z = value.z;
  1657. z = (z > max.z) ? max.z : z;
  1658. z = (z < min.z) ? min.z : z;
  1659. return new Vector3(x, y, z);
  1660. };
  1661. /**
  1662. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1663. */
  1664. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1665. var squared = amount * amount;
  1666. var cubed = amount * squared;
  1667. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1668. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1669. var part3 = (cubed - (2.0 * squared)) + amount;
  1670. var part4 = cubed - squared;
  1671. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1672. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1673. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1674. return new Vector3(x, y, z);
  1675. };
  1676. /**
  1677. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1678. */
  1679. Vector3.Lerp = function (start, end, amount) {
  1680. var result = new Vector3(0, 0, 0);
  1681. Vector3.LerpToRef(start, end, amount, result);
  1682. return result;
  1683. };
  1684. /**
  1685. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1686. */
  1687. Vector3.LerpToRef = function (start, end, amount, result) {
  1688. result.x = start.x + ((end.x - start.x) * amount);
  1689. result.y = start.y + ((end.y - start.y) * amount);
  1690. result.z = start.z + ((end.z - start.z) * amount);
  1691. };
  1692. /**
  1693. * Returns the dot product (float) between the vectors "left" and "right".
  1694. */
  1695. Vector3.Dot = function (left, right) {
  1696. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1697. };
  1698. /**
  1699. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1700. * The cross product is then orthogonal to both "left" and "right".
  1701. */
  1702. Vector3.Cross = function (left, right) {
  1703. var result = Vector3.Zero();
  1704. Vector3.CrossToRef(left, right, result);
  1705. return result;
  1706. };
  1707. /**
  1708. * Sets the passed vector "result" with the cross product of "left" and "right".
  1709. * The cross product is then orthogonal to both "left" and "right".
  1710. */
  1711. Vector3.CrossToRef = function (left, right, result) {
  1712. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1713. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1714. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1715. result.copyFrom(MathTmp.Vector3[0]);
  1716. };
  1717. /**
  1718. * Returns a new Vector3 as the normalization of the passed vector.
  1719. */
  1720. Vector3.Normalize = function (vector) {
  1721. var result = Vector3.Zero();
  1722. Vector3.NormalizeToRef(vector, result);
  1723. return result;
  1724. };
  1725. /**
  1726. * Sets the passed vector "result" with the normalization of the passed first vector.
  1727. */
  1728. Vector3.NormalizeToRef = function (vector, result) {
  1729. result.copyFrom(vector);
  1730. result.normalize();
  1731. };
  1732. Vector3.Project = function (vector, world, transform, viewport) {
  1733. var cw = viewport.width;
  1734. var ch = viewport.height;
  1735. var cx = viewport.x;
  1736. var cy = viewport.y;
  1737. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1738. 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);
  1739. var matrix = MathTmp.Matrix[0];
  1740. world.multiplyToRef(transform, matrix);
  1741. matrix.multiplyToRef(viewportMatrix, matrix);
  1742. return Vector3.TransformCoordinates(vector, matrix);
  1743. };
  1744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1745. var matrix = MathTmp.Matrix[0];
  1746. world.multiplyToRef(transform, matrix);
  1747. matrix.invert();
  1748. source.x = source.x / viewportWidth * 2 - 1;
  1749. source.y = -(source.y / viewportHeight * 2 - 1);
  1750. var vector = Vector3.TransformCoordinates(source, matrix);
  1751. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1752. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1753. vector = vector.scale(1.0 / num);
  1754. }
  1755. return vector;
  1756. };
  1757. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1758. var matrix = MathTmp.Matrix[0];
  1759. world.multiplyToRef(view, matrix);
  1760. matrix.multiplyToRef(projection, matrix);
  1761. matrix.invert();
  1762. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1763. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1764. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1765. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1766. vector = vector.scale(1.0 / num);
  1767. }
  1768. return vector;
  1769. };
  1770. Vector3.Minimize = function (left, right) {
  1771. var min = left.clone();
  1772. min.MinimizeInPlace(right);
  1773. return min;
  1774. };
  1775. Vector3.Maximize = function (left, right) {
  1776. var max = left.clone();
  1777. max.MaximizeInPlace(right);
  1778. return max;
  1779. };
  1780. /**
  1781. * Returns the distance (float) between the vectors "value1" and "value2".
  1782. */
  1783. Vector3.Distance = function (value1, value2) {
  1784. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1785. };
  1786. /**
  1787. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1788. */
  1789. Vector3.DistanceSquared = function (value1, value2) {
  1790. var x = value1.x - value2.x;
  1791. var y = value1.y - value2.y;
  1792. var z = value1.z - value2.z;
  1793. return (x * x) + (y * y) + (z * z);
  1794. };
  1795. /**
  1796. * Returns a new Vector3 located at the center between "value1" and "value2".
  1797. */
  1798. Vector3.Center = function (value1, value2) {
  1799. var center = value1.add(value2);
  1800. center.scaleInPlace(0.5);
  1801. return center;
  1802. };
  1803. /**
  1804. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1805. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1806. * to something in order to rotate it from its local system to the given target system.
  1807. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1808. * Returns a new Vector3.
  1809. */
  1810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1811. var rotation = Vector3.Zero();
  1812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1813. return rotation;
  1814. };
  1815. /**
  1816. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1817. */
  1818. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1819. var quat = MathTmp.Quaternion[0];
  1820. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1821. quat.toEulerAnglesToRef(ref);
  1822. };
  1823. return Vector3;
  1824. }());
  1825. BABYLON.Vector3 = Vector3;
  1826. //Vector4 class created for EulerAngle class conversion to Quaternion
  1827. var Vector4 = /** @class */ (function () {
  1828. /**
  1829. * Creates a Vector4 object from the passed floats.
  1830. */
  1831. function Vector4(x, y, z, w) {
  1832. this.x = x;
  1833. this.y = y;
  1834. this.z = z;
  1835. this.w = w;
  1836. }
  1837. /**
  1838. * Returns the string with the Vector4 coordinates.
  1839. */
  1840. Vector4.prototype.toString = function () {
  1841. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1842. };
  1843. /**
  1844. * Returns the string "Vector4".
  1845. */
  1846. Vector4.prototype.getClassName = function () {
  1847. return "Vector4";
  1848. };
  1849. /**
  1850. * Returns the Vector4 hash code.
  1851. */
  1852. Vector4.prototype.getHashCode = function () {
  1853. var hash = this.x || 0;
  1854. hash = (hash * 397) ^ (this.y || 0);
  1855. hash = (hash * 397) ^ (this.z || 0);
  1856. hash = (hash * 397) ^ (this.w || 0);
  1857. return hash;
  1858. };
  1859. // Operators
  1860. /**
  1861. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.asArray = function () {
  1864. var result = new Array();
  1865. this.toArray(result, 0);
  1866. return result;
  1867. };
  1868. /**
  1869. * Populates the passed array from the passed index with the Vector4 coordinates.
  1870. * Returns the Vector4.
  1871. */
  1872. Vector4.prototype.toArray = function (array, index) {
  1873. if (index === undefined) {
  1874. index = 0;
  1875. }
  1876. array[index] = this.x;
  1877. array[index + 1] = this.y;
  1878. array[index + 2] = this.z;
  1879. array[index + 3] = this.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Adds the passed vector to the current Vector4.
  1884. * Returns the updated Vector4.
  1885. */
  1886. Vector4.prototype.addInPlace = function (otherVector) {
  1887. this.x += otherVector.x;
  1888. this.y += otherVector.y;
  1889. this.z += otherVector.z;
  1890. this.w += otherVector.w;
  1891. return this;
  1892. };
  1893. /**
  1894. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1895. */
  1896. Vector4.prototype.add = function (otherVector) {
  1897. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1898. };
  1899. /**
  1900. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1901. * Returns the current Vector4.
  1902. */
  1903. Vector4.prototype.addToRef = function (otherVector, result) {
  1904. result.x = this.x + otherVector.x;
  1905. result.y = this.y + otherVector.y;
  1906. result.z = this.z + otherVector.z;
  1907. result.w = this.w + otherVector.w;
  1908. return this;
  1909. };
  1910. /**
  1911. * Subtract in place the passed vector from the current Vector4.
  1912. * Returns the updated Vector4.
  1913. */
  1914. Vector4.prototype.subtractInPlace = function (otherVector) {
  1915. this.x -= otherVector.x;
  1916. this.y -= otherVector.y;
  1917. this.z -= otherVector.z;
  1918. this.w -= otherVector.w;
  1919. return this;
  1920. };
  1921. /**
  1922. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1923. */
  1924. Vector4.prototype.subtract = function (otherVector) {
  1925. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1926. };
  1927. /**
  1928. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1929. * Returns the current Vector4.
  1930. */
  1931. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1932. result.x = this.x - otherVector.x;
  1933. result.y = this.y - otherVector.y;
  1934. result.z = this.z - otherVector.z;
  1935. result.w = this.w - otherVector.w;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1940. */
  1941. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1942. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1943. };
  1944. /**
  1945. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1946. * Returns the current Vector4.
  1947. */
  1948. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1949. result.x = this.x - x;
  1950. result.y = this.y - y;
  1951. result.z = this.z - z;
  1952. result.w = this.w - w;
  1953. return this;
  1954. };
  1955. /**
  1956. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1957. */
  1958. Vector4.prototype.negate = function () {
  1959. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1960. };
  1961. /**
  1962. * Multiplies the current Vector4 coordinates by scale (float).
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.scaleInPlace = function (scale) {
  1966. this.x *= scale;
  1967. this.y *= scale;
  1968. this.z *= scale;
  1969. this.w *= scale;
  1970. return this;
  1971. };
  1972. /**
  1973. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1974. */
  1975. Vector4.prototype.scale = function (scale) {
  1976. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1977. };
  1978. /**
  1979. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1980. * Returns the current Vector4.
  1981. */
  1982. Vector4.prototype.scaleToRef = function (scale, result) {
  1983. result.x = this.x * scale;
  1984. result.y = this.y * scale;
  1985. result.z = this.z * scale;
  1986. result.w = this.w * scale;
  1987. return this;
  1988. };
  1989. /**
  1990. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1991. */
  1992. Vector4.prototype.equals = function (otherVector) {
  1993. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1994. };
  1995. /**
  1996. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1997. */
  1998. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1999. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2000. return otherVector
  2001. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2002. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2003. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2004. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2005. };
  2006. /**
  2007. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2008. */
  2009. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2010. return this.x === x && this.y === y && this.z === z && this.w === w;
  2011. };
  2012. /**
  2013. * Multiplies in place the current Vector4 by the passed one.
  2014. * Returns the updated Vector4.
  2015. */
  2016. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2017. this.x *= otherVector.x;
  2018. this.y *= otherVector.y;
  2019. this.z *= otherVector.z;
  2020. this.w *= otherVector.w;
  2021. return this;
  2022. };
  2023. /**
  2024. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2025. */
  2026. Vector4.prototype.multiply = function (otherVector) {
  2027. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2028. };
  2029. /**
  2030. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2031. * Returns the current Vector4.
  2032. */
  2033. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2034. result.x = this.x * otherVector.x;
  2035. result.y = this.y * otherVector.y;
  2036. result.z = this.z * otherVector.z;
  2037. result.w = this.w * otherVector.w;
  2038. return this;
  2039. };
  2040. /**
  2041. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2042. */
  2043. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2044. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2045. };
  2046. /**
  2047. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2048. */
  2049. Vector4.prototype.divide = function (otherVector) {
  2050. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2051. };
  2052. /**
  2053. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2054. * Returns the current Vector4.
  2055. */
  2056. Vector4.prototype.divideToRef = function (otherVector, result) {
  2057. result.x = this.x / otherVector.x;
  2058. result.y = this.y / otherVector.y;
  2059. result.z = this.z / otherVector.z;
  2060. result.w = this.w / otherVector.w;
  2061. return this;
  2062. };
  2063. /**
  2064. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2065. */
  2066. Vector4.prototype.MinimizeInPlace = function (other) {
  2067. if (other.x < this.x)
  2068. this.x = other.x;
  2069. if (other.y < this.y)
  2070. this.y = other.y;
  2071. if (other.z < this.z)
  2072. this.z = other.z;
  2073. if (other.w < this.w)
  2074. this.w = other.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2079. */
  2080. Vector4.prototype.MaximizeInPlace = function (other) {
  2081. if (other.x > this.x)
  2082. this.x = other.x;
  2083. if (other.y > this.y)
  2084. this.y = other.y;
  2085. if (other.z > this.z)
  2086. this.z = other.z;
  2087. if (other.w > this.w)
  2088. this.w = other.w;
  2089. return this;
  2090. };
  2091. // Properties
  2092. /**
  2093. * Returns the Vector4 length (float).
  2094. */
  2095. Vector4.prototype.length = function () {
  2096. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2097. };
  2098. /**
  2099. * Returns the Vector4 squared length (float).
  2100. */
  2101. Vector4.prototype.lengthSquared = function () {
  2102. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2103. };
  2104. // Methods
  2105. /**
  2106. * Normalizes in place the Vector4.
  2107. * Returns the updated Vector4.
  2108. */
  2109. Vector4.prototype.normalize = function () {
  2110. var len = this.length();
  2111. if (len === 0)
  2112. return this;
  2113. var num = 1.0 / len;
  2114. this.x *= num;
  2115. this.y *= num;
  2116. this.z *= num;
  2117. this.w *= num;
  2118. return this;
  2119. };
  2120. /**
  2121. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2122. */
  2123. Vector4.prototype.toVector3 = function () {
  2124. return new Vector3(this.x, this.y, this.z);
  2125. };
  2126. /**
  2127. * Returns a new Vector4 copied from the current one.
  2128. */
  2129. Vector4.prototype.clone = function () {
  2130. return new Vector4(this.x, this.y, this.z, this.w);
  2131. };
  2132. /**
  2133. * Updates the current Vector4 with the passed one coordinates.
  2134. * Returns the updated Vector4.
  2135. */
  2136. Vector4.prototype.copyFrom = function (source) {
  2137. this.x = source.x;
  2138. this.y = source.y;
  2139. this.z = source.z;
  2140. this.w = source.w;
  2141. return this;
  2142. };
  2143. /**
  2144. * Updates the current Vector4 coordinates with the passed floats.
  2145. * Returns the updated Vector4.
  2146. */
  2147. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2148. this.x = x;
  2149. this.y = y;
  2150. this.z = z;
  2151. this.w = w;
  2152. return this;
  2153. };
  2154. /**
  2155. * Updates the current Vector4 coordinates with the passed floats.
  2156. * Returns the updated Vector4.
  2157. */
  2158. Vector4.prototype.set = function (x, y, z, w) {
  2159. return this.copyFromFloats(x, y, z, w);
  2160. };
  2161. // Statics
  2162. /**
  2163. * Returns a new Vector4 set from the starting index of the passed array.
  2164. */
  2165. Vector4.FromArray = function (array, offset) {
  2166. if (!offset) {
  2167. offset = 0;
  2168. }
  2169. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2170. };
  2171. /**
  2172. * Updates the passed vector "result" from the starting index of the passed array.
  2173. */
  2174. Vector4.FromArrayToRef = function (array, offset, result) {
  2175. result.x = array[offset];
  2176. result.y = array[offset + 1];
  2177. result.z = array[offset + 2];
  2178. result.w = array[offset + 3];
  2179. };
  2180. /**
  2181. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2182. */
  2183. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2184. Vector4.FromArrayToRef(array, offset, result);
  2185. };
  2186. /**
  2187. * Updates the passed vector "result" coordinates from the passed floats.
  2188. */
  2189. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2190. result.x = x;
  2191. result.y = y;
  2192. result.z = z;
  2193. result.w = w;
  2194. };
  2195. /**
  2196. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2197. */
  2198. Vector4.Zero = function () {
  2199. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2200. };
  2201. /**
  2202. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2203. */
  2204. Vector4.One = function () {
  2205. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2206. };
  2207. /**
  2208. * Returns a new normalized Vector4 from the passed one.
  2209. */
  2210. Vector4.Normalize = function (vector) {
  2211. var result = Vector4.Zero();
  2212. Vector4.NormalizeToRef(vector, result);
  2213. return result;
  2214. };
  2215. /**
  2216. * Updates the passed vector "result" from the normalization of the passed one.
  2217. */
  2218. Vector4.NormalizeToRef = function (vector, result) {
  2219. result.copyFrom(vector);
  2220. result.normalize();
  2221. };
  2222. Vector4.Minimize = function (left, right) {
  2223. var min = left.clone();
  2224. min.MinimizeInPlace(right);
  2225. return min;
  2226. };
  2227. Vector4.Maximize = function (left, right) {
  2228. var max = left.clone();
  2229. max.MaximizeInPlace(right);
  2230. return max;
  2231. };
  2232. /**
  2233. * Returns the distance (float) between the vectors "value1" and "value2".
  2234. */
  2235. Vector4.Distance = function (value1, value2) {
  2236. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2237. };
  2238. /**
  2239. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2240. */
  2241. Vector4.DistanceSquared = function (value1, value2) {
  2242. var x = value1.x - value2.x;
  2243. var y = value1.y - value2.y;
  2244. var z = value1.z - value2.z;
  2245. var w = value1.w - value2.w;
  2246. return (x * x) + (y * y) + (z * z) + (w * w);
  2247. };
  2248. /**
  2249. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2250. */
  2251. Vector4.Center = function (value1, value2) {
  2252. var center = value1.add(value2);
  2253. center.scaleInPlace(0.5);
  2254. return center;
  2255. };
  2256. /**
  2257. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2258. * This methods computes transformed normalized direction vectors only.
  2259. */
  2260. Vector4.TransformNormal = function (vector, transformation) {
  2261. var result = Vector4.Zero();
  2262. Vector4.TransformNormalToRef(vector, transformation, result);
  2263. return result;
  2264. };
  2265. /**
  2266. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2267. * This methods computes transformed normalized direction vectors only.
  2268. */
  2269. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2270. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2271. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2272. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2273. result.x = x;
  2274. result.y = y;
  2275. result.z = z;
  2276. result.w = vector.w;
  2277. };
  2278. /**
  2279. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2280. * This methods computes transformed normalized direction vectors only.
  2281. */
  2282. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2283. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2284. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2285. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2286. result.w = w;
  2287. };
  2288. return Vector4;
  2289. }());
  2290. BABYLON.Vector4 = Vector4;
  2291. var Size = /** @class */ (function () {
  2292. /**
  2293. * Creates a Size object from the passed width and height (floats).
  2294. */
  2295. function Size(width, height) {
  2296. this.width = width;
  2297. this.height = height;
  2298. }
  2299. // Returns a string with the Size width and height.
  2300. Size.prototype.toString = function () {
  2301. return "{W: " + this.width + ", H: " + this.height + "}";
  2302. };
  2303. /**
  2304. * Returns the string "Size"
  2305. */
  2306. Size.prototype.getClassName = function () {
  2307. return "Size";
  2308. };
  2309. /**
  2310. * Returns the Size hash code.
  2311. */
  2312. Size.prototype.getHashCode = function () {
  2313. var hash = this.width || 0;
  2314. hash = (hash * 397) ^ (this.height || 0);
  2315. return hash;
  2316. };
  2317. /**
  2318. * Updates the current size from the passed one.
  2319. * Returns the updated Size.
  2320. */
  2321. Size.prototype.copyFrom = function (src) {
  2322. this.width = src.width;
  2323. this.height = src.height;
  2324. };
  2325. /**
  2326. * Updates in place the current Size from the passed floats.
  2327. * Returns the updated Size.
  2328. */
  2329. Size.prototype.copyFromFloats = function (width, height) {
  2330. this.width = width;
  2331. this.height = height;
  2332. return this;
  2333. };
  2334. /**
  2335. * Updates in place the current Size from the passed floats.
  2336. * Returns the updated Size.
  2337. */
  2338. Size.prototype.set = function (width, height) {
  2339. return this.copyFromFloats(width, height);
  2340. };
  2341. /**
  2342. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2343. */
  2344. Size.prototype.multiplyByFloats = function (w, h) {
  2345. return new Size(this.width * w, this.height * h);
  2346. };
  2347. /**
  2348. * Returns a new Size copied from the passed one.
  2349. */
  2350. Size.prototype.clone = function () {
  2351. return new Size(this.width, this.height);
  2352. };
  2353. /**
  2354. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2355. */
  2356. Size.prototype.equals = function (other) {
  2357. if (!other) {
  2358. return false;
  2359. }
  2360. return (this.width === other.width) && (this.height === other.height);
  2361. };
  2362. Object.defineProperty(Size.prototype, "surface", {
  2363. /**
  2364. * Returns the surface of the Size : width * height (float).
  2365. */
  2366. get: function () {
  2367. return this.width * this.height;
  2368. },
  2369. enumerable: true,
  2370. configurable: true
  2371. });
  2372. /**
  2373. * Returns a new Size set to (0.0, 0.0)
  2374. */
  2375. Size.Zero = function () {
  2376. return new Size(0.0, 0.0);
  2377. };
  2378. /**
  2379. * Returns a new Size set as the addition result of the current Size and the passed one.
  2380. */
  2381. Size.prototype.add = function (otherSize) {
  2382. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2383. return r;
  2384. };
  2385. /**
  2386. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2387. */
  2388. Size.prototype.subtract = function (otherSize) {
  2389. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2390. return r;
  2391. };
  2392. /**
  2393. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2394. */
  2395. Size.Lerp = function (start, end, amount) {
  2396. var w = start.width + ((end.width - start.width) * amount);
  2397. var h = start.height + ((end.height - start.height) * amount);
  2398. return new Size(w, h);
  2399. };
  2400. return Size;
  2401. }());
  2402. BABYLON.Size = Size;
  2403. var Quaternion = /** @class */ (function () {
  2404. /**
  2405. * Creates a new Quaternion from the passed floats.
  2406. */
  2407. function Quaternion(x, y, z, w) {
  2408. if (x === void 0) { x = 0.0; }
  2409. if (y === void 0) { y = 0.0; }
  2410. if (z === void 0) { z = 0.0; }
  2411. if (w === void 0) { w = 1.0; }
  2412. this.x = x;
  2413. this.y = y;
  2414. this.z = z;
  2415. this.w = w;
  2416. }
  2417. /**
  2418. * Returns a string with the Quaternion coordinates.
  2419. */
  2420. Quaternion.prototype.toString = function () {
  2421. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2422. };
  2423. /**
  2424. * Returns the string "Quaternion".
  2425. */
  2426. Quaternion.prototype.getClassName = function () {
  2427. return "Quaternion";
  2428. };
  2429. /**
  2430. * Returns the Quaternion hash code.
  2431. */
  2432. Quaternion.prototype.getHashCode = function () {
  2433. var hash = this.x || 0;
  2434. hash = (hash * 397) ^ (this.y || 0);
  2435. hash = (hash * 397) ^ (this.z || 0);
  2436. hash = (hash * 397) ^ (this.w || 0);
  2437. return hash;
  2438. };
  2439. /**
  2440. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2441. */
  2442. Quaternion.prototype.asArray = function () {
  2443. return [this.x, this.y, this.z, this.w];
  2444. };
  2445. /**
  2446. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2447. */
  2448. Quaternion.prototype.equals = function (otherQuaternion) {
  2449. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2450. };
  2451. /**
  2452. * Returns a new Quaternion copied from the current one.
  2453. */
  2454. Quaternion.prototype.clone = function () {
  2455. return new Quaternion(this.x, this.y, this.z, this.w);
  2456. };
  2457. /**
  2458. * Updates the current Quaternion from the passed one coordinates.
  2459. * Returns the updated Quaterion.
  2460. */
  2461. Quaternion.prototype.copyFrom = function (other) {
  2462. this.x = other.x;
  2463. this.y = other.y;
  2464. this.z = other.z;
  2465. this.w = other.w;
  2466. return this;
  2467. };
  2468. /**
  2469. * Updates the current Quaternion from the passed float coordinates.
  2470. * Returns the updated Quaterion.
  2471. */
  2472. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2473. this.x = x;
  2474. this.y = y;
  2475. this.z = z;
  2476. this.w = w;
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed float coordinates.
  2481. * Returns the updated Quaterion.
  2482. */
  2483. Quaternion.prototype.set = function (x, y, z, w) {
  2484. return this.copyFromFloats(x, y, z, w);
  2485. };
  2486. /**
  2487. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2488. */
  2489. Quaternion.prototype.add = function (other) {
  2490. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2491. };
  2492. /**
  2493. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2494. */
  2495. Quaternion.prototype.subtract = function (other) {
  2496. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2497. };
  2498. /**
  2499. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2500. */
  2501. Quaternion.prototype.scale = function (value) {
  2502. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2503. };
  2504. /**
  2505. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2506. */
  2507. Quaternion.prototype.multiply = function (q1) {
  2508. var result = new Quaternion(0, 0, 0, 1.0);
  2509. this.multiplyToRef(q1, result);
  2510. return result;
  2511. };
  2512. /**
  2513. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2517. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2518. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2519. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2520. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2521. result.copyFromFloats(x, y, z, w);
  2522. return this;
  2523. };
  2524. /**
  2525. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2526. * Returns the updated Quaternion.
  2527. */
  2528. Quaternion.prototype.multiplyInPlace = function (q1) {
  2529. this.multiplyToRef(q1, this);
  2530. return this;
  2531. };
  2532. /**
  2533. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2534. * Returns the current Quaternion.
  2535. */
  2536. Quaternion.prototype.conjugateToRef = function (ref) {
  2537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2538. return this;
  2539. };
  2540. /**
  2541. * Conjugates in place the current Quaternion.
  2542. * Returns the updated Quaternion.
  2543. */
  2544. Quaternion.prototype.conjugateInPlace = function () {
  2545. this.x *= -1;
  2546. this.y *= -1;
  2547. this.z *= -1;
  2548. return this;
  2549. };
  2550. /**
  2551. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2552. */
  2553. Quaternion.prototype.conjugate = function () {
  2554. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2555. return result;
  2556. };
  2557. /**
  2558. * Returns the Quaternion length (float).
  2559. */
  2560. Quaternion.prototype.length = function () {
  2561. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2562. };
  2563. /**
  2564. * Normalize in place the current Quaternion.
  2565. * Returns the updated Quaternion.
  2566. */
  2567. Quaternion.prototype.normalize = function () {
  2568. var length = 1.0 / this.length();
  2569. this.x *= length;
  2570. this.y *= length;
  2571. this.z *= length;
  2572. this.w *= length;
  2573. return this;
  2574. };
  2575. /**
  2576. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2577. */
  2578. Quaternion.prototype.toEulerAngles = function (order) {
  2579. if (order === void 0) { order = "YZX"; }
  2580. var result = Vector3.Zero();
  2581. this.toEulerAnglesToRef(result, order);
  2582. return result;
  2583. };
  2584. /**
  2585. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2586. * Returns the current Quaternion.
  2587. */
  2588. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2589. if (order === void 0) { order = "YZX"; }
  2590. var qz = this.z;
  2591. var qx = this.x;
  2592. var qy = this.y;
  2593. var qw = this.w;
  2594. var sqw = qw * qw;
  2595. var sqz = qz * qz;
  2596. var sqx = qx * qx;
  2597. var sqy = qy * qy;
  2598. var zAxisY = qy * qz - qx * qw;
  2599. var limit = .4999999;
  2600. if (zAxisY < -limit) {
  2601. result.y = 2 * Math.atan2(qy, qw);
  2602. result.x = Math.PI / 2;
  2603. result.z = 0;
  2604. }
  2605. else if (zAxisY > limit) {
  2606. result.y = 2 * Math.atan2(qy, qw);
  2607. result.x = -Math.PI / 2;
  2608. result.z = 0;
  2609. }
  2610. else {
  2611. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2612. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2613. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2614. }
  2615. return this;
  2616. };
  2617. /**
  2618. * Updates the passed rotation matrix with the current Quaternion values.
  2619. * Returns the current Quaternion.
  2620. */
  2621. Quaternion.prototype.toRotationMatrix = function (result) {
  2622. var xx = this.x * this.x;
  2623. var yy = this.y * this.y;
  2624. var zz = this.z * this.z;
  2625. var xy = this.x * this.y;
  2626. var zw = this.z * this.w;
  2627. var zx = this.z * this.x;
  2628. var yw = this.y * this.w;
  2629. var yz = this.y * this.z;
  2630. var xw = this.x * this.w;
  2631. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2632. result.m[1] = 2.0 * (xy + zw);
  2633. result.m[2] = 2.0 * (zx - yw);
  2634. result.m[3] = 0;
  2635. result.m[4] = 2.0 * (xy - zw);
  2636. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2637. result.m[6] = 2.0 * (yz + xw);
  2638. result.m[7] = 0;
  2639. result.m[8] = 2.0 * (zx + yw);
  2640. result.m[9] = 2.0 * (yz - xw);
  2641. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2642. result.m[11] = 0;
  2643. result.m[12] = 0;
  2644. result.m[13] = 0;
  2645. result.m[14] = 0;
  2646. result.m[15] = 1.0;
  2647. result._markAsUpdated();
  2648. return this;
  2649. };
  2650. /**
  2651. * Updates the current Quaternion from the passed rotation matrix values.
  2652. * Returns the updated Quaternion.
  2653. */
  2654. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2655. Quaternion.FromRotationMatrixToRef(matrix, this);
  2656. return this;
  2657. };
  2658. // Statics
  2659. /**
  2660. * Returns a new Quaternion set from the passed rotation matrix values.
  2661. */
  2662. Quaternion.FromRotationMatrix = function (matrix) {
  2663. var result = new Quaternion();
  2664. Quaternion.FromRotationMatrixToRef(matrix, result);
  2665. return result;
  2666. };
  2667. /**
  2668. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2669. */
  2670. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2671. var data = matrix.m;
  2672. var m11 = data[0], m12 = data[4], m13 = data[8];
  2673. var m21 = data[1], m22 = data[5], m23 = data[9];
  2674. var m31 = data[2], m32 = data[6], m33 = data[10];
  2675. var trace = m11 + m22 + m33;
  2676. var s;
  2677. if (trace > 0) {
  2678. s = 0.5 / Math.sqrt(trace + 1.0);
  2679. result.w = 0.25 / s;
  2680. result.x = (m32 - m23) * s;
  2681. result.y = (m13 - m31) * s;
  2682. result.z = (m21 - m12) * s;
  2683. }
  2684. else if (m11 > m22 && m11 > m33) {
  2685. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2686. result.w = (m32 - m23) / s;
  2687. result.x = 0.25 * s;
  2688. result.y = (m12 + m21) / s;
  2689. result.z = (m13 + m31) / s;
  2690. }
  2691. else if (m22 > m33) {
  2692. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2693. result.w = (m13 - m31) / s;
  2694. result.x = (m12 + m21) / s;
  2695. result.y = 0.25 * s;
  2696. result.z = (m23 + m32) / s;
  2697. }
  2698. else {
  2699. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2700. result.w = (m21 - m12) / s;
  2701. result.x = (m13 + m31) / s;
  2702. result.y = (m23 + m32) / s;
  2703. result.z = 0.25 * s;
  2704. }
  2705. };
  2706. /**
  2707. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2708. */
  2709. Quaternion.Zero = function () {
  2710. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2711. };
  2712. /**
  2713. * Returns a new Quaternion as the inverted current Quaternion.
  2714. */
  2715. Quaternion.Inverse = function (q) {
  2716. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2717. };
  2718. /**
  2719. * Returns the identity Quaternion.
  2720. */
  2721. Quaternion.Identity = function () {
  2722. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2723. };
  2724. Quaternion.IsIdentity = function (quaternion) {
  2725. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2726. };
  2727. /**
  2728. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2729. */
  2730. Quaternion.RotationAxis = function (axis, angle) {
  2731. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2732. };
  2733. /**
  2734. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2735. */
  2736. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2737. var sin = Math.sin(angle / 2);
  2738. axis.normalize();
  2739. result.w = Math.cos(angle / 2);
  2740. result.x = axis.x * sin;
  2741. result.y = axis.y * sin;
  2742. result.z = axis.z * sin;
  2743. return result;
  2744. };
  2745. /**
  2746. * Retuns a new Quaternion set from the starting index of the passed array.
  2747. */
  2748. Quaternion.FromArray = function (array, offset) {
  2749. if (!offset) {
  2750. offset = 0;
  2751. }
  2752. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2753. };
  2754. /**
  2755. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2756. */
  2757. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2758. var q = new Quaternion();
  2759. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2760. return q;
  2761. };
  2762. /**
  2763. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2764. */
  2765. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2766. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2767. var halfRoll = roll * 0.5;
  2768. var halfPitch = pitch * 0.5;
  2769. var halfYaw = yaw * 0.5;
  2770. var sinRoll = Math.sin(halfRoll);
  2771. var cosRoll = Math.cos(halfRoll);
  2772. var sinPitch = Math.sin(halfPitch);
  2773. var cosPitch = Math.cos(halfPitch);
  2774. var sinYaw = Math.sin(halfYaw);
  2775. var cosYaw = Math.cos(halfYaw);
  2776. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2777. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2778. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2779. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2780. };
  2781. /**
  2782. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2783. */
  2784. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2785. var result = new Quaternion();
  2786. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2787. return result;
  2788. };
  2789. /**
  2790. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2791. */
  2792. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2793. // Produces a quaternion from Euler angles in the z-x-z orientation
  2794. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2795. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2796. var halfBeta = beta * 0.5;
  2797. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2798. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2799. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2800. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2801. };
  2802. /**
  2803. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2804. * cf to Vector3.RotationFromAxis() documentation.
  2805. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2806. */
  2807. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2808. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2809. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2810. return quat;
  2811. };
  2812. /**
  2813. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2814. * cf to Vector3.RotationFromAxis() documentation.
  2815. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2816. */
  2817. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2818. var rotMat = MathTmp.Matrix[0];
  2819. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2820. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2821. };
  2822. Quaternion.Slerp = function (left, right, amount) {
  2823. var result = Quaternion.Identity();
  2824. Quaternion.SlerpToRef(left, right, amount, result);
  2825. return result;
  2826. };
  2827. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2828. var num2;
  2829. var num3;
  2830. var num = amount;
  2831. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2832. var flag = false;
  2833. if (num4 < 0) {
  2834. flag = true;
  2835. num4 = -num4;
  2836. }
  2837. if (num4 > 0.999999) {
  2838. num3 = 1 - num;
  2839. num2 = flag ? -num : num;
  2840. }
  2841. else {
  2842. var num5 = Math.acos(num4);
  2843. var num6 = (1.0 / Math.sin(num5));
  2844. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2845. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2846. }
  2847. result.x = (num3 * left.x) + (num2 * right.x);
  2848. result.y = (num3 * left.y) + (num2 * right.y);
  2849. result.z = (num3 * left.z) + (num2 * right.z);
  2850. result.w = (num3 * left.w) + (num2 * right.w);
  2851. };
  2852. /**
  2853. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2854. */
  2855. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2856. var squared = amount * amount;
  2857. var cubed = amount * squared;
  2858. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2859. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2860. var part3 = (cubed - (2.0 * squared)) + amount;
  2861. var part4 = cubed - squared;
  2862. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2863. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2864. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2865. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2866. return new Quaternion(x, y, z, w);
  2867. };
  2868. return Quaternion;
  2869. }());
  2870. BABYLON.Quaternion = Quaternion;
  2871. var Matrix = /** @class */ (function () {
  2872. function Matrix() {
  2873. this._isIdentity = false;
  2874. this._isIdentityDirty = true;
  2875. this.m = new Float32Array(16);
  2876. this._markAsUpdated();
  2877. }
  2878. Matrix.prototype._markAsUpdated = function () {
  2879. this.updateFlag = Matrix._updateFlagSeed++;
  2880. this._isIdentityDirty = true;
  2881. };
  2882. // Properties
  2883. /**
  2884. * Boolean : True is the matrix is the identity matrix
  2885. */
  2886. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2887. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2888. if (this._isIdentityDirty) {
  2889. this._isIdentityDirty = false;
  2890. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2891. this._isIdentity = false;
  2892. }
  2893. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2894. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2895. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2896. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2897. this._isIdentity = false;
  2898. }
  2899. else {
  2900. this._isIdentity = true;
  2901. }
  2902. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2903. this._isIdentity = false;
  2904. }
  2905. }
  2906. return this._isIdentity;
  2907. };
  2908. /**
  2909. * Returns the matrix determinant (float).
  2910. */
  2911. Matrix.prototype.determinant = function () {
  2912. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2913. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2914. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2915. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2916. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2917. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2918. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2919. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2920. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2921. };
  2922. // Methods
  2923. /**
  2924. * Returns the matrix underlying array.
  2925. */
  2926. Matrix.prototype.toArray = function () {
  2927. return this.m;
  2928. };
  2929. /**
  2930. * Returns the matrix underlying array.
  2931. */
  2932. Matrix.prototype.asArray = function () {
  2933. return this.toArray();
  2934. };
  2935. /**
  2936. * Inverts in place the Matrix.
  2937. * Returns the Matrix inverted.
  2938. */
  2939. Matrix.prototype.invert = function () {
  2940. this.invertToRef(this);
  2941. return this;
  2942. };
  2943. /**
  2944. * Sets all the matrix elements to zero.
  2945. * Returns the Matrix.
  2946. */
  2947. Matrix.prototype.reset = function () {
  2948. for (var index = 0; index < 16; index++) {
  2949. this.m[index] = 0.0;
  2950. }
  2951. this._markAsUpdated();
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2956. */
  2957. Matrix.prototype.add = function (other) {
  2958. var result = new Matrix();
  2959. this.addToRef(other, result);
  2960. return result;
  2961. };
  2962. /**
  2963. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2964. * Returns the Matrix.
  2965. */
  2966. Matrix.prototype.addToRef = function (other, result) {
  2967. for (var index = 0; index < 16; index++) {
  2968. result.m[index] = this.m[index] + other.m[index];
  2969. }
  2970. result._markAsUpdated();
  2971. return this;
  2972. };
  2973. /**
  2974. * Adds in place the passed matrix to the current Matrix.
  2975. * Returns the updated Matrix.
  2976. */
  2977. Matrix.prototype.addToSelf = function (other) {
  2978. for (var index = 0; index < 16; index++) {
  2979. this.m[index] += other.m[index];
  2980. }
  2981. this._markAsUpdated();
  2982. return this;
  2983. };
  2984. /**
  2985. * Sets the passed matrix with the current inverted Matrix.
  2986. * Returns the unmodified current Matrix.
  2987. */
  2988. Matrix.prototype.invertToRef = function (other) {
  2989. var l1 = this.m[0];
  2990. var l2 = this.m[1];
  2991. var l3 = this.m[2];
  2992. var l4 = this.m[3];
  2993. var l5 = this.m[4];
  2994. var l6 = this.m[5];
  2995. var l7 = this.m[6];
  2996. var l8 = this.m[7];
  2997. var l9 = this.m[8];
  2998. var l10 = this.m[9];
  2999. var l11 = this.m[10];
  3000. var l12 = this.m[11];
  3001. var l13 = this.m[12];
  3002. var l14 = this.m[13];
  3003. var l15 = this.m[14];
  3004. var l16 = this.m[15];
  3005. var l17 = (l11 * l16) - (l12 * l15);
  3006. var l18 = (l10 * l16) - (l12 * l14);
  3007. var l19 = (l10 * l15) - (l11 * l14);
  3008. var l20 = (l9 * l16) - (l12 * l13);
  3009. var l21 = (l9 * l15) - (l11 * l13);
  3010. var l22 = (l9 * l14) - (l10 * l13);
  3011. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3012. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3013. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3014. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3015. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3016. var l28 = (l7 * l16) - (l8 * l15);
  3017. var l29 = (l6 * l16) - (l8 * l14);
  3018. var l30 = (l6 * l15) - (l7 * l14);
  3019. var l31 = (l5 * l16) - (l8 * l13);
  3020. var l32 = (l5 * l15) - (l7 * l13);
  3021. var l33 = (l5 * l14) - (l6 * l13);
  3022. var l34 = (l7 * l12) - (l8 * l11);
  3023. var l35 = (l6 * l12) - (l8 * l10);
  3024. var l36 = (l6 * l11) - (l7 * l10);
  3025. var l37 = (l5 * l12) - (l8 * l9);
  3026. var l38 = (l5 * l11) - (l7 * l9);
  3027. var l39 = (l5 * l10) - (l6 * l9);
  3028. other.m[0] = l23 * l27;
  3029. other.m[4] = l24 * l27;
  3030. other.m[8] = l25 * l27;
  3031. other.m[12] = l26 * l27;
  3032. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3033. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3034. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3035. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3036. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3037. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3038. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3039. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3040. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3041. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3042. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3043. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3044. other._markAsUpdated();
  3045. return this;
  3046. };
  3047. /**
  3048. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3049. * Returns the updated Matrix.
  3050. */
  3051. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3052. this.m[12] = x;
  3053. this.m[13] = y;
  3054. this.m[14] = z;
  3055. this._markAsUpdated();
  3056. return this;
  3057. };
  3058. /**
  3059. * Inserts the translation vector in the current Matrix.
  3060. * Returns the updated Matrix.
  3061. */
  3062. Matrix.prototype.setTranslation = function (vector3) {
  3063. this.m[12] = vector3.x;
  3064. this.m[13] = vector3.y;
  3065. this.m[14] = vector3.z;
  3066. this._markAsUpdated();
  3067. return this;
  3068. };
  3069. /**
  3070. * Returns a new Vector3 as the extracted translation from the Matrix.
  3071. */
  3072. Matrix.prototype.getTranslation = function () {
  3073. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3074. };
  3075. /**
  3076. * Fill a Vector3 with the extracted translation from the Matrix.
  3077. */
  3078. Matrix.prototype.getTranslationToRef = function (result) {
  3079. result.x = this.m[12];
  3080. result.y = this.m[13];
  3081. result.z = this.m[14];
  3082. return this;
  3083. };
  3084. /**
  3085. * Remove rotation and scaling part from the Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.removeRotationAndScaling = function () {
  3089. this.setRowFromFloats(0, 1, 0, 0, 0);
  3090. this.setRowFromFloats(1, 0, 1, 0, 0);
  3091. this.setRowFromFloats(2, 0, 0, 1, 0);
  3092. return this;
  3093. };
  3094. /**
  3095. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3096. */
  3097. Matrix.prototype.multiply = function (other) {
  3098. var result = new Matrix();
  3099. this.multiplyToRef(other, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Updates the current Matrix from the passed one values.
  3104. * Returns the updated Matrix.
  3105. */
  3106. Matrix.prototype.copyFrom = function (other) {
  3107. for (var index = 0; index < 16; index++) {
  3108. this.m[index] = other.m[index];
  3109. }
  3110. this._markAsUpdated();
  3111. return this;
  3112. };
  3113. /**
  3114. * Populates the passed array from the starting index with the Matrix values.
  3115. * Returns the Matrix.
  3116. */
  3117. Matrix.prototype.copyToArray = function (array, offset) {
  3118. if (offset === void 0) { offset = 0; }
  3119. for (var index = 0; index < 16; index++) {
  3120. array[offset + index] = this.m[index];
  3121. }
  3122. return this;
  3123. };
  3124. /**
  3125. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3126. */
  3127. Matrix.prototype.multiplyToRef = function (other, result) {
  3128. this.multiplyToArray(other, result.m, 0);
  3129. result._markAsUpdated();
  3130. return this;
  3131. };
  3132. /**
  3133. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3134. */
  3135. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3136. var tm0 = this.m[0];
  3137. var tm1 = this.m[1];
  3138. var tm2 = this.m[2];
  3139. var tm3 = this.m[3];
  3140. var tm4 = this.m[4];
  3141. var tm5 = this.m[5];
  3142. var tm6 = this.m[6];
  3143. var tm7 = this.m[7];
  3144. var tm8 = this.m[8];
  3145. var tm9 = this.m[9];
  3146. var tm10 = this.m[10];
  3147. var tm11 = this.m[11];
  3148. var tm12 = this.m[12];
  3149. var tm13 = this.m[13];
  3150. var tm14 = this.m[14];
  3151. var tm15 = this.m[15];
  3152. var om0 = other.m[0];
  3153. var om1 = other.m[1];
  3154. var om2 = other.m[2];
  3155. var om3 = other.m[3];
  3156. var om4 = other.m[4];
  3157. var om5 = other.m[5];
  3158. var om6 = other.m[6];
  3159. var om7 = other.m[7];
  3160. var om8 = other.m[8];
  3161. var om9 = other.m[9];
  3162. var om10 = other.m[10];
  3163. var om11 = other.m[11];
  3164. var om12 = other.m[12];
  3165. var om13 = other.m[13];
  3166. var om14 = other.m[14];
  3167. var om15 = other.m[15];
  3168. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3169. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3170. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3171. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3172. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3173. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3174. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3175. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3176. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3177. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3178. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3179. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3180. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3181. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3182. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3183. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3184. return this;
  3185. };
  3186. /**
  3187. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3188. */
  3189. Matrix.prototype.equals = function (value) {
  3190. return value &&
  3191. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3192. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3193. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3194. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3195. };
  3196. /**
  3197. * Returns a new Matrix from the current Matrix.
  3198. */
  3199. Matrix.prototype.clone = function () {
  3200. 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]);
  3201. };
  3202. /**
  3203. * Returns the string "Matrix"
  3204. */
  3205. Matrix.prototype.getClassName = function () {
  3206. return "Matrix";
  3207. };
  3208. /**
  3209. * Returns the Matrix hash code.
  3210. */
  3211. Matrix.prototype.getHashCode = function () {
  3212. var hash = this.m[0] || 0;
  3213. for (var i = 1; i < 16; i++) {
  3214. hash = (hash * 397) ^ (this.m[i] || 0);
  3215. }
  3216. return hash;
  3217. };
  3218. /**
  3219. * Decomposes the current Matrix into :
  3220. * - a scale vector3 passed as a reference to update,
  3221. * - a rotation quaternion passed as a reference to update,
  3222. * - a translation vector3 passed as a reference to update.
  3223. * Returns the boolean `true`.
  3224. */
  3225. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3226. translation.x = this.m[12];
  3227. translation.y = this.m[13];
  3228. translation.z = this.m[14];
  3229. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3230. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3231. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3232. if (this.determinant() <= 0) {
  3233. scale.y *= -1;
  3234. }
  3235. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3236. rotation.x = 0;
  3237. rotation.y = 0;
  3238. rotation.z = 0;
  3239. rotation.w = 1;
  3240. return false;
  3241. }
  3242. 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]);
  3243. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3244. return true;
  3245. };
  3246. /**
  3247. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3248. */
  3249. Matrix.prototype.getRotationMatrix = function () {
  3250. var result = Matrix.Identity();
  3251. this.getRotationMatrixToRef(result);
  3252. return result;
  3253. };
  3254. /**
  3255. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3256. * Returns the current Matrix.
  3257. */
  3258. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3259. var m = this.m;
  3260. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3261. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3262. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3263. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3264. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3265. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3266. 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);
  3267. return this;
  3268. };
  3269. // Statics
  3270. /**
  3271. * Returns a new Matrix set from the starting index of the passed array.
  3272. */
  3273. Matrix.FromArray = function (array, offset) {
  3274. var result = new Matrix();
  3275. if (!offset) {
  3276. offset = 0;
  3277. }
  3278. Matrix.FromArrayToRef(array, offset, result);
  3279. return result;
  3280. };
  3281. /**
  3282. * Sets the passed "result" matrix from the starting index of the passed array.
  3283. */
  3284. Matrix.FromArrayToRef = function (array, offset, result) {
  3285. for (var index = 0; index < 16; index++) {
  3286. result.m[index] = array[index + offset];
  3287. }
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3292. */
  3293. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3294. for (var index = 0; index < 16; index++) {
  3295. result.m[index] = array[index + offset] * scale;
  3296. }
  3297. result._markAsUpdated();
  3298. };
  3299. /**
  3300. * Sets the passed matrix "result" with the 16 passed floats.
  3301. */
  3302. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3303. result.m[0] = initialM11;
  3304. result.m[1] = initialM12;
  3305. result.m[2] = initialM13;
  3306. result.m[3] = initialM14;
  3307. result.m[4] = initialM21;
  3308. result.m[5] = initialM22;
  3309. result.m[6] = initialM23;
  3310. result.m[7] = initialM24;
  3311. result.m[8] = initialM31;
  3312. result.m[9] = initialM32;
  3313. result.m[10] = initialM33;
  3314. result.m[11] = initialM34;
  3315. result.m[12] = initialM41;
  3316. result.m[13] = initialM42;
  3317. result.m[14] = initialM43;
  3318. result.m[15] = initialM44;
  3319. result._markAsUpdated();
  3320. };
  3321. /**
  3322. * Returns the index-th row of the current matrix as a new Vector4.
  3323. */
  3324. Matrix.prototype.getRow = function (index) {
  3325. if (index < 0 || index > 3) {
  3326. return null;
  3327. }
  3328. var i = index * 4;
  3329. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3330. };
  3331. /**
  3332. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3333. * Returns the updated Matrix.
  3334. */
  3335. Matrix.prototype.setRow = function (index, row) {
  3336. if (index < 0 || index > 3) {
  3337. return this;
  3338. }
  3339. var i = index * 4;
  3340. this.m[i + 0] = row.x;
  3341. this.m[i + 1] = row.y;
  3342. this.m[i + 2] = row.z;
  3343. this.m[i + 3] = row.w;
  3344. this._markAsUpdated();
  3345. return this;
  3346. };
  3347. /**
  3348. * Compute the transpose of the matrix.
  3349. * Returns a new Matrix.
  3350. */
  3351. Matrix.prototype.transpose = function () {
  3352. return Matrix.Transpose(this);
  3353. };
  3354. /**
  3355. * Compute the transpose of the matrix.
  3356. * Returns the current matrix.
  3357. */
  3358. Matrix.prototype.transposeToRef = function (result) {
  3359. Matrix.TransposeToRef(this, result);
  3360. return this;
  3361. };
  3362. /**
  3363. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3364. * Returns the updated Matrix.
  3365. */
  3366. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3367. if (index < 0 || index > 3) {
  3368. return this;
  3369. }
  3370. var i = index * 4;
  3371. this.m[i + 0] = x;
  3372. this.m[i + 1] = y;
  3373. this.m[i + 2] = z;
  3374. this.m[i + 3] = w;
  3375. this._markAsUpdated();
  3376. return this;
  3377. };
  3378. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3379. /**
  3380. * Static identity matrix to be used as readonly matrix
  3381. * Must not be updated.
  3382. */
  3383. get: function () {
  3384. return Matrix._identityReadOnly;
  3385. },
  3386. enumerable: true,
  3387. configurable: true
  3388. });
  3389. /**
  3390. * Returns a new Matrix set from the 16 passed floats.
  3391. */
  3392. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3393. var result = new Matrix();
  3394. result.m[0] = initialM11;
  3395. result.m[1] = initialM12;
  3396. result.m[2] = initialM13;
  3397. result.m[3] = initialM14;
  3398. result.m[4] = initialM21;
  3399. result.m[5] = initialM22;
  3400. result.m[6] = initialM23;
  3401. result.m[7] = initialM24;
  3402. result.m[8] = initialM31;
  3403. result.m[9] = initialM32;
  3404. result.m[10] = initialM33;
  3405. result.m[11] = initialM34;
  3406. result.m[12] = initialM41;
  3407. result.m[13] = initialM42;
  3408. result.m[14] = initialM43;
  3409. result.m[15] = initialM44;
  3410. return result;
  3411. };
  3412. /**
  3413. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3414. */
  3415. Matrix.Compose = function (scale, rotation, translation) {
  3416. var result = Matrix.Identity();
  3417. Matrix.ComposeToRef(scale, rotation, translation, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3422. */
  3423. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3424. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3425. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3426. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3427. result.setTranslation(translation);
  3428. };
  3429. /**
  3430. * Returns a new indentity Matrix.
  3431. */
  3432. Matrix.Identity = function () {
  3433. 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);
  3434. };
  3435. /**
  3436. * Sets the passed "result" as an identity matrix.
  3437. */
  3438. Matrix.IdentityToRef = function (result) {
  3439. 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);
  3440. };
  3441. /**
  3442. * Returns a new zero Matrix.
  3443. */
  3444. Matrix.Zero = function () {
  3445. 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);
  3446. };
  3447. /**
  3448. * Returns a new rotation matrix for "angle" radians around the X axis.
  3449. */
  3450. Matrix.RotationX = function (angle) {
  3451. var result = new Matrix();
  3452. Matrix.RotationXToRef(angle, result);
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix as the passed inverted one.
  3457. */
  3458. Matrix.Invert = function (source) {
  3459. var result = new Matrix();
  3460. source.invertToRef(result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3465. */
  3466. Matrix.RotationXToRef = function (angle, result) {
  3467. var s = Math.sin(angle);
  3468. var c = Math.cos(angle);
  3469. result.m[0] = 1.0;
  3470. result.m[15] = 1.0;
  3471. result.m[5] = c;
  3472. result.m[10] = c;
  3473. result.m[9] = -s;
  3474. result.m[6] = s;
  3475. result.m[1] = 0.0;
  3476. result.m[2] = 0.0;
  3477. result.m[3] = 0.0;
  3478. result.m[4] = 0.0;
  3479. result.m[7] = 0.0;
  3480. result.m[8] = 0.0;
  3481. result.m[11] = 0.0;
  3482. result.m[12] = 0.0;
  3483. result.m[13] = 0.0;
  3484. result.m[14] = 0.0;
  3485. result._markAsUpdated();
  3486. };
  3487. /**
  3488. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3489. */
  3490. Matrix.RotationY = function (angle) {
  3491. var result = new Matrix();
  3492. Matrix.RotationYToRef(angle, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3497. */
  3498. Matrix.RotationYToRef = function (angle, result) {
  3499. var s = Math.sin(angle);
  3500. var c = Math.cos(angle);
  3501. result.m[5] = 1.0;
  3502. result.m[15] = 1.0;
  3503. result.m[0] = c;
  3504. result.m[2] = -s;
  3505. result.m[8] = s;
  3506. result.m[10] = c;
  3507. result.m[1] = 0.0;
  3508. result.m[3] = 0.0;
  3509. result.m[4] = 0.0;
  3510. result.m[6] = 0.0;
  3511. result.m[7] = 0.0;
  3512. result.m[9] = 0.0;
  3513. result.m[11] = 0.0;
  3514. result.m[12] = 0.0;
  3515. result.m[13] = 0.0;
  3516. result.m[14] = 0.0;
  3517. result._markAsUpdated();
  3518. };
  3519. /**
  3520. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3521. */
  3522. Matrix.RotationZ = function (angle) {
  3523. var result = new Matrix();
  3524. Matrix.RotationZToRef(angle, result);
  3525. return result;
  3526. };
  3527. /**
  3528. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3529. */
  3530. Matrix.RotationZToRef = function (angle, result) {
  3531. var s = Math.sin(angle);
  3532. var c = Math.cos(angle);
  3533. result.m[10] = 1.0;
  3534. result.m[15] = 1.0;
  3535. result.m[0] = c;
  3536. result.m[1] = s;
  3537. result.m[4] = -s;
  3538. result.m[5] = c;
  3539. result.m[2] = 0.0;
  3540. result.m[3] = 0.0;
  3541. result.m[6] = 0.0;
  3542. result.m[7] = 0.0;
  3543. result.m[8] = 0.0;
  3544. result.m[9] = 0.0;
  3545. result.m[11] = 0.0;
  3546. result.m[12] = 0.0;
  3547. result.m[13] = 0.0;
  3548. result.m[14] = 0.0;
  3549. result._markAsUpdated();
  3550. };
  3551. /**
  3552. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3553. */
  3554. Matrix.RotationAxis = function (axis, angle) {
  3555. var result = Matrix.Zero();
  3556. Matrix.RotationAxisToRef(axis, angle, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3561. */
  3562. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3563. var s = Math.sin(-angle);
  3564. var c = Math.cos(-angle);
  3565. var c1 = 1 - c;
  3566. axis.normalize();
  3567. result.m[0] = (axis.x * axis.x) * c1 + c;
  3568. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3569. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3570. result.m[3] = 0.0;
  3571. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3572. result.m[5] = (axis.y * axis.y) * c1 + c;
  3573. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3574. result.m[7] = 0.0;
  3575. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3576. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3577. result.m[10] = (axis.z * axis.z) * c1 + c;
  3578. result.m[11] = 0.0;
  3579. result.m[15] = 1.0;
  3580. result._markAsUpdated();
  3581. };
  3582. /**
  3583. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3584. */
  3585. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3586. var result = new Matrix();
  3587. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3588. return result;
  3589. };
  3590. /**
  3591. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3592. */
  3593. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3594. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3595. this._tempQuaternion.toRotationMatrix(result);
  3596. };
  3597. /**
  3598. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3599. */
  3600. Matrix.Scaling = function (x, y, z) {
  3601. var result = Matrix.Zero();
  3602. Matrix.ScalingToRef(x, y, z, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3607. */
  3608. Matrix.ScalingToRef = function (x, y, z, result) {
  3609. result.m[0] = x;
  3610. result.m[1] = 0.0;
  3611. result.m[2] = 0.0;
  3612. result.m[3] = 0.0;
  3613. result.m[4] = 0.0;
  3614. result.m[5] = y;
  3615. result.m[6] = 0.0;
  3616. result.m[7] = 0.0;
  3617. result.m[8] = 0.0;
  3618. result.m[9] = 0.0;
  3619. result.m[10] = z;
  3620. result.m[11] = 0.0;
  3621. result.m[12] = 0.0;
  3622. result.m[13] = 0.0;
  3623. result.m[14] = 0.0;
  3624. result.m[15] = 1.0;
  3625. result._markAsUpdated();
  3626. };
  3627. /**
  3628. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3629. */
  3630. Matrix.Translation = function (x, y, z) {
  3631. var result = Matrix.Identity();
  3632. Matrix.TranslationToRef(x, y, z, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3637. */
  3638. Matrix.TranslationToRef = function (x, y, z, result) {
  3639. 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);
  3640. };
  3641. /**
  3642. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3643. */
  3644. Matrix.Lerp = function (startValue, endValue, gradient) {
  3645. var result = Matrix.Zero();
  3646. for (var index = 0; index < 16; index++) {
  3647. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3648. }
  3649. result._markAsUpdated();
  3650. return result;
  3651. };
  3652. /**
  3653. * Returns a new Matrix whose values are computed by :
  3654. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3655. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3656. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3657. */
  3658. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3659. var startScale = new Vector3(0, 0, 0);
  3660. var startRotation = new Quaternion();
  3661. var startTranslation = new Vector3(0, 0, 0);
  3662. startValue.decompose(startScale, startRotation, startTranslation);
  3663. var endScale = new Vector3(0, 0, 0);
  3664. var endRotation = new Quaternion();
  3665. var endTranslation = new Vector3(0, 0, 0);
  3666. endValue.decompose(endScale, endRotation, endTranslation);
  3667. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3668. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3669. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3670. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3671. };
  3672. /**
  3673. * 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".
  3674. * This methods works for a Left-Handed system.
  3675. */
  3676. Matrix.LookAtLH = function (eye, target, up) {
  3677. var result = Matrix.Zero();
  3678. Matrix.LookAtLHToRef(eye, target, up, result);
  3679. return result;
  3680. };
  3681. /**
  3682. * 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".
  3683. * This methods works for a Left-Handed system.
  3684. */
  3685. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3686. // Z axis
  3687. target.subtractToRef(eye, this._zAxis);
  3688. this._zAxis.normalize();
  3689. // X axis
  3690. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3691. if (this._xAxis.lengthSquared() === 0) {
  3692. this._xAxis.x = 1.0;
  3693. }
  3694. else {
  3695. this._xAxis.normalize();
  3696. }
  3697. // Y axis
  3698. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3699. this._yAxis.normalize();
  3700. // Eye angles
  3701. var ex = -Vector3.Dot(this._xAxis, eye);
  3702. var ey = -Vector3.Dot(this._yAxis, eye);
  3703. var ez = -Vector3.Dot(this._zAxis, eye);
  3704. 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);
  3705. };
  3706. /**
  3707. * 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".
  3708. * This methods works for a Right-Handed system.
  3709. */
  3710. Matrix.LookAtRH = function (eye, target, up) {
  3711. var result = Matrix.Zero();
  3712. Matrix.LookAtRHToRef(eye, target, up, result);
  3713. return result;
  3714. };
  3715. /**
  3716. * 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".
  3717. * This methods works for a Left-Handed system.
  3718. */
  3719. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3720. // Z axis
  3721. eye.subtractToRef(target, this._zAxis);
  3722. this._zAxis.normalize();
  3723. // X axis
  3724. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3725. if (this._xAxis.lengthSquared() === 0) {
  3726. this._xAxis.x = 1.0;
  3727. }
  3728. else {
  3729. this._xAxis.normalize();
  3730. }
  3731. // Y axis
  3732. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3733. this._yAxis.normalize();
  3734. // Eye angles
  3735. var ex = -Vector3.Dot(this._xAxis, eye);
  3736. var ey = -Vector3.Dot(this._yAxis, eye);
  3737. var ez = -Vector3.Dot(this._zAxis, eye);
  3738. 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);
  3739. };
  3740. /**
  3741. * 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.
  3742. */
  3743. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3744. var matrix = Matrix.Zero();
  3745. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3746. return matrix;
  3747. };
  3748. /**
  3749. * 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.
  3750. */
  3751. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3752. var n = znear;
  3753. var f = zfar;
  3754. var a = 2.0 / width;
  3755. var b = 2.0 / height;
  3756. var c = 2.0 / (f - n);
  3757. var d = -(f + n) / (f - n);
  3758. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3759. };
  3760. /**
  3761. * 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.
  3762. */
  3763. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3764. var matrix = Matrix.Zero();
  3765. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3766. return matrix;
  3767. };
  3768. /**
  3769. * 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.
  3770. */
  3771. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3772. var n = znear;
  3773. var f = zfar;
  3774. var a = 2.0 / (right - left);
  3775. var b = 2.0 / (top - bottom);
  3776. var c = 2.0 / (f - n);
  3777. var d = -(f + n) / (f - n);
  3778. var i0 = (left + right) / (left - right);
  3779. var i1 = (top + bottom) / (bottom - top);
  3780. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3781. };
  3782. /**
  3783. * 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.
  3784. */
  3785. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3786. var matrix = Matrix.Zero();
  3787. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3788. return matrix;
  3789. };
  3790. /**
  3791. * 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.
  3792. */
  3793. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3794. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3795. result.m[10] *= -1.0;
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. var n = znear;
  3803. var f = zfar;
  3804. var a = 2.0 * n / width;
  3805. var b = 2.0 * n / height;
  3806. var c = (f + n) / (f - n);
  3807. var d = -2.0 * f * n / (f - n);
  3808. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3809. return matrix;
  3810. };
  3811. /**
  3812. * 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.
  3813. */
  3814. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3815. var matrix = Matrix.Zero();
  3816. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3817. return matrix;
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3823. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3824. var n = znear;
  3825. var f = zfar;
  3826. var t = 1.0 / (Math.tan(fov * 0.5));
  3827. var a = isVerticalFovFixed ? (t / aspect) : t;
  3828. var b = isVerticalFovFixed ? t : (t * aspect);
  3829. var c = (f + n) / (f - n);
  3830. var d = -2.0 * f * n / (f - n);
  3831. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3832. };
  3833. /**
  3834. * 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.
  3835. */
  3836. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3837. var matrix = Matrix.Zero();
  3838. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3839. return matrix;
  3840. };
  3841. /**
  3842. * 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.
  3843. */
  3844. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3845. //alternatively this could be expressed as:
  3846. // m = PerspectiveFovLHToRef
  3847. // m[10] *= -1.0;
  3848. // m[11] *= -1.0;
  3849. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3850. var n = znear;
  3851. var f = zfar;
  3852. var t = 1.0 / (Math.tan(fov * 0.5));
  3853. var a = isVerticalFovFixed ? (t / aspect) : t;
  3854. var b = isVerticalFovFixed ? t : (t * aspect);
  3855. var c = -(f + n) / (f - n);
  3856. var d = -2 * f * n / (f - n);
  3857. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3858. };
  3859. /**
  3860. * 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.
  3861. */
  3862. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3863. if (rightHanded === void 0) { rightHanded = false; }
  3864. var rightHandedFactor = rightHanded ? -1 : 1;
  3865. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3866. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3867. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3868. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3869. var xScale = 2.0 / (leftTan + rightTan);
  3870. var yScale = 2.0 / (upTan + downTan);
  3871. result.m[0] = xScale;
  3872. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3873. result.m[5] = yScale;
  3874. result.m[6] = result.m[7] = 0.0;
  3875. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3876. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3877. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3878. result.m[10] = -zfar / (znear - zfar);
  3879. result.m[11] = 1.0 * rightHandedFactor;
  3880. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3881. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3882. // result.m[14] = (znear * zfar) / (znear - zfar);
  3883. result._markAsUpdated();
  3884. };
  3885. /**
  3886. * Returns the final transformation matrix : world * view * projection * viewport
  3887. */
  3888. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3889. var cw = viewport.width;
  3890. var ch = viewport.height;
  3891. var cx = viewport.x;
  3892. var cy = viewport.y;
  3893. 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);
  3894. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3895. };
  3896. /**
  3897. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3898. */
  3899. Matrix.GetAsMatrix2x2 = function (matrix) {
  3900. return new Float32Array([
  3901. matrix.m[0], matrix.m[1],
  3902. matrix.m[4], matrix.m[5]
  3903. ]);
  3904. };
  3905. /**
  3906. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3907. */
  3908. Matrix.GetAsMatrix3x3 = function (matrix) {
  3909. return new Float32Array([
  3910. matrix.m[0], matrix.m[1], matrix.m[2],
  3911. matrix.m[4], matrix.m[5], matrix.m[6],
  3912. matrix.m[8], matrix.m[9], matrix.m[10]
  3913. ]);
  3914. };
  3915. /**
  3916. * Compute the transpose of the passed Matrix.
  3917. * Returns a new Matrix.
  3918. */
  3919. Matrix.Transpose = function (matrix) {
  3920. var result = new Matrix();
  3921. Matrix.TransposeToRef(matrix, result);
  3922. return result;
  3923. };
  3924. /**
  3925. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3926. */
  3927. Matrix.TransposeToRef = function (matrix, result) {
  3928. result.m[0] = matrix.m[0];
  3929. result.m[1] = matrix.m[4];
  3930. result.m[2] = matrix.m[8];
  3931. result.m[3] = matrix.m[12];
  3932. result.m[4] = matrix.m[1];
  3933. result.m[5] = matrix.m[5];
  3934. result.m[6] = matrix.m[9];
  3935. result.m[7] = matrix.m[13];
  3936. result.m[8] = matrix.m[2];
  3937. result.m[9] = matrix.m[6];
  3938. result.m[10] = matrix.m[10];
  3939. result.m[11] = matrix.m[14];
  3940. result.m[12] = matrix.m[3];
  3941. result.m[13] = matrix.m[7];
  3942. result.m[14] = matrix.m[11];
  3943. result.m[15] = matrix.m[15];
  3944. };
  3945. /**
  3946. * Returns a new Matrix as the reflection matrix across the passed plane.
  3947. */
  3948. Matrix.Reflection = function (plane) {
  3949. var matrix = new Matrix();
  3950. Matrix.ReflectionToRef(plane, matrix);
  3951. return matrix;
  3952. };
  3953. /**
  3954. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3955. */
  3956. Matrix.ReflectionToRef = function (plane, result) {
  3957. plane.normalize();
  3958. var x = plane.normal.x;
  3959. var y = plane.normal.y;
  3960. var z = plane.normal.z;
  3961. var temp = -2 * x;
  3962. var temp2 = -2 * y;
  3963. var temp3 = -2 * z;
  3964. result.m[0] = (temp * x) + 1;
  3965. result.m[1] = temp2 * x;
  3966. result.m[2] = temp3 * x;
  3967. result.m[3] = 0.0;
  3968. result.m[4] = temp * y;
  3969. result.m[5] = (temp2 * y) + 1;
  3970. result.m[6] = temp3 * y;
  3971. result.m[7] = 0.0;
  3972. result.m[8] = temp * z;
  3973. result.m[9] = temp2 * z;
  3974. result.m[10] = (temp3 * z) + 1;
  3975. result.m[11] = 0.0;
  3976. result.m[12] = temp * plane.d;
  3977. result.m[13] = temp2 * plane.d;
  3978. result.m[14] = temp3 * plane.d;
  3979. result.m[15] = 1.0;
  3980. result._markAsUpdated();
  3981. };
  3982. /**
  3983. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3984. */
  3985. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3986. result.m[0] = xaxis.x;
  3987. result.m[1] = xaxis.y;
  3988. result.m[2] = xaxis.z;
  3989. result.m[3] = 0.0;
  3990. result.m[4] = yaxis.x;
  3991. result.m[5] = yaxis.y;
  3992. result.m[6] = yaxis.z;
  3993. result.m[7] = 0.0;
  3994. result.m[8] = zaxis.x;
  3995. result.m[9] = zaxis.y;
  3996. result.m[10] = zaxis.z;
  3997. result.m[11] = 0.0;
  3998. result.m[12] = 0.0;
  3999. result.m[13] = 0.0;
  4000. result.m[14] = 0.0;
  4001. result.m[15] = 1.0;
  4002. result._markAsUpdated();
  4003. };
  4004. /**
  4005. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4006. */
  4007. Matrix.FromQuaternionToRef = function (quat, result) {
  4008. var xx = quat.x * quat.x;
  4009. var yy = quat.y * quat.y;
  4010. var zz = quat.z * quat.z;
  4011. var xy = quat.x * quat.y;
  4012. var zw = quat.z * quat.w;
  4013. var zx = quat.z * quat.x;
  4014. var yw = quat.y * quat.w;
  4015. var yz = quat.y * quat.z;
  4016. var xw = quat.x * quat.w;
  4017. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4018. result.m[1] = 2.0 * (xy + zw);
  4019. result.m[2] = 2.0 * (zx - yw);
  4020. result.m[3] = 0.0;
  4021. result.m[4] = 2.0 * (xy - zw);
  4022. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4023. result.m[6] = 2.0 * (yz + xw);
  4024. result.m[7] = 0.0;
  4025. result.m[8] = 2.0 * (zx + yw);
  4026. result.m[9] = 2.0 * (yz - xw);
  4027. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4028. result.m[11] = 0.0;
  4029. result.m[12] = 0.0;
  4030. result.m[13] = 0.0;
  4031. result.m[14] = 0.0;
  4032. result.m[15] = 1.0;
  4033. result._markAsUpdated();
  4034. };
  4035. Matrix._tempQuaternion = new Quaternion();
  4036. Matrix._xAxis = Vector3.Zero();
  4037. Matrix._yAxis = Vector3.Zero();
  4038. Matrix._zAxis = Vector3.Zero();
  4039. Matrix._updateFlagSeed = 0;
  4040. Matrix._identityReadOnly = Matrix.Identity();
  4041. return Matrix;
  4042. }());
  4043. BABYLON.Matrix = Matrix;
  4044. var Plane = /** @class */ (function () {
  4045. /**
  4046. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4047. */
  4048. function Plane(a, b, c, d) {
  4049. this.normal = new Vector3(a, b, c);
  4050. this.d = d;
  4051. }
  4052. /**
  4053. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4054. */
  4055. Plane.prototype.asArray = function () {
  4056. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4057. };
  4058. // Methods
  4059. /**
  4060. * Returns a new plane copied from the current Plane.
  4061. */
  4062. Plane.prototype.clone = function () {
  4063. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4064. };
  4065. /**
  4066. * Returns the string "Plane".
  4067. */
  4068. Plane.prototype.getClassName = function () {
  4069. return "Plane";
  4070. };
  4071. /**
  4072. * Returns the Plane hash code.
  4073. */
  4074. Plane.prototype.getHashCode = function () {
  4075. var hash = this.normal.getHashCode();
  4076. hash = (hash * 397) ^ (this.d || 0);
  4077. return hash;
  4078. };
  4079. /**
  4080. * Normalize the current Plane in place.
  4081. * Returns the updated Plane.
  4082. */
  4083. Plane.prototype.normalize = function () {
  4084. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4085. var magnitude = 0.0;
  4086. if (norm !== 0) {
  4087. magnitude = 1.0 / norm;
  4088. }
  4089. this.normal.x *= magnitude;
  4090. this.normal.y *= magnitude;
  4091. this.normal.z *= magnitude;
  4092. this.d *= magnitude;
  4093. return this;
  4094. };
  4095. /**
  4096. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4097. */
  4098. Plane.prototype.transform = function (transformation) {
  4099. var transposedMatrix = Matrix.Transpose(transformation);
  4100. var x = this.normal.x;
  4101. var y = this.normal.y;
  4102. var z = this.normal.z;
  4103. var d = this.d;
  4104. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4105. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4106. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4107. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4108. return new Plane(normalX, normalY, normalZ, finalD);
  4109. };
  4110. /**
  4111. * Returns the dot product (float) of the point coordinates and the plane normal.
  4112. */
  4113. Plane.prototype.dotCoordinate = function (point) {
  4114. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4115. };
  4116. /**
  4117. * Updates the current Plane from the plane defined by the three passed points.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4121. var x1 = point2.x - point1.x;
  4122. var y1 = point2.y - point1.y;
  4123. var z1 = point2.z - point1.z;
  4124. var x2 = point3.x - point1.x;
  4125. var y2 = point3.y - point1.y;
  4126. var z2 = point3.z - point1.z;
  4127. var yz = (y1 * z2) - (z1 * y2);
  4128. var xz = (z1 * x2) - (x1 * z2);
  4129. var xy = (x1 * y2) - (y1 * x2);
  4130. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4131. var invPyth;
  4132. if (pyth !== 0) {
  4133. invPyth = 1.0 / pyth;
  4134. }
  4135. else {
  4136. invPyth = 0.0;
  4137. }
  4138. this.normal.x = yz * invPyth;
  4139. this.normal.y = xz * invPyth;
  4140. this.normal.z = xy * invPyth;
  4141. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4142. return this;
  4143. };
  4144. /**
  4145. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4146. */
  4147. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4148. var dot = Vector3.Dot(this.normal, direction);
  4149. return (dot <= epsilon);
  4150. };
  4151. /**
  4152. * Returns the signed distance (float) from the passed point to the Plane.
  4153. */
  4154. Plane.prototype.signedDistanceTo = function (point) {
  4155. return Vector3.Dot(point, this.normal) + this.d;
  4156. };
  4157. // Statics
  4158. /**
  4159. * Returns a new Plane from the passed array.
  4160. */
  4161. Plane.FromArray = function (array) {
  4162. return new Plane(array[0], array[1], array[2], array[3]);
  4163. };
  4164. /**
  4165. * Returns a new Plane defined by the three passed points.
  4166. */
  4167. Plane.FromPoints = function (point1, point2, point3) {
  4168. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4169. result.copyFromPoints(point1, point2, point3);
  4170. return result;
  4171. };
  4172. /**
  4173. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4174. * Note : the vector "normal" is updated because normalized.
  4175. */
  4176. Plane.FromPositionAndNormal = function (origin, normal) {
  4177. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4178. normal.normalize();
  4179. result.normal = normal;
  4180. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4181. return result;
  4182. };
  4183. /**
  4184. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4185. */
  4186. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4187. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4188. return Vector3.Dot(point, normal) + d;
  4189. };
  4190. return Plane;
  4191. }());
  4192. BABYLON.Plane = Plane;
  4193. var Viewport = /** @class */ (function () {
  4194. /**
  4195. * Creates a Viewport object located at (x, y) and sized (width, height).
  4196. */
  4197. function Viewport(x, y, width, height) {
  4198. this.x = x;
  4199. this.y = y;
  4200. this.width = width;
  4201. this.height = height;
  4202. }
  4203. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4204. if (renderWidthOrEngine.getRenderWidth) {
  4205. var engine = renderWidthOrEngine;
  4206. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4207. }
  4208. var renderWidth = renderWidthOrEngine;
  4209. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4210. };
  4211. /**
  4212. * Returns a new Viewport copied from the current one.
  4213. */
  4214. Viewport.prototype.clone = function () {
  4215. return new Viewport(this.x, this.y, this.width, this.height);
  4216. };
  4217. return Viewport;
  4218. }());
  4219. BABYLON.Viewport = Viewport;
  4220. var Frustum = /** @class */ (function () {
  4221. function Frustum() {
  4222. }
  4223. /**
  4224. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4225. */
  4226. Frustum.GetPlanes = function (transform) {
  4227. var frustumPlanes = [];
  4228. for (var index = 0; index < 6; index++) {
  4229. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4230. }
  4231. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4232. return frustumPlanes;
  4233. };
  4234. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4235. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4236. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4237. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4238. frustumPlane.d = transform.m[15] + transform.m[14];
  4239. frustumPlane.normalize();
  4240. };
  4241. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4242. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4243. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4244. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4245. frustumPlane.d = transform.m[15] - transform.m[14];
  4246. frustumPlane.normalize();
  4247. };
  4248. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4249. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4250. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4251. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4252. frustumPlane.d = transform.m[15] + transform.m[12];
  4253. frustumPlane.normalize();
  4254. };
  4255. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4256. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4257. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4258. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4259. frustumPlane.d = transform.m[15] - transform.m[12];
  4260. frustumPlane.normalize();
  4261. };
  4262. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4263. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4264. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4265. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4266. frustumPlane.d = transform.m[15] - transform.m[13];
  4267. frustumPlane.normalize();
  4268. };
  4269. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4270. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4271. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4272. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4273. frustumPlane.d = transform.m[15] + transform.m[13];
  4274. frustumPlane.normalize();
  4275. };
  4276. /**
  4277. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4278. */
  4279. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4280. // Near
  4281. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4282. // Far
  4283. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4284. // Left
  4285. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4286. // Right
  4287. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4288. // Top
  4289. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4290. // Bottom
  4291. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4292. };
  4293. return Frustum;
  4294. }());
  4295. BABYLON.Frustum = Frustum;
  4296. var Space;
  4297. (function (Space) {
  4298. Space[Space["LOCAL"] = 0] = "LOCAL";
  4299. Space[Space["WORLD"] = 1] = "WORLD";
  4300. Space[Space["BONE"] = 2] = "BONE";
  4301. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4302. var Axis = /** @class */ (function () {
  4303. function Axis() {
  4304. }
  4305. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4306. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4307. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4308. return Axis;
  4309. }());
  4310. BABYLON.Axis = Axis;
  4311. ;
  4312. var BezierCurve = /** @class */ (function () {
  4313. function BezierCurve() {
  4314. }
  4315. /**
  4316. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4317. */
  4318. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4319. // Extract X (which is equal to time here)
  4320. var f0 = 1 - 3 * x2 + 3 * x1;
  4321. var f1 = 3 * x2 - 6 * x1;
  4322. var f2 = 3 * x1;
  4323. var refinedT = t;
  4324. for (var i = 0; i < 5; i++) {
  4325. var refinedT2 = refinedT * refinedT;
  4326. var refinedT3 = refinedT2 * refinedT;
  4327. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4328. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4329. refinedT -= (x - t) * slope;
  4330. refinedT = Math.min(1, Math.max(0, refinedT));
  4331. }
  4332. // Resolve cubic bezier for the given x
  4333. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4334. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4335. Math.pow(refinedT, 3);
  4336. };
  4337. return BezierCurve;
  4338. }());
  4339. BABYLON.BezierCurve = BezierCurve;
  4340. var Orientation;
  4341. (function (Orientation) {
  4342. Orientation[Orientation["CW"] = 0] = "CW";
  4343. Orientation[Orientation["CCW"] = 1] = "CCW";
  4344. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4345. var Angle = /** @class */ (function () {
  4346. /**
  4347. * Creates an Angle object of "radians" radians (float).
  4348. */
  4349. function Angle(radians) {
  4350. var _this = this;
  4351. /**
  4352. * Returns the Angle value in degrees (float).
  4353. */
  4354. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4355. /**
  4356. * Returns the Angle value in radians (float).
  4357. */
  4358. this.radians = function () { return _this._radians; };
  4359. this._radians = radians;
  4360. if (this._radians < 0.0)
  4361. this._radians += (2.0 * Math.PI);
  4362. }
  4363. /**
  4364. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4365. */
  4366. Angle.BetweenTwoPoints = function (a, b) {
  4367. var delta = b.subtract(a);
  4368. var theta = Math.atan2(delta.y, delta.x);
  4369. return new Angle(theta);
  4370. };
  4371. /**
  4372. * Returns a new Angle object from the passed float in radians.
  4373. */
  4374. Angle.FromRadians = function (radians) {
  4375. return new Angle(radians);
  4376. };
  4377. /**
  4378. * Returns a new Angle object from the passed float in degrees.
  4379. */
  4380. Angle.FromDegrees = function (degrees) {
  4381. return new Angle(degrees * Math.PI / 180.0);
  4382. };
  4383. return Angle;
  4384. }());
  4385. BABYLON.Angle = Angle;
  4386. var Arc2 = /** @class */ (function () {
  4387. /**
  4388. * Creates an Arc object from the three passed points : start, middle and end.
  4389. */
  4390. function Arc2(startPoint, midPoint, endPoint) {
  4391. this.startPoint = startPoint;
  4392. this.midPoint = midPoint;
  4393. this.endPoint = endPoint;
  4394. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4395. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4396. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4397. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4398. 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);
  4399. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4400. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4401. var a1 = this.startAngle.degrees();
  4402. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4403. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4404. // angles correction
  4405. if (a2 - a1 > +180.0)
  4406. a2 -= 360.0;
  4407. if (a2 - a1 < -180.0)
  4408. a2 += 360.0;
  4409. if (a3 - a2 > +180.0)
  4410. a3 -= 360.0;
  4411. if (a3 - a2 < -180.0)
  4412. a3 += 360.0;
  4413. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4414. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4415. }
  4416. return Arc2;
  4417. }());
  4418. BABYLON.Arc2 = Arc2;
  4419. var Path2 = /** @class */ (function () {
  4420. /**
  4421. * Creates a Path2 object from the starting 2D coordinates x and y.
  4422. */
  4423. function Path2(x, y) {
  4424. this._points = new Array();
  4425. this._length = 0.0;
  4426. this.closed = false;
  4427. this._points.push(new Vector2(x, y));
  4428. }
  4429. /**
  4430. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4431. * Returns the updated Path2.
  4432. */
  4433. Path2.prototype.addLineTo = function (x, y) {
  4434. if (closed) {
  4435. //Tools.Error("cannot add lines to closed paths");
  4436. return this;
  4437. }
  4438. var newPoint = new Vector2(x, y);
  4439. var previousPoint = this._points[this._points.length - 1];
  4440. this._points.push(newPoint);
  4441. this._length += newPoint.subtract(previousPoint).length();
  4442. return this;
  4443. };
  4444. /**
  4445. * 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.
  4446. * Returns the updated Path2.
  4447. */
  4448. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4449. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4450. if (closed) {
  4451. //Tools.Error("cannot add arcs to closed paths");
  4452. return this;
  4453. }
  4454. var startPoint = this._points[this._points.length - 1];
  4455. var midPoint = new Vector2(midX, midY);
  4456. var endPoint = new Vector2(endX, endY);
  4457. var arc = new Arc2(startPoint, midPoint, endPoint);
  4458. var increment = arc.angle.radians() / numberOfSegments;
  4459. if (arc.orientation === Orientation.CW)
  4460. increment *= -1;
  4461. var currentAngle = arc.startAngle.radians() + increment;
  4462. for (var i = 0; i < numberOfSegments; i++) {
  4463. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4464. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4465. this.addLineTo(x, y);
  4466. currentAngle += increment;
  4467. }
  4468. return this;
  4469. };
  4470. /**
  4471. * Closes the Path2.
  4472. * Returns the Path2.
  4473. */
  4474. Path2.prototype.close = function () {
  4475. this.closed = true;
  4476. return this;
  4477. };
  4478. /**
  4479. * Returns the Path2 total length (float).
  4480. */
  4481. Path2.prototype.length = function () {
  4482. var result = this._length;
  4483. if (!this.closed) {
  4484. var lastPoint = this._points[this._points.length - 1];
  4485. var firstPoint = this._points[0];
  4486. result += (firstPoint.subtract(lastPoint).length());
  4487. }
  4488. return result;
  4489. };
  4490. /**
  4491. * Returns the Path2 internal array of points.
  4492. */
  4493. Path2.prototype.getPoints = function () {
  4494. return this._points;
  4495. };
  4496. /**
  4497. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4498. */
  4499. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4500. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4501. //Tools.Error("normalized length position should be between 0 and 1.");
  4502. return Vector2.Zero();
  4503. }
  4504. var lengthPosition = normalizedLengthPosition * this.length();
  4505. var previousOffset = 0;
  4506. for (var i = 0; i < this._points.length; i++) {
  4507. var j = (i + 1) % this._points.length;
  4508. var a = this._points[i];
  4509. var b = this._points[j];
  4510. var bToA = b.subtract(a);
  4511. var nextOffset = (bToA.length() + previousOffset);
  4512. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4513. var dir = bToA.normalize();
  4514. var localOffset = lengthPosition - previousOffset;
  4515. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4516. }
  4517. previousOffset = nextOffset;
  4518. }
  4519. //Tools.Error("internal error");
  4520. return Vector2.Zero();
  4521. };
  4522. /**
  4523. * Returns a new Path2 starting at the coordinates (x, y).
  4524. */
  4525. Path2.StartingAt = function (x, y) {
  4526. return new Path2(x, y);
  4527. };
  4528. return Path2;
  4529. }());
  4530. BABYLON.Path2 = Path2;
  4531. var Path3D = /** @class */ (function () {
  4532. /**
  4533. * new Path3D(path, normal, raw)
  4534. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4535. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4536. * path : an array of Vector3, the curve axis of the Path3D
  4537. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4538. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4539. */
  4540. function Path3D(path, firstNormal, raw) {
  4541. if (firstNormal === void 0) { firstNormal = null; }
  4542. this.path = path;
  4543. this._curve = new Array();
  4544. this._distances = new Array();
  4545. this._tangents = new Array();
  4546. this._normals = new Array();
  4547. this._binormals = new Array();
  4548. for (var p = 0; p < path.length; p++) {
  4549. this._curve[p] = path[p].clone(); // hard copy
  4550. }
  4551. this._raw = raw || false;
  4552. this._compute(firstNormal);
  4553. }
  4554. /**
  4555. * Returns the Path3D array of successive Vector3 designing its curve.
  4556. */
  4557. Path3D.prototype.getCurve = function () {
  4558. return this._curve;
  4559. };
  4560. /**
  4561. * Returns an array populated with tangent vectors on each Path3D curve point.
  4562. */
  4563. Path3D.prototype.getTangents = function () {
  4564. return this._tangents;
  4565. };
  4566. /**
  4567. * Returns an array populated with normal vectors on each Path3D curve point.
  4568. */
  4569. Path3D.prototype.getNormals = function () {
  4570. return this._normals;
  4571. };
  4572. /**
  4573. * Returns an array populated with binormal vectors on each Path3D curve point.
  4574. */
  4575. Path3D.prototype.getBinormals = function () {
  4576. return this._binormals;
  4577. };
  4578. /**
  4579. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4580. */
  4581. Path3D.prototype.getDistances = function () {
  4582. return this._distances;
  4583. };
  4584. /**
  4585. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4586. * Returns the same object updated.
  4587. */
  4588. Path3D.prototype.update = function (path, firstNormal) {
  4589. if (firstNormal === void 0) { firstNormal = null; }
  4590. for (var p = 0; p < path.length; p++) {
  4591. this._curve[p].x = path[p].x;
  4592. this._curve[p].y = path[p].y;
  4593. this._curve[p].z = path[p].z;
  4594. }
  4595. this._compute(firstNormal);
  4596. return this;
  4597. };
  4598. // private function compute() : computes tangents, normals and binormals
  4599. Path3D.prototype._compute = function (firstNormal) {
  4600. var l = this._curve.length;
  4601. // first and last tangents
  4602. this._tangents[0] = this._getFirstNonNullVector(0);
  4603. if (!this._raw) {
  4604. this._tangents[0].normalize();
  4605. }
  4606. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4607. if (!this._raw) {
  4608. this._tangents[l - 1].normalize();
  4609. }
  4610. // normals and binormals at first point : arbitrary vector with _normalVector()
  4611. var tg0 = this._tangents[0];
  4612. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4613. this._normals[0] = pp0;
  4614. if (!this._raw) {
  4615. this._normals[0].normalize();
  4616. }
  4617. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4618. if (!this._raw) {
  4619. this._binormals[0].normalize();
  4620. }
  4621. this._distances[0] = 0.0;
  4622. // normals and binormals : next points
  4623. var prev; // previous vector (segment)
  4624. var cur; // current vector (segment)
  4625. var curTang; // current tangent
  4626. // previous normal
  4627. var prevBinor; // previous binormal
  4628. for (var i = 1; i < l; i++) {
  4629. // tangents
  4630. prev = this._getLastNonNullVector(i);
  4631. if (i < l - 1) {
  4632. cur = this._getFirstNonNullVector(i);
  4633. this._tangents[i] = prev.add(cur);
  4634. this._tangents[i].normalize();
  4635. }
  4636. this._distances[i] = this._distances[i - 1] + prev.length();
  4637. // normals and binormals
  4638. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4639. curTang = this._tangents[i];
  4640. prevBinor = this._binormals[i - 1];
  4641. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4642. if (!this._raw) {
  4643. this._normals[i].normalize();
  4644. }
  4645. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4646. if (!this._raw) {
  4647. this._binormals[i].normalize();
  4648. }
  4649. }
  4650. };
  4651. // private function getFirstNonNullVector(index)
  4652. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4653. Path3D.prototype._getFirstNonNullVector = function (index) {
  4654. var i = 1;
  4655. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4656. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4657. i++;
  4658. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. }
  4660. return nNVector;
  4661. };
  4662. // private function getLastNonNullVector(index)
  4663. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4664. Path3D.prototype._getLastNonNullVector = function (index) {
  4665. var i = 1;
  4666. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4667. while (nLVector.length() === 0 && index > i + 1) {
  4668. i++;
  4669. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. }
  4671. return nLVector;
  4672. };
  4673. // private function normalVector(v0, vt, va) :
  4674. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4675. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4676. Path3D.prototype._normalVector = function (v0, vt, va) {
  4677. var normal0;
  4678. var tgl = vt.length();
  4679. if (tgl === 0.0) {
  4680. tgl = 1.0;
  4681. }
  4682. if (va === undefined || va === null) {
  4683. var point;
  4684. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4685. point = new Vector3(0.0, -1.0, 0.0);
  4686. }
  4687. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(1.0, 0.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(0.0, 0.0, 1.0);
  4692. }
  4693. else {
  4694. point = Vector3.Zero();
  4695. }
  4696. normal0 = Vector3.Cross(vt, point);
  4697. }
  4698. else {
  4699. normal0 = Vector3.Cross(vt, va);
  4700. Vector3.CrossToRef(normal0, vt, normal0);
  4701. }
  4702. normal0.normalize();
  4703. return normal0;
  4704. };
  4705. return Path3D;
  4706. }());
  4707. BABYLON.Path3D = Path3D;
  4708. var Curve3 = /** @class */ (function () {
  4709. /**
  4710. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4711. * A Curve3 is designed from a series of successive Vector3.
  4712. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4713. */
  4714. function Curve3(points) {
  4715. this._length = 0.0;
  4716. this._points = points;
  4717. this._length = this._computeLength(points);
  4718. }
  4719. /**
  4720. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4721. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4722. * @param v1 (Vector3) the control point
  4723. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4724. * @param nbPoints (integer) the wanted number of points in the curve
  4725. */
  4726. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4727. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4728. var bez = new Array();
  4729. var equation = function (t, val0, val1, val2) {
  4730. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4731. return res;
  4732. };
  4733. for (var i = 0; i <= nbPoints; i++) {
  4734. 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)));
  4735. }
  4736. return new Curve3(bez);
  4737. };
  4738. /**
  4739. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4740. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4741. * @param v1 (Vector3) the first control point
  4742. * @param v2 (Vector3) the second control point
  4743. * @param v3 (Vector3) the end point of the Cubic Bezier
  4744. * @param nbPoints (integer) the wanted number of points in the curve
  4745. */
  4746. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4747. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4748. var bez = new Array();
  4749. var equation = function (t, val0, val1, val2, val3) {
  4750. 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;
  4751. return res;
  4752. };
  4753. for (var i = 0; i <= nbPoints; i++) {
  4754. 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)));
  4755. }
  4756. return new Curve3(bez);
  4757. };
  4758. /**
  4759. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4760. * @param p1 (Vector3) the origin point of the Hermite Spline
  4761. * @param t1 (Vector3) the tangent vector at the origin point
  4762. * @param p2 (Vector3) the end point of the Hermite Spline
  4763. * @param t2 (Vector3) the tangent vector at the end point
  4764. * @param nbPoints (integer) the wanted number of points in the curve
  4765. */
  4766. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4767. var hermite = new Array();
  4768. var step = 1.0 / nbPoints;
  4769. for (var i = 0; i <= nbPoints; i++) {
  4770. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4771. }
  4772. return new Curve3(hermite);
  4773. };
  4774. /**
  4775. * Returns a Curve3 object along a CatmullRom Spline curve :
  4776. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4777. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4778. */
  4779. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4780. var totalPoints = new Array();
  4781. totalPoints.push(points[0].clone());
  4782. Array.prototype.push.apply(totalPoints, points);
  4783. totalPoints.push(points[points.length - 1].clone());
  4784. var catmullRom = new Array();
  4785. var step = 1.0 / nbPoints;
  4786. var amount = 0.0;
  4787. for (var i = 0; i < totalPoints.length - 3; i++) {
  4788. amount = 0;
  4789. for (var c = 0; c < nbPoints; c++) {
  4790. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4791. amount += step;
  4792. }
  4793. }
  4794. i--;
  4795. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4796. return new Curve3(catmullRom);
  4797. };
  4798. /**
  4799. * Returns the Curve3 stored array of successive Vector3
  4800. */
  4801. Curve3.prototype.getPoints = function () {
  4802. return this._points;
  4803. };
  4804. /**
  4805. * Returns the computed length (float) of the curve.
  4806. */
  4807. Curve3.prototype.length = function () {
  4808. return this._length;
  4809. };
  4810. /**
  4811. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4812. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4813. * curveA and curveB keep unchanged.
  4814. */
  4815. Curve3.prototype.continue = function (curve) {
  4816. var lastPoint = this._points[this._points.length - 1];
  4817. var continuedPoints = this._points.slice();
  4818. var curvePoints = curve.getPoints();
  4819. for (var i = 1; i < curvePoints.length; i++) {
  4820. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4821. }
  4822. var continuedCurve = new Curve3(continuedPoints);
  4823. return continuedCurve;
  4824. };
  4825. Curve3.prototype._computeLength = function (path) {
  4826. var l = 0;
  4827. for (var i = 1; i < path.length; i++) {
  4828. l += (path[i].subtract(path[i - 1])).length();
  4829. }
  4830. return l;
  4831. };
  4832. return Curve3;
  4833. }());
  4834. BABYLON.Curve3 = Curve3;
  4835. // Vertex formats
  4836. var PositionNormalVertex = /** @class */ (function () {
  4837. function PositionNormalVertex(position, normal) {
  4838. if (position === void 0) { position = Vector3.Zero(); }
  4839. if (normal === void 0) { normal = Vector3.Up(); }
  4840. this.position = position;
  4841. this.normal = normal;
  4842. }
  4843. PositionNormalVertex.prototype.clone = function () {
  4844. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4845. };
  4846. return PositionNormalVertex;
  4847. }());
  4848. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4849. var PositionNormalTextureVertex = /** @class */ (function () {
  4850. function PositionNormalTextureVertex(position, normal, uv) {
  4851. if (position === void 0) { position = Vector3.Zero(); }
  4852. if (normal === void 0) { normal = Vector3.Up(); }
  4853. if (uv === void 0) { uv = Vector2.Zero(); }
  4854. this.position = position;
  4855. this.normal = normal;
  4856. this.uv = uv;
  4857. }
  4858. PositionNormalTextureVertex.prototype.clone = function () {
  4859. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4860. };
  4861. return PositionNormalTextureVertex;
  4862. }());
  4863. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4864. // Temporary pre-allocated objects for engine internal use
  4865. // usage in any internal function :
  4866. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4867. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4868. var Tmp = /** @class */ (function () {
  4869. function Tmp() {
  4870. }
  4871. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4872. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4873. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4874. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4875. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4876. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4877. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4878. Matrix.Zero(), Matrix.Zero(),
  4879. Matrix.Zero(), Matrix.Zero(),
  4880. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4881. return Tmp;
  4882. }());
  4883. BABYLON.Tmp = Tmp;
  4884. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4885. var MathTmp = /** @class */ (function () {
  4886. function MathTmp() {
  4887. }
  4888. MathTmp.Vector3 = [Vector3.Zero()];
  4889. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4890. MathTmp.Quaternion = [Quaternion.Zero()];
  4891. return MathTmp;
  4892. }());
  4893. })(BABYLON || (BABYLON = {}));
  4894. //# sourceMappingURL=babylon.math.js.map
  4895. var BABYLON;
  4896. (function (BABYLON) {
  4897. var Scalar = /** @class */ (function () {
  4898. function Scalar() {
  4899. }
  4900. /**
  4901. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4902. */
  4903. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4904. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4905. var num = a - b;
  4906. return -epsilon <= num && num <= epsilon;
  4907. };
  4908. /**
  4909. * Returns a string : the upper case translation of the number i to hexadecimal.
  4910. */
  4911. Scalar.ToHex = function (i) {
  4912. var str = i.toString(16);
  4913. if (i <= 15) {
  4914. return ("0" + str).toUpperCase();
  4915. }
  4916. return str.toUpperCase();
  4917. };
  4918. /**
  4919. * Returns -1 if value is negative and +1 is value is positive.
  4920. * Returns the value itself if it's equal to zero.
  4921. */
  4922. Scalar.Sign = function (value) {
  4923. value = +value; // convert to a number
  4924. if (value === 0 || isNaN(value))
  4925. return value;
  4926. return value > 0 ? 1 : -1;
  4927. };
  4928. /**
  4929. * Returns the value itself if it's between min and max.
  4930. * Returns min if the value is lower than min.
  4931. * Returns max if the value is greater than max.
  4932. */
  4933. Scalar.Clamp = function (value, min, max) {
  4934. if (min === void 0) { min = 0; }
  4935. if (max === void 0) { max = 1; }
  4936. return Math.min(max, Math.max(min, value));
  4937. };
  4938. /**
  4939. * Returns the log2 of value.
  4940. */
  4941. Scalar.Log2 = function (value) {
  4942. return Math.log(value) * Math.LOG2E;
  4943. };
  4944. /**
  4945. * Loops the value, so that it is never larger than length and never smaller than 0.
  4946. *
  4947. * This is similar to the modulo operator but it works with floating point numbers.
  4948. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4949. * With t = 5 and length = 2.5, the result would be 0.0.
  4950. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4951. */
  4952. Scalar.Repeat = function (value, length) {
  4953. return value - Math.floor(value / length) * length;
  4954. };
  4955. /**
  4956. * Normalize the value between 0.0 and 1.0 using min and max values
  4957. */
  4958. Scalar.Normalize = function (value, min, max) {
  4959. return (value - min) / (max - min);
  4960. };
  4961. /**
  4962. * Denormalize the value from 0.0 and 1.0 using min and max values
  4963. */
  4964. Scalar.Denormalize = function (normalized, min, max) {
  4965. return (normalized * (max - min) + min);
  4966. };
  4967. /**
  4968. * Calculates the shortest difference between two given angles given in degrees.
  4969. */
  4970. Scalar.DeltaAngle = function (current, target) {
  4971. var num = Scalar.Repeat(target - current, 360.0);
  4972. if (num > 180.0) {
  4973. num -= 360.0;
  4974. }
  4975. return num;
  4976. };
  4977. /**
  4978. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4979. *
  4980. * The returned value will move back and forth between 0 and length
  4981. */
  4982. Scalar.PingPong = function (tx, length) {
  4983. var t = Scalar.Repeat(tx, length * 2.0);
  4984. return length - Math.abs(t - length);
  4985. };
  4986. /**
  4987. * Interpolates between min and max with smoothing at the limits.
  4988. *
  4989. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4990. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4991. */
  4992. Scalar.SmoothStep = function (from, to, tx) {
  4993. var t = Scalar.Clamp(tx);
  4994. t = -2.0 * t * t * t + 3.0 * t * t;
  4995. return to * t + from * (1.0 - t);
  4996. };
  4997. /**
  4998. * Moves a value current towards target.
  4999. *
  5000. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5001. * Negative values of maxDelta pushes the value away from target.
  5002. */
  5003. Scalar.MoveTowards = function (current, target, maxDelta) {
  5004. var result = 0;
  5005. if (Math.abs(target - current) <= maxDelta) {
  5006. result = target;
  5007. }
  5008. else {
  5009. result = current + Scalar.Sign(target - current) * maxDelta;
  5010. }
  5011. return result;
  5012. };
  5013. /**
  5014. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5015. *
  5016. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5017. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5018. */
  5019. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5020. var num = Scalar.DeltaAngle(current, target);
  5021. var result = 0;
  5022. if (-maxDelta < num && num < maxDelta) {
  5023. result = target;
  5024. }
  5025. else {
  5026. target = current + num;
  5027. result = Scalar.MoveTowards(current, target, maxDelta);
  5028. }
  5029. return result;
  5030. };
  5031. /**
  5032. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5033. */
  5034. Scalar.Lerp = function (start, end, amount) {
  5035. return start + ((end - start) * amount);
  5036. };
  5037. /**
  5038. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5039. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5040. */
  5041. Scalar.LerpAngle = function (start, end, amount) {
  5042. var num = Scalar.Repeat(end - start, 360.0);
  5043. if (num > 180.0) {
  5044. num -= 360.0;
  5045. }
  5046. return start + num * Scalar.Clamp(amount);
  5047. };
  5048. /**
  5049. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5050. */
  5051. Scalar.InverseLerp = function (a, b, value) {
  5052. var result = 0;
  5053. if (a != b) {
  5054. result = Scalar.Clamp((value - a) / (b - a));
  5055. }
  5056. else {
  5057. result = 0.0;
  5058. }
  5059. return result;
  5060. };
  5061. /**
  5062. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5063. */
  5064. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5065. var squared = amount * amount;
  5066. var cubed = amount * squared;
  5067. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5068. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5069. var part3 = (cubed - (2.0 * squared)) + amount;
  5070. var part4 = cubed - squared;
  5071. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5072. };
  5073. /**
  5074. * Returns a random float number between and min and max values
  5075. */
  5076. Scalar.RandomRange = function (min, max) {
  5077. if (min === max)
  5078. return min;
  5079. return ((Math.random() * (max - min)) + min);
  5080. };
  5081. /**
  5082. * This function returns percentage of a number in a given range.
  5083. *
  5084. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5085. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5086. */
  5087. Scalar.RangeToPercent = function (number, min, max) {
  5088. return ((number - min) / (max - min));
  5089. };
  5090. /**
  5091. * This function returns number that corresponds to the percentage in a given range.
  5092. *
  5093. * PercentToRange(0.34,0,100) will return 34.
  5094. */
  5095. Scalar.PercentToRange = function (percent, min, max) {
  5096. return ((max - min) * percent + min);
  5097. };
  5098. return Scalar;
  5099. }());
  5100. BABYLON.Scalar = Scalar;
  5101. })(BABYLON || (BABYLON = {}));
  5102. //# sourceMappingURL=babylon.math.scalar.js.map
  5103. //# sourceMappingURL=babylon.mixins.js.map
  5104. var BABYLON;
  5105. (function (BABYLON) {
  5106. var __decoratorInitialStore = {};
  5107. var __mergedStore = {};
  5108. var _copySource = function (creationFunction, source, instanciate) {
  5109. var destination = creationFunction();
  5110. // Tags
  5111. if (BABYLON.Tags) {
  5112. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5113. }
  5114. var classStore = getMergedStore(destination);
  5115. // Properties
  5116. for (var property in classStore) {
  5117. var propertyDescriptor = classStore[property];
  5118. var sourceProperty = source[property];
  5119. var propertyType = propertyDescriptor.type;
  5120. if (sourceProperty !== undefined && sourceProperty !== null) {
  5121. switch (propertyType) {
  5122. case 0: // Value
  5123. case 6:// Mesh reference
  5124. destination[property] = sourceProperty;
  5125. break;
  5126. case 1:// Texture
  5127. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5128. break;
  5129. case 2: // Color3
  5130. case 3: // FresnelParameters
  5131. case 4: // Vector2
  5132. case 5: // Vector3
  5133. case 7:// Color Curves
  5134. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5135. break;
  5136. }
  5137. }
  5138. }
  5139. return destination;
  5140. };
  5141. function getDirectStore(target) {
  5142. var classKey = target.getClassName();
  5143. if (!__decoratorInitialStore[classKey]) {
  5144. __decoratorInitialStore[classKey] = {};
  5145. }
  5146. return __decoratorInitialStore[classKey];
  5147. }
  5148. /**
  5149. * Return the list of properties flagged as serializable
  5150. * @param target: host object
  5151. */
  5152. function getMergedStore(target) {
  5153. var classKey = target.getClassName();
  5154. if (__mergedStore[classKey]) {
  5155. return __mergedStore[classKey];
  5156. }
  5157. __mergedStore[classKey] = {};
  5158. var store = __mergedStore[classKey];
  5159. var currentTarget = target;
  5160. var currentKey = classKey;
  5161. while (currentKey) {
  5162. var initialStore = __decoratorInitialStore[currentKey];
  5163. for (var property in initialStore) {
  5164. store[property] = initialStore[property];
  5165. }
  5166. var parent_1 = void 0;
  5167. var done = false;
  5168. do {
  5169. parent_1 = Object.getPrototypeOf(currentTarget);
  5170. if (!parent_1.getClassName) {
  5171. done = true;
  5172. break;
  5173. }
  5174. if (parent_1.getClassName() !== currentKey) {
  5175. break;
  5176. }
  5177. currentTarget = parent_1;
  5178. } while (parent_1);
  5179. if (done) {
  5180. break;
  5181. }
  5182. currentKey = parent_1.getClassName();
  5183. currentTarget = parent_1;
  5184. }
  5185. return store;
  5186. }
  5187. function generateSerializableMember(type, sourceName) {
  5188. return function (target, propertyKey) {
  5189. var classStore = getDirectStore(target);
  5190. if (!classStore[propertyKey]) {
  5191. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5192. }
  5193. };
  5194. }
  5195. function generateExpandMember(setCallback, targetKey) {
  5196. if (targetKey === void 0) { targetKey = null; }
  5197. return function (target, propertyKey) {
  5198. var key = targetKey || ("_" + propertyKey);
  5199. Object.defineProperty(target, propertyKey, {
  5200. get: function () {
  5201. return this[key];
  5202. },
  5203. set: function (value) {
  5204. if (this[key] === value) {
  5205. return;
  5206. }
  5207. this[key] = value;
  5208. target[setCallback].apply(this);
  5209. },
  5210. enumerable: true,
  5211. configurable: true
  5212. });
  5213. };
  5214. }
  5215. function expandToProperty(callback, targetKey) {
  5216. if (targetKey === void 0) { targetKey = null; }
  5217. return generateExpandMember(callback, targetKey);
  5218. }
  5219. BABYLON.expandToProperty = expandToProperty;
  5220. function serialize(sourceName) {
  5221. return generateSerializableMember(0, sourceName); // value member
  5222. }
  5223. BABYLON.serialize = serialize;
  5224. function serializeAsTexture(sourceName) {
  5225. return generateSerializableMember(1, sourceName); // texture member
  5226. }
  5227. BABYLON.serializeAsTexture = serializeAsTexture;
  5228. function serializeAsColor3(sourceName) {
  5229. return generateSerializableMember(2, sourceName); // color3 member
  5230. }
  5231. BABYLON.serializeAsColor3 = serializeAsColor3;
  5232. function serializeAsFresnelParameters(sourceName) {
  5233. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5234. }
  5235. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5236. function serializeAsVector2(sourceName) {
  5237. return generateSerializableMember(4, sourceName); // vector2 member
  5238. }
  5239. BABYLON.serializeAsVector2 = serializeAsVector2;
  5240. function serializeAsVector3(sourceName) {
  5241. return generateSerializableMember(5, sourceName); // vector3 member
  5242. }
  5243. BABYLON.serializeAsVector3 = serializeAsVector3;
  5244. function serializeAsMeshReference(sourceName) {
  5245. return generateSerializableMember(6, sourceName); // mesh reference member
  5246. }
  5247. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5248. function serializeAsColorCurves(sourceName) {
  5249. return generateSerializableMember(7, sourceName); // color curves
  5250. }
  5251. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5252. function serializeAsColor4(sourceName) {
  5253. return generateSerializableMember(8, sourceName); // color 4
  5254. }
  5255. BABYLON.serializeAsColor4 = serializeAsColor4;
  5256. function serializeAsImageProcessingConfiguration(sourceName) {
  5257. return generateSerializableMember(9, sourceName); // image processing
  5258. }
  5259. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5260. var SerializationHelper = /** @class */ (function () {
  5261. function SerializationHelper() {
  5262. }
  5263. SerializationHelper.Serialize = function (entity, serializationObject) {
  5264. if (!serializationObject) {
  5265. serializationObject = {};
  5266. }
  5267. // Tags
  5268. if (BABYLON.Tags) {
  5269. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5270. }
  5271. var serializedProperties = getMergedStore(entity);
  5272. // Properties
  5273. for (var property in serializedProperties) {
  5274. var propertyDescriptor = serializedProperties[property];
  5275. var targetPropertyName = propertyDescriptor.sourceName || property;
  5276. var propertyType = propertyDescriptor.type;
  5277. var sourceProperty = entity[property];
  5278. if (sourceProperty !== undefined && sourceProperty !== null) {
  5279. switch (propertyType) {
  5280. case 0:// Value
  5281. serializationObject[targetPropertyName] = sourceProperty;
  5282. break;
  5283. case 1:// Texture
  5284. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5285. break;
  5286. case 2:// Color3
  5287. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5288. break;
  5289. case 3:// FresnelParameters
  5290. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5291. break;
  5292. case 4:// Vector2
  5293. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5294. break;
  5295. case 5:// Vector3
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 6:// Mesh reference
  5299. serializationObject[targetPropertyName] = sourceProperty.id;
  5300. break;
  5301. case 7:// Color Curves
  5302. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5303. break;
  5304. case 8:// Color 4
  5305. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5306. break;
  5307. case 9:// Image Processing
  5308. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5309. break;
  5310. }
  5311. }
  5312. }
  5313. return serializationObject;
  5314. };
  5315. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5316. if (rootUrl === void 0) { rootUrl = null; }
  5317. var destination = creationFunction();
  5318. if (!rootUrl) {
  5319. rootUrl = "";
  5320. }
  5321. // Tags
  5322. if (BABYLON.Tags) {
  5323. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5324. }
  5325. var classStore = getMergedStore(destination);
  5326. // Properties
  5327. for (var property in classStore) {
  5328. var propertyDescriptor = classStore[property];
  5329. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5330. var propertyType = propertyDescriptor.type;
  5331. if (sourceProperty !== undefined && sourceProperty !== null) {
  5332. var dest = destination;
  5333. switch (propertyType) {
  5334. case 0:// Value
  5335. dest[property] = sourceProperty;
  5336. break;
  5337. case 1:// Texture
  5338. if (scene) {
  5339. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5340. }
  5341. break;
  5342. case 2:// Color3
  5343. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5344. break;
  5345. case 3:// FresnelParameters
  5346. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5347. break;
  5348. case 4:// Vector2
  5349. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5350. break;
  5351. case 5:// Vector3
  5352. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5353. break;
  5354. case 6:// Mesh reference
  5355. if (scene) {
  5356. dest[property] = scene.getLastMeshByID(sourceProperty);
  5357. }
  5358. break;
  5359. case 7:// Color Curves
  5360. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5361. break;
  5362. case 8:// Color 4
  5363. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5364. break;
  5365. case 9:// Image Processing
  5366. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5367. break;
  5368. }
  5369. }
  5370. }
  5371. return destination;
  5372. };
  5373. SerializationHelper.Clone = function (creationFunction, source) {
  5374. return _copySource(creationFunction, source, false);
  5375. };
  5376. SerializationHelper.Instanciate = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, true);
  5378. };
  5379. return SerializationHelper;
  5380. }());
  5381. BABYLON.SerializationHelper = SerializationHelper;
  5382. })(BABYLON || (BABYLON = {}));
  5383. //# sourceMappingURL=babylon.decorators.js.map
  5384. var BABYLON;
  5385. (function (BABYLON) {
  5386. /**
  5387. * A class serves as a medium between the observable and its observers
  5388. */
  5389. var EventState = /** @class */ (function () {
  5390. /**
  5391. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5392. */
  5393. function EventState(mask, skipNextObservers, target, currentTarget) {
  5394. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5395. this.initalize(mask, skipNextObservers, target, currentTarget);
  5396. }
  5397. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5398. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5399. this.mask = mask;
  5400. this.skipNextObservers = skipNextObservers;
  5401. this.target = target;
  5402. this.currentTarget = currentTarget;
  5403. return this;
  5404. };
  5405. return EventState;
  5406. }());
  5407. BABYLON.EventState = EventState;
  5408. /**
  5409. * Represent an Observer registered to a given Observable object.
  5410. */
  5411. var Observer = /** @class */ (function () {
  5412. function Observer(callback, mask, scope) {
  5413. if (scope === void 0) { scope = null; }
  5414. this.callback = callback;
  5415. this.mask = mask;
  5416. this.scope = scope;
  5417. }
  5418. return Observer;
  5419. }());
  5420. BABYLON.Observer = Observer;
  5421. /**
  5422. * Represent a list of observers registered to multiple Observables object.
  5423. */
  5424. var MultiObserver = /** @class */ (function () {
  5425. function MultiObserver() {
  5426. }
  5427. MultiObserver.prototype.dispose = function () {
  5428. if (this._observers && this._observables) {
  5429. for (var index = 0; index < this._observers.length; index++) {
  5430. this._observables[index].remove(this._observers[index]);
  5431. }
  5432. }
  5433. this._observers = null;
  5434. this._observables = null;
  5435. };
  5436. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5437. if (mask === void 0) { mask = -1; }
  5438. if (scope === void 0) { scope = null; }
  5439. var result = new MultiObserver();
  5440. result._observers = new Array();
  5441. result._observables = observables;
  5442. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5443. var observable = observables_1[_i];
  5444. var observer = observable.add(callback, mask, false, scope);
  5445. if (observer) {
  5446. result._observers.push(observer);
  5447. }
  5448. }
  5449. return result;
  5450. };
  5451. return MultiObserver;
  5452. }());
  5453. BABYLON.MultiObserver = MultiObserver;
  5454. /**
  5455. * The Observable class is a simple implementation of the Observable pattern.
  5456. * 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.
  5457. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5458. * 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).
  5459. * 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.
  5460. */
  5461. var Observable = /** @class */ (function () {
  5462. function Observable(onObserverAdded) {
  5463. this._observers = new Array();
  5464. this._eventState = new EventState(0);
  5465. if (onObserverAdded) {
  5466. this._onObserverAdded = onObserverAdded;
  5467. }
  5468. }
  5469. /**
  5470. * Create a new Observer with the specified callback
  5471. * @param callback the callback that will be executed for that Observer
  5472. * @param mask the mask used to filter observers
  5473. * @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.
  5474. * @param scope optional scope for the callback to be called from
  5475. */
  5476. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5477. if (mask === void 0) { mask = -1; }
  5478. if (insertFirst === void 0) { insertFirst = false; }
  5479. if (scope === void 0) { scope = null; }
  5480. if (!callback) {
  5481. return null;
  5482. }
  5483. var observer = new Observer(callback, mask, scope);
  5484. if (insertFirst) {
  5485. this._observers.unshift(observer);
  5486. }
  5487. else {
  5488. this._observers.push(observer);
  5489. }
  5490. if (this._onObserverAdded) {
  5491. this._onObserverAdded(observer);
  5492. }
  5493. return observer;
  5494. };
  5495. /**
  5496. * Remove an Observer from the Observable object
  5497. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5498. */
  5499. Observable.prototype.remove = function (observer) {
  5500. if (!observer) {
  5501. return false;
  5502. }
  5503. var index = this._observers.indexOf(observer);
  5504. if (index !== -1) {
  5505. this._observers.splice(index, 1);
  5506. return true;
  5507. }
  5508. return false;
  5509. };
  5510. /**
  5511. * Remove a callback from the Observable object
  5512. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5513. */
  5514. Observable.prototype.removeCallback = function (callback) {
  5515. for (var index = 0; index < this._observers.length; index++) {
  5516. if (this._observers[index].callback === callback) {
  5517. this._observers.splice(index, 1);
  5518. return true;
  5519. }
  5520. }
  5521. return false;
  5522. };
  5523. /**
  5524. * Notify all Observers by calling their respective callback with the given data
  5525. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5526. * @param eventData
  5527. * @param mask
  5528. */
  5529. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5530. if (mask === void 0) { mask = -1; }
  5531. var state = this._eventState;
  5532. state.mask = mask;
  5533. state.target = target;
  5534. state.currentTarget = currentTarget;
  5535. state.skipNextObservers = false;
  5536. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5537. var obs = _a[_i];
  5538. if (obs.mask & mask) {
  5539. if (obs.scope) {
  5540. obs.callback.apply(obs.scope, [eventData, state]);
  5541. }
  5542. else {
  5543. obs.callback(eventData, state);
  5544. }
  5545. }
  5546. if (state.skipNextObservers) {
  5547. return false;
  5548. }
  5549. }
  5550. return true;
  5551. };
  5552. /**
  5553. * Notify a specific observer
  5554. * @param eventData
  5555. * @param mask
  5556. */
  5557. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5558. if (mask === void 0) { mask = -1; }
  5559. var state = this._eventState;
  5560. state.mask = mask;
  5561. state.skipNextObservers = false;
  5562. observer.callback(eventData, state);
  5563. };
  5564. /**
  5565. * return true is the Observable has at least one Observer registered
  5566. */
  5567. Observable.prototype.hasObservers = function () {
  5568. return this._observers.length > 0;
  5569. };
  5570. /**
  5571. * Clear the list of observers
  5572. */
  5573. Observable.prototype.clear = function () {
  5574. this._observers = new Array();
  5575. this._onObserverAdded = null;
  5576. };
  5577. /**
  5578. * Clone the current observable
  5579. */
  5580. Observable.prototype.clone = function () {
  5581. var result = new Observable();
  5582. result._observers = this._observers.slice(0);
  5583. return result;
  5584. };
  5585. /**
  5586. * Does this observable handles observer registered with a given mask
  5587. * @param {number} trigger - the mask to be tested
  5588. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5589. **/
  5590. Observable.prototype.hasSpecificMask = function (mask) {
  5591. if (mask === void 0) { mask = -1; }
  5592. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5593. var obs = _a[_i];
  5594. if (obs.mask & mask || obs.mask === mask) {
  5595. return true;
  5596. }
  5597. }
  5598. return false;
  5599. };
  5600. return Observable;
  5601. }());
  5602. BABYLON.Observable = Observable;
  5603. })(BABYLON || (BABYLON = {}));
  5604. //# sourceMappingURL=babylon.observable.js.map
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. var SmartArray = /** @class */ (function () {
  5608. function SmartArray(capacity) {
  5609. this.length = 0;
  5610. this._duplicateId = 0;
  5611. this.data = new Array(capacity);
  5612. this._id = SmartArray._GlobalId++;
  5613. }
  5614. SmartArray.prototype.push = function (value) {
  5615. this.data[this.length++] = value;
  5616. if (this.length > this.data.length) {
  5617. this.data.length *= 2;
  5618. }
  5619. if (!value.__smartArrayFlags) {
  5620. value.__smartArrayFlags = {};
  5621. }
  5622. value.__smartArrayFlags[this._id] = this._duplicateId;
  5623. };
  5624. SmartArray.prototype.forEach = function (func) {
  5625. for (var index = 0; index < this.length; index++) {
  5626. func(this.data[index]);
  5627. }
  5628. };
  5629. SmartArray.prototype.pushNoDuplicate = function (value) {
  5630. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5631. return false;
  5632. }
  5633. this.push(value);
  5634. return true;
  5635. };
  5636. SmartArray.prototype.sort = function (compareFn) {
  5637. this.data.sort(compareFn);
  5638. };
  5639. SmartArray.prototype.reset = function () {
  5640. this.length = 0;
  5641. this._duplicateId++;
  5642. };
  5643. SmartArray.prototype.dispose = function () {
  5644. this.reset();
  5645. if (this.data) {
  5646. this.data.length = 0;
  5647. this.data = [];
  5648. }
  5649. };
  5650. SmartArray.prototype.concat = function (array) {
  5651. if (array.length === 0) {
  5652. return;
  5653. }
  5654. if (this.length + array.length > this.data.length) {
  5655. this.data.length = (this.length + array.length) * 2;
  5656. }
  5657. for (var index = 0; index < array.length; index++) {
  5658. this.data[this.length++] = (array.data || array)[index];
  5659. }
  5660. };
  5661. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5662. if (array.length === 0) {
  5663. return;
  5664. }
  5665. if (this.length + array.length > this.data.length) {
  5666. this.data.length = (this.length + array.length) * 2;
  5667. }
  5668. for (var index = 0; index < array.length; index++) {
  5669. var item = (array.data || array)[index];
  5670. this.pushNoDuplicate(item);
  5671. }
  5672. };
  5673. SmartArray.prototype.indexOf = function (value) {
  5674. var position = this.data.indexOf(value);
  5675. if (position >= this.length) {
  5676. return -1;
  5677. }
  5678. return position;
  5679. };
  5680. SmartArray.prototype.contains = function (value) {
  5681. return this.data.indexOf(value) !== -1;
  5682. };
  5683. // Statics
  5684. SmartArray._GlobalId = 0;
  5685. return SmartArray;
  5686. }());
  5687. BABYLON.SmartArray = SmartArray;
  5688. })(BABYLON || (BABYLON = {}));
  5689. //# sourceMappingURL=babylon.smartArray.js.map
  5690. var BABYLON;
  5691. (function (BABYLON) {
  5692. // Screenshots
  5693. var screenshotCanvas;
  5694. var cloneValue = function (source, destinationObject) {
  5695. if (!source)
  5696. return null;
  5697. if (source instanceof BABYLON.Mesh) {
  5698. return null;
  5699. }
  5700. if (source instanceof BABYLON.SubMesh) {
  5701. return source.clone(destinationObject);
  5702. }
  5703. else if (source.clone) {
  5704. return source.clone();
  5705. }
  5706. return null;
  5707. };
  5708. var Tools = /** @class */ (function () {
  5709. function Tools() {
  5710. }
  5711. ;
  5712. /**
  5713. * Interpolates between a and b via alpha
  5714. * @param a The lower value (returned when alpha = 0)
  5715. * @param b The upper value (returned when alpha = 1)
  5716. * @param alpha The interpolation-factor
  5717. * @return The mixed value
  5718. */
  5719. Tools.Mix = function (a, b, alpha) {
  5720. return a * (1 - alpha) + b * alpha;
  5721. };
  5722. Tools.Instantiate = function (className) {
  5723. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5724. return Tools.RegisteredExternalClasses[className];
  5725. }
  5726. var arr = className.split(".");
  5727. var fn = (window || this);
  5728. for (var i = 0, len = arr.length; i < len; i++) {
  5729. fn = fn[arr[i]];
  5730. }
  5731. if (typeof fn !== "function") {
  5732. return null;
  5733. }
  5734. return fn;
  5735. };
  5736. Tools.SetImmediate = function (action) {
  5737. if (window.setImmediate) {
  5738. window.setImmediate(action);
  5739. }
  5740. else {
  5741. setTimeout(action, 1);
  5742. }
  5743. };
  5744. Tools.IsExponentOfTwo = function (value) {
  5745. var count = 1;
  5746. do {
  5747. count *= 2;
  5748. } while (count < value);
  5749. return count === value;
  5750. };
  5751. /**
  5752. * Find the next highest power of two.
  5753. * @param x Number to start search from.
  5754. * @return Next highest power of two.
  5755. */
  5756. Tools.CeilingPOT = function (x) {
  5757. x--;
  5758. x |= x >> 1;
  5759. x |= x >> 2;
  5760. x |= x >> 4;
  5761. x |= x >> 8;
  5762. x |= x >> 16;
  5763. x++;
  5764. return x;
  5765. };
  5766. /**
  5767. * Find the next lowest power of two.
  5768. * @param x Number to start search from.
  5769. * @return Next lowest power of two.
  5770. */
  5771. Tools.FloorPOT = function (x) {
  5772. x = x | (x >> 1);
  5773. x = x | (x >> 2);
  5774. x = x | (x >> 4);
  5775. x = x | (x >> 8);
  5776. x = x | (x >> 16);
  5777. return x - (x >> 1);
  5778. };
  5779. /**
  5780. * Find the nearest power of two.
  5781. * @param x Number to start search from.
  5782. * @return Next nearest power of two.
  5783. */
  5784. Tools.NearestPOT = function (x) {
  5785. var c = Tools.CeilingPOT(x);
  5786. var f = Tools.FloorPOT(x);
  5787. return (c - x) > (x - f) ? f : c;
  5788. };
  5789. Tools.GetExponentOfTwo = function (value, max, mode) {
  5790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5791. var pot;
  5792. switch (mode) {
  5793. case BABYLON.Engine.SCALEMODE_FLOOR:
  5794. pot = Tools.FloorPOT(value);
  5795. break;
  5796. case BABYLON.Engine.SCALEMODE_NEAREST:
  5797. pot = Tools.NearestPOT(value);
  5798. break;
  5799. case BABYLON.Engine.SCALEMODE_CEILING:
  5800. default:
  5801. pot = Tools.CeilingPOT(value);
  5802. break;
  5803. }
  5804. return Math.min(pot, max);
  5805. };
  5806. Tools.GetFilename = function (path) {
  5807. var index = path.lastIndexOf("/");
  5808. if (index < 0)
  5809. return path;
  5810. return path.substring(index + 1);
  5811. };
  5812. Tools.GetDOMTextContent = function (element) {
  5813. var result = "";
  5814. var child = element.firstChild;
  5815. while (child) {
  5816. if (child.nodeType === 3) {
  5817. result += child.textContent;
  5818. }
  5819. child = child.nextSibling;
  5820. }
  5821. return result;
  5822. };
  5823. Tools.ToDegrees = function (angle) {
  5824. return angle * 180 / Math.PI;
  5825. };
  5826. Tools.ToRadians = function (angle) {
  5827. return angle * Math.PI / 180;
  5828. };
  5829. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5830. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5831. var output = "";
  5832. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5833. var i = 0;
  5834. var bytes = new Uint8Array(buffer);
  5835. while (i < bytes.length) {
  5836. chr1 = bytes[i++];
  5837. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5838. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5839. enc1 = chr1 >> 2;
  5840. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5841. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5842. enc4 = chr3 & 63;
  5843. if (isNaN(chr2)) {
  5844. enc3 = enc4 = 64;
  5845. }
  5846. else if (isNaN(chr3)) {
  5847. enc4 = 64;
  5848. }
  5849. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5850. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5851. }
  5852. return "data:image/png;base64," + output;
  5853. };
  5854. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5855. if (bias === void 0) { bias = null; }
  5856. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5857. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5858. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5859. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5860. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5861. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5862. }
  5863. if (bias) {
  5864. minimum.x -= minimum.x * bias.x + bias.y;
  5865. minimum.y -= minimum.y * bias.x + bias.y;
  5866. minimum.z -= minimum.z * bias.x + bias.y;
  5867. maximum.x += maximum.x * bias.x + bias.y;
  5868. maximum.y += maximum.y * bias.x + bias.y;
  5869. maximum.z += maximum.z * bias.x + bias.y;
  5870. }
  5871. return {
  5872. minimum: minimum,
  5873. maximum: maximum
  5874. };
  5875. };
  5876. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5877. if (bias === void 0) { bias = null; }
  5878. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5879. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5880. if (!stride) {
  5881. stride = 3;
  5882. }
  5883. for (var index = start; index < start + count; index++) {
  5884. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5885. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5886. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5887. }
  5888. if (bias) {
  5889. minimum.x -= minimum.x * bias.x + bias.y;
  5890. minimum.y -= minimum.y * bias.x + bias.y;
  5891. minimum.z -= minimum.z * bias.x + bias.y;
  5892. maximum.x += maximum.x * bias.x + bias.y;
  5893. maximum.y += maximum.y * bias.x + bias.y;
  5894. maximum.z += maximum.z * bias.x + bias.y;
  5895. }
  5896. return {
  5897. minimum: minimum,
  5898. maximum: maximum
  5899. };
  5900. };
  5901. Tools.Vector2ArrayFeeder = function (array) {
  5902. return function (index) {
  5903. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5904. var length = isFloatArray ? array.length / 2 : array.length;
  5905. if (index >= length) {
  5906. return null;
  5907. }
  5908. if (isFloatArray) {
  5909. var fa = array;
  5910. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5911. }
  5912. var a = array;
  5913. return a[index];
  5914. };
  5915. };
  5916. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5917. if (bias === void 0) { bias = null; }
  5918. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5919. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5920. var i = 0;
  5921. var cur = feeder(i++);
  5922. while (cur) {
  5923. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5924. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5925. cur = feeder(i++);
  5926. }
  5927. if (bias) {
  5928. minimum.x -= minimum.x * bias.x + bias.y;
  5929. minimum.y -= minimum.y * bias.x + bias.y;
  5930. maximum.x += maximum.x * bias.x + bias.y;
  5931. maximum.y += maximum.y * bias.x + bias.y;
  5932. }
  5933. return {
  5934. minimum: minimum,
  5935. maximum: maximum
  5936. };
  5937. };
  5938. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5939. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5940. return null;
  5941. return Array.isArray(obj) ? obj : [obj];
  5942. };
  5943. // Misc.
  5944. Tools.GetPointerPrefix = function () {
  5945. var eventPrefix = "pointer";
  5946. // Check if pointer events are supported
  5947. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5948. eventPrefix = "mouse";
  5949. }
  5950. return eventPrefix;
  5951. };
  5952. /**
  5953. * @param func - the function to be called
  5954. * @param requester - the object that will request the next frame. Falls back to window.
  5955. */
  5956. Tools.QueueNewFrame = function (func, requester) {
  5957. if (!Tools.IsWindowObjectExist()) {
  5958. return setTimeout(func, 16);
  5959. }
  5960. if (!requester) {
  5961. requester = window;
  5962. }
  5963. if (requester.requestAnimationFrame) {
  5964. return requester.requestAnimationFrame(func);
  5965. }
  5966. else if (requester.msRequestAnimationFrame) {
  5967. return requester.msRequestAnimationFrame(func);
  5968. }
  5969. else if (requester.webkitRequestAnimationFrame) {
  5970. return requester.webkitRequestAnimationFrame(func);
  5971. }
  5972. else if (requester.mozRequestAnimationFrame) {
  5973. return requester.mozRequestAnimationFrame(func);
  5974. }
  5975. else if (requester.oRequestAnimationFrame) {
  5976. return requester.oRequestAnimationFrame(func);
  5977. }
  5978. else {
  5979. return window.setTimeout(func, 16);
  5980. }
  5981. };
  5982. Tools.RequestFullscreen = function (element) {
  5983. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5984. if (!requestFunction)
  5985. return;
  5986. requestFunction.call(element);
  5987. };
  5988. Tools.ExitFullscreen = function () {
  5989. if (document.exitFullscreen) {
  5990. document.exitFullscreen();
  5991. }
  5992. else if (document.mozCancelFullScreen) {
  5993. document.mozCancelFullScreen();
  5994. }
  5995. else if (document.webkitCancelFullScreen) {
  5996. document.webkitCancelFullScreen();
  5997. }
  5998. else if (document.msCancelFullScreen) {
  5999. document.msCancelFullScreen();
  6000. }
  6001. };
  6002. Tools.SetCorsBehavior = function (url, img) {
  6003. if (Tools.CorsBehavior) {
  6004. switch (typeof (Tools.CorsBehavior)) {
  6005. case "function":
  6006. var result = Tools.CorsBehavior(url);
  6007. if (result) {
  6008. img.crossOrigin = result;
  6009. }
  6010. break;
  6011. case "string":
  6012. default:
  6013. img.crossOrigin = Tools.CorsBehavior;
  6014. break;
  6015. }
  6016. }
  6017. };
  6018. // External files
  6019. Tools.CleanUrl = function (url) {
  6020. url = url.replace(/#/mg, "%23");
  6021. return url;
  6022. };
  6023. Tools.LoadImage = function (url, onLoad, onError, database) {
  6024. if (url instanceof ArrayBuffer) {
  6025. url = Tools.EncodeArrayBufferTobase64(url);
  6026. }
  6027. url = Tools.CleanUrl(url);
  6028. url = Tools.PreprocessUrl(url);
  6029. var img = new Image();
  6030. if (url.substr(0, 5) !== "data:") {
  6031. Tools.SetCorsBehavior(url, img);
  6032. }
  6033. img.onload = function () {
  6034. onLoad(img);
  6035. };
  6036. img.onerror = function (err) {
  6037. Tools.Error("Error while trying to load image: " + url);
  6038. if (Tools.UseFallbackTexture) {
  6039. img.src = Tools.fallbackTexture;
  6040. onLoad(img);
  6041. }
  6042. else {
  6043. onError("Error while trying to load image: " + url, err);
  6044. }
  6045. };
  6046. var noIndexedDB = function () {
  6047. img.src = url;
  6048. };
  6049. var loadFromIndexedDB = function () {
  6050. if (database) {
  6051. database.loadImageFromDB(url, img);
  6052. }
  6053. };
  6054. //ANY database to do!
  6055. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6056. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6057. }
  6058. else {
  6059. if (url.indexOf("file:") !== 0) {
  6060. noIndexedDB();
  6061. }
  6062. else {
  6063. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6064. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6065. try {
  6066. var blobURL;
  6067. try {
  6068. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6069. }
  6070. catch (ex) {
  6071. // Chrome doesn't support oneTimeOnly parameter
  6072. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6073. }
  6074. img.src = blobURL;
  6075. }
  6076. catch (e) {
  6077. img.src = "";
  6078. }
  6079. }
  6080. else {
  6081. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6082. img.src = Tools.fallbackTexture;
  6083. }
  6084. }
  6085. }
  6086. return img;
  6087. };
  6088. //ANY
  6089. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6090. url = Tools.CleanUrl(url);
  6091. url = Tools.PreprocessUrl(url);
  6092. var request = null;
  6093. var noIndexedDB = function () {
  6094. request = new XMLHttpRequest();
  6095. var loadUrl = Tools.BaseUrl + url;
  6096. request.open('GET', loadUrl, true);
  6097. if (useArrayBuffer) {
  6098. request.responseType = "arraybuffer";
  6099. }
  6100. if (progressCallBack) {
  6101. request.onprogress = progressCallBack;
  6102. }
  6103. request.onreadystatechange = function () {
  6104. var req = request;
  6105. // In case of undefined state in some browsers.
  6106. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6107. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6108. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6109. callback(!useArrayBuffer ? req.responseText : req.response);
  6110. }
  6111. else {
  6112. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6113. if (onError) {
  6114. onError(req, e);
  6115. }
  6116. else {
  6117. throw e;
  6118. }
  6119. }
  6120. }
  6121. };
  6122. request.send(null);
  6123. };
  6124. var loadFromIndexedDB = function () {
  6125. if (database) {
  6126. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6127. }
  6128. };
  6129. if (url.indexOf("file:") !== -1) {
  6130. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6131. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6132. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6133. }
  6134. else {
  6135. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6136. if (onError) {
  6137. var e = new Error(errorMessage);
  6138. onError(undefined, e);
  6139. }
  6140. else {
  6141. Tools.Error(errorMessage);
  6142. }
  6143. }
  6144. }
  6145. else {
  6146. // Caching all files
  6147. if (database && database.enableSceneOffline) {
  6148. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6149. }
  6150. else {
  6151. noIndexedDB();
  6152. }
  6153. }
  6154. return request;
  6155. };
  6156. /**
  6157. * Load a script (identified by an url). When the url returns, the
  6158. * content of this file is added into a new script element, attached to the DOM (body element)
  6159. */
  6160. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6161. var head = document.getElementsByTagName('head')[0];
  6162. var script = document.createElement('script');
  6163. script.type = 'text/javascript';
  6164. script.src = scriptUrl;
  6165. script.onload = function () {
  6166. if (onSuccess) {
  6167. onSuccess();
  6168. }
  6169. };
  6170. script.onerror = function (e) {
  6171. if (onError) {
  6172. onError("Unable to load script", e);
  6173. }
  6174. };
  6175. head.appendChild(script);
  6176. };
  6177. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6178. var reader = new FileReader();
  6179. reader.onload = function (e) {
  6180. //target doesn't have result from ts 1.3
  6181. callback(e.target['result']);
  6182. };
  6183. reader.onprogress = progressCallback;
  6184. reader.readAsDataURL(fileToLoad);
  6185. };
  6186. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6187. var reader = new FileReader();
  6188. reader.onerror = function (e) {
  6189. Tools.Log("Error while reading file: " + fileToLoad.name);
  6190. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6191. };
  6192. reader.onload = function (e) {
  6193. //target doesn't have result from ts 1.3
  6194. callback(e.target['result']);
  6195. };
  6196. if (progressCallBack) {
  6197. reader.onprogress = progressCallBack;
  6198. }
  6199. if (!useArrayBuffer) {
  6200. // Asynchronous read
  6201. reader.readAsText(fileToLoad);
  6202. }
  6203. else {
  6204. reader.readAsArrayBuffer(fileToLoad);
  6205. }
  6206. };
  6207. //returns a downloadable url to a file content.
  6208. Tools.FileAsURL = function (content) {
  6209. var fileBlob = new Blob([content]);
  6210. var url = window.URL || window.webkitURL;
  6211. var link = url.createObjectURL(fileBlob);
  6212. return link;
  6213. };
  6214. // Misc.
  6215. Tools.Format = function (value, decimals) {
  6216. if (decimals === void 0) { decimals = 2; }
  6217. return value.toFixed(decimals);
  6218. };
  6219. Tools.CheckExtends = function (v, min, max) {
  6220. if (v.x < min.x)
  6221. min.x = v.x;
  6222. if (v.y < min.y)
  6223. min.y = v.y;
  6224. if (v.z < min.z)
  6225. min.z = v.z;
  6226. if (v.x > max.x)
  6227. max.x = v.x;
  6228. if (v.y > max.y)
  6229. max.y = v.y;
  6230. if (v.z > max.z)
  6231. max.z = v.z;
  6232. };
  6233. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6234. for (var prop in source) {
  6235. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6236. continue;
  6237. }
  6238. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6239. continue;
  6240. }
  6241. var sourceValue = source[prop];
  6242. var typeOfSourceValue = typeof sourceValue;
  6243. if (typeOfSourceValue === "function") {
  6244. continue;
  6245. }
  6246. if (typeOfSourceValue === "object") {
  6247. if (sourceValue instanceof Array) {
  6248. destination[prop] = [];
  6249. if (sourceValue.length > 0) {
  6250. if (typeof sourceValue[0] == "object") {
  6251. for (var index = 0; index < sourceValue.length; index++) {
  6252. var clonedValue = cloneValue(sourceValue[index], destination);
  6253. if (destination[prop].indexOf(clonedValue) === -1) {
  6254. destination[prop].push(clonedValue);
  6255. }
  6256. }
  6257. }
  6258. else {
  6259. destination[prop] = sourceValue.slice(0);
  6260. }
  6261. }
  6262. }
  6263. else {
  6264. destination[prop] = cloneValue(sourceValue, destination);
  6265. }
  6266. }
  6267. else {
  6268. destination[prop] = sourceValue;
  6269. }
  6270. }
  6271. };
  6272. Tools.IsEmpty = function (obj) {
  6273. for (var i in obj) {
  6274. if (obj.hasOwnProperty(i)) {
  6275. return false;
  6276. }
  6277. }
  6278. return true;
  6279. };
  6280. Tools.RegisterTopRootEvents = function (events) {
  6281. for (var index = 0; index < events.length; index++) {
  6282. var event = events[index];
  6283. window.addEventListener(event.name, event.handler, false);
  6284. try {
  6285. if (window.parent) {
  6286. window.parent.addEventListener(event.name, event.handler, false);
  6287. }
  6288. }
  6289. catch (e) {
  6290. // Silently fails...
  6291. }
  6292. }
  6293. };
  6294. Tools.UnregisterTopRootEvents = function (events) {
  6295. for (var index = 0; index < events.length; index++) {
  6296. var event = events[index];
  6297. window.removeEventListener(event.name, event.handler);
  6298. try {
  6299. if (window.parent) {
  6300. window.parent.removeEventListener(event.name, event.handler);
  6301. }
  6302. }
  6303. catch (e) {
  6304. // Silently fails...
  6305. }
  6306. }
  6307. };
  6308. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6309. if (mimeType === void 0) { mimeType = "image/png"; }
  6310. // Read the contents of the framebuffer
  6311. var numberOfChannelsByLine = width * 4;
  6312. var halfHeight = height / 2;
  6313. //Reading datas from WebGL
  6314. var data = engine.readPixels(0, 0, width, height);
  6315. //To flip image on Y axis.
  6316. for (var i = 0; i < halfHeight; i++) {
  6317. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6318. var currentCell = j + i * numberOfChannelsByLine;
  6319. var targetLine = height - i - 1;
  6320. var targetCell = j + targetLine * numberOfChannelsByLine;
  6321. var temp = data[currentCell];
  6322. data[currentCell] = data[targetCell];
  6323. data[targetCell] = temp;
  6324. }
  6325. }
  6326. // Create a 2D canvas to store the result
  6327. if (!screenshotCanvas) {
  6328. screenshotCanvas = document.createElement('canvas');
  6329. }
  6330. screenshotCanvas.width = width;
  6331. screenshotCanvas.height = height;
  6332. var context = screenshotCanvas.getContext('2d');
  6333. if (context) {
  6334. // Copy the pixels to a 2D canvas
  6335. var imageData = context.createImageData(width, height);
  6336. var castData = (imageData.data);
  6337. castData.set(data);
  6338. context.putImageData(imageData, 0, 0);
  6339. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6340. }
  6341. };
  6342. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6343. if (mimeType === void 0) { mimeType = "image/png"; }
  6344. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6345. if (successCallback) {
  6346. successCallback(base64Image);
  6347. }
  6348. else {
  6349. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6350. if (("download" in document.createElement("a"))) {
  6351. var a = window.document.createElement("a");
  6352. a.href = base64Image;
  6353. var date = new Date();
  6354. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6355. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6356. window.document.body.appendChild(a);
  6357. a.addEventListener("click", function () {
  6358. if (a.parentElement) {
  6359. a.parentElement.removeChild(a);
  6360. }
  6361. });
  6362. a.click();
  6363. //Or opening a new tab with the image if it is not possible to automatically start download.
  6364. }
  6365. else {
  6366. var newWindow = window.open("");
  6367. var img = newWindow.document.createElement("img");
  6368. img.src = base64Image;
  6369. newWindow.document.body.appendChild(img);
  6370. }
  6371. }
  6372. };
  6373. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6374. if (mimeType === void 0) { mimeType = "image/png"; }
  6375. var width;
  6376. var height;
  6377. // If a precision value is specified
  6378. if (size.precision) {
  6379. width = Math.round(engine.getRenderWidth() * size.precision);
  6380. height = Math.round(width / engine.getAspectRatio(camera));
  6381. }
  6382. else if (size.width && size.height) {
  6383. width = size.width;
  6384. height = size.height;
  6385. }
  6386. else if (size.width && !size.height) {
  6387. width = size.width;
  6388. height = Math.round(width / engine.getAspectRatio(camera));
  6389. }
  6390. else if (size.height && !size.width) {
  6391. height = size.height;
  6392. width = Math.round(height * engine.getAspectRatio(camera));
  6393. }
  6394. else if (!isNaN(size)) {
  6395. height = size;
  6396. width = size;
  6397. }
  6398. else {
  6399. Tools.Error("Invalid 'size' parameter !");
  6400. return;
  6401. }
  6402. if (!screenshotCanvas) {
  6403. screenshotCanvas = document.createElement('canvas');
  6404. }
  6405. screenshotCanvas.width = width;
  6406. screenshotCanvas.height = height;
  6407. var renderContext = screenshotCanvas.getContext("2d");
  6408. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6409. var newWidth = width;
  6410. var newHeight = newWidth / ratio;
  6411. if (newHeight > height) {
  6412. newHeight = height;
  6413. newWidth = newHeight * ratio;
  6414. }
  6415. var offsetX = Math.max(0, width - newWidth) / 2;
  6416. var offsetY = Math.max(0, height - newHeight) / 2;
  6417. var renderingCanvas = engine.getRenderingCanvas();
  6418. if (renderContext && renderingCanvas) {
  6419. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6420. }
  6421. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6422. };
  6423. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6424. if (mimeType === void 0) { mimeType = "image/png"; }
  6425. if (samples === void 0) { samples = 1; }
  6426. var width;
  6427. var height;
  6428. //If a precision value is specified
  6429. if (size.precision) {
  6430. width = Math.round(engine.getRenderWidth() * size.precision);
  6431. height = Math.round(width / engine.getAspectRatio(camera));
  6432. size = { width: width, height: height };
  6433. }
  6434. else if (size.width && size.height) {
  6435. width = size.width;
  6436. height = size.height;
  6437. }
  6438. else if (size.width && !size.height) {
  6439. width = size.width;
  6440. height = Math.round(width / engine.getAspectRatio(camera));
  6441. size = { width: width, height: height };
  6442. }
  6443. else if (size.height && !size.width) {
  6444. height = size.height;
  6445. width = Math.round(height * engine.getAspectRatio(camera));
  6446. size = { width: width, height: height };
  6447. }
  6448. else if (!isNaN(size)) {
  6449. height = size;
  6450. width = size;
  6451. }
  6452. else {
  6453. Tools.Error("Invalid 'size' parameter !");
  6454. return;
  6455. }
  6456. var scene = camera.getScene();
  6457. var previousCamera = null;
  6458. if (scene.activeCamera !== camera) {
  6459. previousCamera = scene.activeCamera;
  6460. scene.activeCamera = camera;
  6461. }
  6462. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6463. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6464. texture.renderList = null;
  6465. texture.samples = samples;
  6466. texture.onAfterRenderObservable.add(function () {
  6467. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6468. });
  6469. scene.incrementRenderId();
  6470. scene.resetCachedMaterial();
  6471. texture.render(true);
  6472. texture.dispose();
  6473. if (previousCamera) {
  6474. scene.activeCamera = previousCamera;
  6475. }
  6476. camera.getProjectionMatrix(true); // Force cache refresh;
  6477. };
  6478. // XHR response validator for local file scenario
  6479. Tools.ValidateXHRData = function (xhr, dataType) {
  6480. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6481. if (dataType === void 0) { dataType = 7; }
  6482. try {
  6483. if (dataType & 1) {
  6484. if (xhr.responseText && xhr.responseText.length > 0) {
  6485. return true;
  6486. }
  6487. else if (dataType === 1) {
  6488. return false;
  6489. }
  6490. }
  6491. if (dataType & 2) {
  6492. // Check header width and height since there is no "TGA" magic number
  6493. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6494. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6495. return true;
  6496. }
  6497. else if (dataType === 2) {
  6498. return false;
  6499. }
  6500. }
  6501. if (dataType & 4) {
  6502. // Check for the "DDS" magic number
  6503. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6504. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6505. return true;
  6506. }
  6507. else {
  6508. return false;
  6509. }
  6510. }
  6511. }
  6512. catch (e) {
  6513. // Global protection
  6514. }
  6515. return false;
  6516. };
  6517. /**
  6518. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6519. * Be aware Math.random() could cause collisions, but:
  6520. * "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"
  6521. */
  6522. Tools.RandomId = function () {
  6523. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6524. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6525. return v.toString(16);
  6526. });
  6527. };
  6528. Object.defineProperty(Tools, "NoneLogLevel", {
  6529. get: function () {
  6530. return Tools._NoneLogLevel;
  6531. },
  6532. enumerable: true,
  6533. configurable: true
  6534. });
  6535. Object.defineProperty(Tools, "MessageLogLevel", {
  6536. get: function () {
  6537. return Tools._MessageLogLevel;
  6538. },
  6539. enumerable: true,
  6540. configurable: true
  6541. });
  6542. Object.defineProperty(Tools, "WarningLogLevel", {
  6543. get: function () {
  6544. return Tools._WarningLogLevel;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(Tools, "ErrorLogLevel", {
  6550. get: function () {
  6551. return Tools._ErrorLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "AllLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Tools._AddLogEntry = function (entry) {
  6564. Tools._LogCache = entry + Tools._LogCache;
  6565. if (Tools.OnNewCacheEntry) {
  6566. Tools.OnNewCacheEntry(entry);
  6567. }
  6568. };
  6569. Tools._FormatMessage = function (message) {
  6570. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6571. var date = new Date();
  6572. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6573. };
  6574. Tools._LogDisabled = function (message) {
  6575. // nothing to do
  6576. };
  6577. Tools._LogEnabled = function (message) {
  6578. var formattedMessage = Tools._FormatMessage(message);
  6579. console.log("BJS - " + formattedMessage);
  6580. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6581. Tools._AddLogEntry(entry);
  6582. };
  6583. Tools._WarnDisabled = function (message) {
  6584. // nothing to do
  6585. };
  6586. Tools._WarnEnabled = function (message) {
  6587. var formattedMessage = Tools._FormatMessage(message);
  6588. console.warn("BJS - " + formattedMessage);
  6589. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6590. Tools._AddLogEntry(entry);
  6591. };
  6592. Tools._ErrorDisabled = function (message) {
  6593. // nothing to do
  6594. };
  6595. Tools._ErrorEnabled = function (message) {
  6596. Tools.errorsCount++;
  6597. var formattedMessage = Tools._FormatMessage(message);
  6598. console.error("BJS - " + formattedMessage);
  6599. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6600. Tools._AddLogEntry(entry);
  6601. };
  6602. Object.defineProperty(Tools, "LogCache", {
  6603. get: function () {
  6604. return Tools._LogCache;
  6605. },
  6606. enumerable: true,
  6607. configurable: true
  6608. });
  6609. Tools.ClearLogCache = function () {
  6610. Tools._LogCache = "";
  6611. Tools.errorsCount = 0;
  6612. };
  6613. Object.defineProperty(Tools, "LogLevels", {
  6614. set: function (level) {
  6615. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6616. Tools.Log = Tools._LogEnabled;
  6617. }
  6618. else {
  6619. Tools.Log = Tools._LogDisabled;
  6620. }
  6621. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6622. Tools.Warn = Tools._WarnEnabled;
  6623. }
  6624. else {
  6625. Tools.Warn = Tools._WarnDisabled;
  6626. }
  6627. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6628. Tools.Error = Tools._ErrorEnabled;
  6629. }
  6630. else {
  6631. Tools.Error = Tools._ErrorDisabled;
  6632. }
  6633. },
  6634. enumerable: true,
  6635. configurable: true
  6636. });
  6637. Tools.IsWindowObjectExist = function () {
  6638. return (typeof window) !== "undefined";
  6639. };
  6640. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6641. get: function () {
  6642. return Tools._PerformanceNoneLogLevel;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6648. get: function () {
  6649. return Tools._PerformanceUserMarkLogLevel;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6655. get: function () {
  6656. return Tools._PerformanceConsoleLogLevel;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6662. set: function (level) {
  6663. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6664. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6665. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6666. return;
  6667. }
  6668. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6669. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6670. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6671. return;
  6672. }
  6673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6675. },
  6676. enumerable: true,
  6677. configurable: true
  6678. });
  6679. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6680. };
  6681. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6682. };
  6683. Tools._StartUserMark = function (counterName, condition) {
  6684. if (condition === void 0) { condition = true; }
  6685. if (!Tools._performance) {
  6686. if (!Tools.IsWindowObjectExist()) {
  6687. return;
  6688. }
  6689. Tools._performance = window.performance;
  6690. }
  6691. if (!condition || !Tools._performance.mark) {
  6692. return;
  6693. }
  6694. Tools._performance.mark(counterName + "-Begin");
  6695. };
  6696. Tools._EndUserMark = function (counterName, condition) {
  6697. if (condition === void 0) { condition = true; }
  6698. if (!condition || !Tools._performance.mark) {
  6699. return;
  6700. }
  6701. Tools._performance.mark(counterName + "-End");
  6702. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6703. };
  6704. Tools._StartPerformanceConsole = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!condition) {
  6707. return;
  6708. }
  6709. Tools._StartUserMark(counterName, condition);
  6710. if (console.time) {
  6711. console.time(counterName);
  6712. }
  6713. };
  6714. Tools._EndPerformanceConsole = function (counterName, condition) {
  6715. if (condition === void 0) { condition = true; }
  6716. if (!condition) {
  6717. return;
  6718. }
  6719. Tools._EndUserMark(counterName, condition);
  6720. if (console.time) {
  6721. console.timeEnd(counterName);
  6722. }
  6723. };
  6724. Object.defineProperty(Tools, "Now", {
  6725. get: function () {
  6726. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6727. return window.performance.now();
  6728. }
  6729. return new Date().getTime();
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * This method will return the name of the class used to create the instance of the given object.
  6736. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6737. * @param object the object to get the class name from
  6738. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6739. */
  6740. Tools.GetClassName = function (object, isType) {
  6741. if (isType === void 0) { isType = false; }
  6742. var name = null;
  6743. if (!isType && object.getClassName) {
  6744. name = object.getClassName();
  6745. }
  6746. else {
  6747. if (object instanceof Object) {
  6748. var classObj = isType ? object : Object.getPrototypeOf(object);
  6749. name = classObj.constructor["__bjsclassName__"];
  6750. }
  6751. if (!name) {
  6752. name = typeof object;
  6753. }
  6754. }
  6755. return name;
  6756. };
  6757. Tools.First = function (array, predicate) {
  6758. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6759. var el = array_1[_i];
  6760. if (predicate(el)) {
  6761. return el;
  6762. }
  6763. }
  6764. return null;
  6765. };
  6766. /**
  6767. * This method will return the name of the full name of the class, including its owning module (if any).
  6768. * 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).
  6769. * @param object the object to get the class name from
  6770. * @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.
  6771. */
  6772. Tools.getFullClassName = function (object, isType) {
  6773. if (isType === void 0) { isType = false; }
  6774. var className = null;
  6775. var moduleName = null;
  6776. if (!isType && object.getClassName) {
  6777. className = object.getClassName();
  6778. }
  6779. else {
  6780. if (object instanceof Object) {
  6781. var classObj = isType ? object : Object.getPrototypeOf(object);
  6782. className = classObj.constructor["__bjsclassName__"];
  6783. moduleName = classObj.constructor["__bjsmoduleName__"];
  6784. }
  6785. if (!className) {
  6786. className = typeof object;
  6787. }
  6788. }
  6789. if (!className) {
  6790. return null;
  6791. }
  6792. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6793. };
  6794. /**
  6795. * 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.
  6796. * @param array
  6797. */
  6798. Tools.arrayOrStringFeeder = function (array) {
  6799. return function (index) {
  6800. if (index >= array.length) {
  6801. return null;
  6802. }
  6803. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6804. if (val && val.getHashCode) {
  6805. val = val.getHashCode();
  6806. }
  6807. if (typeof val === "string") {
  6808. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6809. }
  6810. return val;
  6811. };
  6812. };
  6813. /**
  6814. * Compute the hashCode of a stream of number
  6815. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6816. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6817. * @return the hash code computed
  6818. */
  6819. Tools.hashCodeFromStream = function (feeder) {
  6820. // Based from here: http://stackoverflow.com/a/7616484/802124
  6821. var hash = 0;
  6822. var index = 0;
  6823. var chr = feeder(index++);
  6824. while (chr != null) {
  6825. hash = ((hash << 5) - hash) + chr;
  6826. hash |= 0; // Convert to 32bit integer
  6827. chr = feeder(index++);
  6828. }
  6829. return hash;
  6830. };
  6831. Tools.BaseUrl = "";
  6832. Tools.CorsBehavior = "anonymous";
  6833. Tools.UseFallbackTexture = true;
  6834. /**
  6835. * Use this object to register external classes like custom textures or material
  6836. * to allow the laoders to instantiate them
  6837. */
  6838. Tools.RegisteredExternalClasses = {};
  6839. // Used in case of a texture loading problem
  6840. 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";
  6841. Tools.PreprocessUrl = function (url) {
  6842. return url;
  6843. };
  6844. // Logs
  6845. Tools._NoneLogLevel = 0;
  6846. Tools._MessageLogLevel = 1;
  6847. Tools._WarningLogLevel = 2;
  6848. Tools._ErrorLogLevel = 4;
  6849. Tools._LogCache = "";
  6850. Tools.errorsCount = 0;
  6851. Tools.Log = Tools._LogEnabled;
  6852. Tools.Warn = Tools._WarnEnabled;
  6853. Tools.Error = Tools._ErrorEnabled;
  6854. // Performances
  6855. Tools._PerformanceNoneLogLevel = 0;
  6856. Tools._PerformanceUserMarkLogLevel = 1;
  6857. Tools._PerformanceConsoleLogLevel = 2;
  6858. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6859. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6860. return Tools;
  6861. }());
  6862. BABYLON.Tools = Tools;
  6863. /**
  6864. * This class is used to track a performance counter which is number based.
  6865. * The user has access to many properties which give statistics of different nature
  6866. *
  6867. * The implementer can track two kinds of Performance Counter: time and count
  6868. * 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.
  6869. * 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.
  6870. */
  6871. var PerfCounter = /** @class */ (function () {
  6872. function PerfCounter() {
  6873. this._startMonitoringTime = 0;
  6874. this._min = 0;
  6875. this._max = 0;
  6876. this._average = 0;
  6877. this._lastSecAverage = 0;
  6878. this._current = 0;
  6879. this._totalValueCount = 0;
  6880. this._totalAccumulated = 0;
  6881. this._lastSecAccumulated = 0;
  6882. this._lastSecTime = 0;
  6883. this._lastSecValueCount = 0;
  6884. }
  6885. Object.defineProperty(PerfCounter.prototype, "min", {
  6886. /**
  6887. * Returns the smallest value ever
  6888. */
  6889. get: function () {
  6890. return this._min;
  6891. },
  6892. enumerable: true,
  6893. configurable: true
  6894. });
  6895. Object.defineProperty(PerfCounter.prototype, "max", {
  6896. /**
  6897. * Returns the biggest value ever
  6898. */
  6899. get: function () {
  6900. return this._max;
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(PerfCounter.prototype, "average", {
  6906. /**
  6907. * Returns the average value since the performance counter is running
  6908. */
  6909. get: function () {
  6910. return this._average;
  6911. },
  6912. enumerable: true,
  6913. configurable: true
  6914. });
  6915. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6916. /**
  6917. * Returns the average value of the last second the counter was monitored
  6918. */
  6919. get: function () {
  6920. return this._lastSecAverage;
  6921. },
  6922. enumerable: true,
  6923. configurable: true
  6924. });
  6925. Object.defineProperty(PerfCounter.prototype, "current", {
  6926. /**
  6927. * Returns the current value
  6928. */
  6929. get: function () {
  6930. return this._current;
  6931. },
  6932. enumerable: true,
  6933. configurable: true
  6934. });
  6935. Object.defineProperty(PerfCounter.prototype, "total", {
  6936. get: function () {
  6937. return this._totalAccumulated;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(PerfCounter.prototype, "count", {
  6943. get: function () {
  6944. return this._totalValueCount;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. /**
  6950. * Call this method to start monitoring a new frame.
  6951. * 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.
  6952. */
  6953. PerfCounter.prototype.fetchNewFrame = function () {
  6954. this._totalValueCount++;
  6955. this._current = 0;
  6956. this._lastSecValueCount++;
  6957. };
  6958. /**
  6959. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6960. * @param newCount the count value to add to the monitored count
  6961. * @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.
  6962. */
  6963. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6964. if (!PerfCounter.Enabled) {
  6965. return;
  6966. }
  6967. this._current += newCount;
  6968. if (fetchResult) {
  6969. this._fetchResult();
  6970. }
  6971. };
  6972. /**
  6973. * Start monitoring this performance counter
  6974. */
  6975. PerfCounter.prototype.beginMonitoring = function () {
  6976. if (!PerfCounter.Enabled) {
  6977. return;
  6978. }
  6979. this._startMonitoringTime = Tools.Now;
  6980. };
  6981. /**
  6982. * Compute the time lapsed since the previous beginMonitoring() call.
  6983. * @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
  6984. */
  6985. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6986. if (newFrame === void 0) { newFrame = true; }
  6987. if (!PerfCounter.Enabled) {
  6988. return;
  6989. }
  6990. if (newFrame) {
  6991. this.fetchNewFrame();
  6992. }
  6993. var currentTime = Tools.Now;
  6994. this._current = currentTime - this._startMonitoringTime;
  6995. if (newFrame) {
  6996. this._fetchResult();
  6997. }
  6998. };
  6999. PerfCounter.prototype._fetchResult = function () {
  7000. this._totalAccumulated += this._current;
  7001. this._lastSecAccumulated += this._current;
  7002. // Min/Max update
  7003. this._min = Math.min(this._min, this._current);
  7004. this._max = Math.max(this._max, this._current);
  7005. this._average = this._totalAccumulated / this._totalValueCount;
  7006. // Reset last sec?
  7007. var now = Tools.Now;
  7008. if ((now - this._lastSecTime) > 1000) {
  7009. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7010. this._lastSecTime = now;
  7011. this._lastSecAccumulated = 0;
  7012. this._lastSecValueCount = 0;
  7013. }
  7014. };
  7015. PerfCounter.Enabled = true;
  7016. return PerfCounter;
  7017. }());
  7018. BABYLON.PerfCounter = PerfCounter;
  7019. /**
  7020. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7021. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7022. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7023. * @param name The name of the class, case should be preserved
  7024. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7025. */
  7026. function className(name, module) {
  7027. return function (target) {
  7028. target["__bjsclassName__"] = name;
  7029. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7030. };
  7031. }
  7032. BABYLON.className = className;
  7033. /**
  7034. * An implementation of a loop for asynchronous functions.
  7035. */
  7036. var AsyncLoop = /** @class */ (function () {
  7037. /**
  7038. * Constroctor.
  7039. * @param iterations the number of iterations.
  7040. * @param _fn the function to run each iteration
  7041. * @param _successCallback the callback that will be called upon succesful execution
  7042. * @param offset starting offset.
  7043. */
  7044. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7045. if (offset === void 0) { offset = 0; }
  7046. this.iterations = iterations;
  7047. this._fn = _fn;
  7048. this._successCallback = _successCallback;
  7049. this.index = offset - 1;
  7050. this._done = false;
  7051. }
  7052. /**
  7053. * Execute the next iteration. Must be called after the last iteration was finished.
  7054. */
  7055. AsyncLoop.prototype.executeNext = function () {
  7056. if (!this._done) {
  7057. if (this.index + 1 < this.iterations) {
  7058. ++this.index;
  7059. this._fn(this);
  7060. }
  7061. else {
  7062. this.breakLoop();
  7063. }
  7064. }
  7065. };
  7066. /**
  7067. * Break the loop and run the success callback.
  7068. */
  7069. AsyncLoop.prototype.breakLoop = function () {
  7070. this._done = true;
  7071. this._successCallback();
  7072. };
  7073. /**
  7074. * Helper function
  7075. */
  7076. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7077. if (offset === void 0) { offset = 0; }
  7078. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7079. loop.executeNext();
  7080. return loop;
  7081. };
  7082. /**
  7083. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7084. * @param iterations total number of iterations
  7085. * @param syncedIterations number of synchronous iterations in each async iteration.
  7086. * @param fn the function to call each iteration.
  7087. * @param callback a success call back that will be called when iterating stops.
  7088. * @param breakFunction a break condition (optional)
  7089. * @param timeout timeout settings for the setTimeout function. default - 0.
  7090. * @constructor
  7091. */
  7092. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7093. if (timeout === void 0) { timeout = 0; }
  7094. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7095. if (breakFunction && breakFunction())
  7096. loop.breakLoop();
  7097. else {
  7098. setTimeout(function () {
  7099. for (var i = 0; i < syncedIterations; ++i) {
  7100. var iteration = (loop.index * syncedIterations) + i;
  7101. if (iteration >= iterations)
  7102. break;
  7103. fn(iteration);
  7104. if (breakFunction && breakFunction()) {
  7105. loop.breakLoop();
  7106. break;
  7107. }
  7108. }
  7109. loop.executeNext();
  7110. }, timeout);
  7111. }
  7112. }, callback);
  7113. };
  7114. return AsyncLoop;
  7115. }());
  7116. BABYLON.AsyncLoop = AsyncLoop;
  7117. })(BABYLON || (BABYLON = {}));
  7118. //# sourceMappingURL=babylon.tools.js.map
  7119. var BABYLON;
  7120. (function (BABYLON) {
  7121. var Internals;
  7122. (function (Internals) {
  7123. var _AlphaState = /** @class */ (function () {
  7124. /**
  7125. * Initializes the state.
  7126. */
  7127. function _AlphaState() {
  7128. this._isAlphaBlendDirty = false;
  7129. this._isBlendFunctionParametersDirty = false;
  7130. this._isBlendEquationParametersDirty = false;
  7131. this._isBlendConstantsDirty = false;
  7132. this._alphaBlend = false;
  7133. this._blendFunctionParameters = new Array(4);
  7134. this._blendEquationParameters = new Array(2);
  7135. this._blendConstants = new Array(4);
  7136. this.reset();
  7137. }
  7138. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7139. get: function () {
  7140. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7141. },
  7142. enumerable: true,
  7143. configurable: true
  7144. });
  7145. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7146. get: function () {
  7147. return this._alphaBlend;
  7148. },
  7149. set: function (value) {
  7150. if (this._alphaBlend === value) {
  7151. return;
  7152. }
  7153. this._alphaBlend = value;
  7154. this._isAlphaBlendDirty = true;
  7155. },
  7156. enumerable: true,
  7157. configurable: true
  7158. });
  7159. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7160. if (this._blendConstants[0] === r &&
  7161. this._blendConstants[1] === g &&
  7162. this._blendConstants[2] === b &&
  7163. this._blendConstants[3] === a) {
  7164. return;
  7165. }
  7166. this._blendConstants[0] = r;
  7167. this._blendConstants[1] = g;
  7168. this._blendConstants[2] = b;
  7169. this._blendConstants[3] = a;
  7170. this._isBlendConstantsDirty = true;
  7171. };
  7172. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7173. if (this._blendFunctionParameters[0] === value0 &&
  7174. this._blendFunctionParameters[1] === value1 &&
  7175. this._blendFunctionParameters[2] === value2 &&
  7176. this._blendFunctionParameters[3] === value3) {
  7177. return;
  7178. }
  7179. this._blendFunctionParameters[0] = value0;
  7180. this._blendFunctionParameters[1] = value1;
  7181. this._blendFunctionParameters[2] = value2;
  7182. this._blendFunctionParameters[3] = value3;
  7183. this._isBlendFunctionParametersDirty = true;
  7184. };
  7185. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7186. if (this._blendEquationParameters[0] === rgb &&
  7187. this._blendEquationParameters[1] === alpha) {
  7188. return;
  7189. }
  7190. this._blendEquationParameters[0] = rgb;
  7191. this._blendEquationParameters[1] = alpha;
  7192. this._isBlendEquationParametersDirty = true;
  7193. };
  7194. _AlphaState.prototype.reset = function () {
  7195. this._alphaBlend = false;
  7196. this._blendFunctionParameters[0] = null;
  7197. this._blendFunctionParameters[1] = null;
  7198. this._blendFunctionParameters[2] = null;
  7199. this._blendFunctionParameters[3] = null;
  7200. this._blendEquationParameters[0] = null;
  7201. this._blendEquationParameters[1] = null;
  7202. this._blendConstants[0] = null;
  7203. this._blendConstants[1] = null;
  7204. this._blendConstants[2] = null;
  7205. this._blendConstants[3] = null;
  7206. this._isAlphaBlendDirty = true;
  7207. this._isBlendFunctionParametersDirty = false;
  7208. this._isBlendEquationParametersDirty = false;
  7209. this._isBlendConstantsDirty = false;
  7210. };
  7211. _AlphaState.prototype.apply = function (gl) {
  7212. if (!this.isDirty) {
  7213. return;
  7214. }
  7215. // Alpha blend
  7216. if (this._isAlphaBlendDirty) {
  7217. if (this._alphaBlend) {
  7218. gl.enable(gl.BLEND);
  7219. }
  7220. else {
  7221. gl.disable(gl.BLEND);
  7222. }
  7223. this._isAlphaBlendDirty = false;
  7224. }
  7225. // Alpha function
  7226. if (this._isBlendFunctionParametersDirty) {
  7227. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7228. this._isBlendFunctionParametersDirty = false;
  7229. }
  7230. // Alpha equation
  7231. if (this._isBlendEquationParametersDirty) {
  7232. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7233. this._isBlendEquationParametersDirty = false;
  7234. }
  7235. // Constants
  7236. if (this._isBlendConstantsDirty) {
  7237. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7238. this._isBlendConstantsDirty = false;
  7239. }
  7240. };
  7241. return _AlphaState;
  7242. }());
  7243. Internals._AlphaState = _AlphaState;
  7244. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7245. })(BABYLON || (BABYLON = {}));
  7246. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var Internals;
  7250. (function (Internals) {
  7251. var _DepthCullingState = /** @class */ (function () {
  7252. /**
  7253. * Initializes the state.
  7254. */
  7255. function _DepthCullingState() {
  7256. this._isDepthTestDirty = false;
  7257. this._isDepthMaskDirty = false;
  7258. this._isDepthFuncDirty = false;
  7259. this._isCullFaceDirty = false;
  7260. this._isCullDirty = false;
  7261. this._isZOffsetDirty = false;
  7262. this.reset();
  7263. }
  7264. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7265. get: function () {
  7266. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7267. },
  7268. enumerable: true,
  7269. configurable: true
  7270. });
  7271. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7272. get: function () {
  7273. return this._zOffset;
  7274. },
  7275. set: function (value) {
  7276. if (this._zOffset === value) {
  7277. return;
  7278. }
  7279. this._zOffset = value;
  7280. this._isZOffsetDirty = true;
  7281. },
  7282. enumerable: true,
  7283. configurable: true
  7284. });
  7285. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7286. get: function () {
  7287. return this._cullFace;
  7288. },
  7289. set: function (value) {
  7290. if (this._cullFace === value) {
  7291. return;
  7292. }
  7293. this._cullFace = value;
  7294. this._isCullFaceDirty = true;
  7295. },
  7296. enumerable: true,
  7297. configurable: true
  7298. });
  7299. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7300. get: function () {
  7301. return this._cull;
  7302. },
  7303. set: function (value) {
  7304. if (this._cull === value) {
  7305. return;
  7306. }
  7307. this._cull = value;
  7308. this._isCullDirty = true;
  7309. },
  7310. enumerable: true,
  7311. configurable: true
  7312. });
  7313. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7314. get: function () {
  7315. return this._depthFunc;
  7316. },
  7317. set: function (value) {
  7318. if (this._depthFunc === value) {
  7319. return;
  7320. }
  7321. this._depthFunc = value;
  7322. this._isDepthFuncDirty = true;
  7323. },
  7324. enumerable: true,
  7325. configurable: true
  7326. });
  7327. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7328. get: function () {
  7329. return this._depthMask;
  7330. },
  7331. set: function (value) {
  7332. if (this._depthMask === value) {
  7333. return;
  7334. }
  7335. this._depthMask = value;
  7336. this._isDepthMaskDirty = true;
  7337. },
  7338. enumerable: true,
  7339. configurable: true
  7340. });
  7341. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7342. get: function () {
  7343. return this._depthTest;
  7344. },
  7345. set: function (value) {
  7346. if (this._depthTest === value) {
  7347. return;
  7348. }
  7349. this._depthTest = value;
  7350. this._isDepthTestDirty = true;
  7351. },
  7352. enumerable: true,
  7353. configurable: true
  7354. });
  7355. _DepthCullingState.prototype.reset = function () {
  7356. this._depthMask = true;
  7357. this._depthTest = true;
  7358. this._depthFunc = null;
  7359. this._cullFace = null;
  7360. this._cull = null;
  7361. this._zOffset = 0;
  7362. this._isDepthTestDirty = true;
  7363. this._isDepthMaskDirty = true;
  7364. this._isDepthFuncDirty = false;
  7365. this._isCullFaceDirty = false;
  7366. this._isCullDirty = false;
  7367. this._isZOffsetDirty = false;
  7368. };
  7369. _DepthCullingState.prototype.apply = function (gl) {
  7370. if (!this.isDirty) {
  7371. return;
  7372. }
  7373. // Cull
  7374. if (this._isCullDirty) {
  7375. if (this.cull) {
  7376. gl.enable(gl.CULL_FACE);
  7377. }
  7378. else {
  7379. gl.disable(gl.CULL_FACE);
  7380. }
  7381. this._isCullDirty = false;
  7382. }
  7383. // Cull face
  7384. if (this._isCullFaceDirty) {
  7385. gl.cullFace(this.cullFace);
  7386. this._isCullFaceDirty = false;
  7387. }
  7388. // Depth mask
  7389. if (this._isDepthMaskDirty) {
  7390. gl.depthMask(this.depthMask);
  7391. this._isDepthMaskDirty = false;
  7392. }
  7393. // Depth test
  7394. if (this._isDepthTestDirty) {
  7395. if (this.depthTest) {
  7396. gl.enable(gl.DEPTH_TEST);
  7397. }
  7398. else {
  7399. gl.disable(gl.DEPTH_TEST);
  7400. }
  7401. this._isDepthTestDirty = false;
  7402. }
  7403. // Depth func
  7404. if (this._isDepthFuncDirty) {
  7405. gl.depthFunc(this.depthFunc);
  7406. this._isDepthFuncDirty = false;
  7407. }
  7408. // zOffset
  7409. if (this._isZOffsetDirty) {
  7410. if (this.zOffset) {
  7411. gl.enable(gl.POLYGON_OFFSET_FILL);
  7412. gl.polygonOffset(this.zOffset, 0);
  7413. }
  7414. else {
  7415. gl.disable(gl.POLYGON_OFFSET_FILL);
  7416. }
  7417. this._isZOffsetDirty = false;
  7418. }
  7419. };
  7420. return _DepthCullingState;
  7421. }());
  7422. Internals._DepthCullingState = _DepthCullingState;
  7423. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7424. })(BABYLON || (BABYLON = {}));
  7425. //# sourceMappingURL=babylon.depthCullingState.js.map
  7426. var BABYLON;
  7427. (function (BABYLON) {
  7428. var Internals;
  7429. (function (Internals) {
  7430. var _StencilState = /** @class */ (function () {
  7431. function _StencilState() {
  7432. this._isStencilTestDirty = false;
  7433. this._isStencilMaskDirty = false;
  7434. this._isStencilFuncDirty = false;
  7435. this._isStencilOpDirty = false;
  7436. this.reset();
  7437. }
  7438. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7439. get: function () {
  7440. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7441. },
  7442. enumerable: true,
  7443. configurable: true
  7444. });
  7445. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7446. get: function () {
  7447. return this._stencilFunc;
  7448. },
  7449. set: function (value) {
  7450. if (this._stencilFunc === value) {
  7451. return;
  7452. }
  7453. this._stencilFunc = value;
  7454. this._isStencilFuncDirty = true;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7460. get: function () {
  7461. return this._stencilFuncRef;
  7462. },
  7463. set: function (value) {
  7464. if (this._stencilFuncRef === value) {
  7465. return;
  7466. }
  7467. this._stencilFuncRef = value;
  7468. this._isStencilFuncDirty = true;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7474. get: function () {
  7475. return this._stencilFuncMask;
  7476. },
  7477. set: function (value) {
  7478. if (this._stencilFuncMask === value) {
  7479. return;
  7480. }
  7481. this._stencilFuncMask = value;
  7482. this._isStencilFuncDirty = true;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7488. get: function () {
  7489. return this._stencilOpStencilFail;
  7490. },
  7491. set: function (value) {
  7492. if (this._stencilOpStencilFail === value) {
  7493. return;
  7494. }
  7495. this._stencilOpStencilFail = value;
  7496. this._isStencilOpDirty = true;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7502. get: function () {
  7503. return this._stencilOpDepthFail;
  7504. },
  7505. set: function (value) {
  7506. if (this._stencilOpDepthFail === value) {
  7507. return;
  7508. }
  7509. this._stencilOpDepthFail = value;
  7510. this._isStencilOpDirty = true;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7516. get: function () {
  7517. return this._stencilOpStencilDepthPass;
  7518. },
  7519. set: function (value) {
  7520. if (this._stencilOpStencilDepthPass === value) {
  7521. return;
  7522. }
  7523. this._stencilOpStencilDepthPass = value;
  7524. this._isStencilOpDirty = true;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7530. get: function () {
  7531. return this._stencilMask;
  7532. },
  7533. set: function (value) {
  7534. if (this._stencilMask === value) {
  7535. return;
  7536. }
  7537. this._stencilMask = value;
  7538. this._isStencilMaskDirty = true;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7544. get: function () {
  7545. return this._stencilTest;
  7546. },
  7547. set: function (value) {
  7548. if (this._stencilTest === value) {
  7549. return;
  7550. }
  7551. this._stencilTest = value;
  7552. this._isStencilTestDirty = true;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. _StencilState.prototype.reset = function () {
  7558. this._stencilTest = false;
  7559. this._stencilMask = 0xFF;
  7560. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7561. this._stencilFuncRef = 1;
  7562. this._stencilFuncMask = 0xFF;
  7563. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7564. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7565. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7566. this._isStencilTestDirty = true;
  7567. this._isStencilMaskDirty = true;
  7568. this._isStencilFuncDirty = true;
  7569. this._isStencilOpDirty = true;
  7570. };
  7571. _StencilState.prototype.apply = function (gl) {
  7572. if (!this.isDirty) {
  7573. return;
  7574. }
  7575. // Stencil test
  7576. if (this._isStencilTestDirty) {
  7577. if (this.stencilTest) {
  7578. gl.enable(gl.STENCIL_TEST);
  7579. }
  7580. else {
  7581. gl.disable(gl.STENCIL_TEST);
  7582. }
  7583. this._isStencilTestDirty = false;
  7584. }
  7585. // Stencil mask
  7586. if (this._isStencilMaskDirty) {
  7587. gl.stencilMask(this.stencilMask);
  7588. this._isStencilMaskDirty = false;
  7589. }
  7590. // Stencil func
  7591. if (this._isStencilFuncDirty) {
  7592. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7593. this._isStencilFuncDirty = false;
  7594. }
  7595. // Stencil op
  7596. if (this._isStencilOpDirty) {
  7597. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7598. this._isStencilOpDirty = false;
  7599. }
  7600. };
  7601. return _StencilState;
  7602. }());
  7603. Internals._StencilState = _StencilState;
  7604. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7605. })(BABYLON || (BABYLON = {}));
  7606. //# sourceMappingURL=babylon.stencilState.js.map
  7607. var BABYLON;
  7608. (function (BABYLON) {
  7609. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7610. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7611. };
  7612. var compileRawShader = function (gl, source, type) {
  7613. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7614. gl.shaderSource(shader, source);
  7615. gl.compileShader(shader);
  7616. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7617. var log = gl.getShaderInfoLog(shader);
  7618. if (log) {
  7619. throw new Error(log);
  7620. }
  7621. }
  7622. if (!shader) {
  7623. throw new Error("Something went wrong while compile the shader.");
  7624. }
  7625. return shader;
  7626. };
  7627. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7628. var magFilter = gl.NEAREST;
  7629. var minFilter = gl.NEAREST;
  7630. switch (samplingMode) {
  7631. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7632. magFilter = gl.LINEAR;
  7633. if (generateMipMaps) {
  7634. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7635. }
  7636. else {
  7637. minFilter = gl.LINEAR;
  7638. }
  7639. break;
  7640. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7641. magFilter = gl.LINEAR;
  7642. if (generateMipMaps) {
  7643. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7644. }
  7645. else {
  7646. minFilter = gl.LINEAR;
  7647. }
  7648. break;
  7649. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7650. magFilter = gl.NEAREST;
  7651. if (generateMipMaps) {
  7652. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7653. }
  7654. else {
  7655. minFilter = gl.NEAREST;
  7656. }
  7657. break;
  7658. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7659. magFilter = gl.NEAREST;
  7660. if (generateMipMaps) {
  7661. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7662. }
  7663. else {
  7664. minFilter = gl.NEAREST;
  7665. }
  7666. break;
  7667. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7668. magFilter = gl.NEAREST;
  7669. if (generateMipMaps) {
  7670. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7671. }
  7672. else {
  7673. minFilter = gl.LINEAR;
  7674. }
  7675. break;
  7676. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7677. magFilter = gl.NEAREST;
  7678. if (generateMipMaps) {
  7679. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7680. }
  7681. else {
  7682. minFilter = gl.LINEAR;
  7683. }
  7684. break;
  7685. case BABYLON.Texture.NEAREST_LINEAR:
  7686. magFilter = gl.NEAREST;
  7687. minFilter = gl.LINEAR;
  7688. break;
  7689. case BABYLON.Texture.NEAREST_NEAREST:
  7690. magFilter = gl.NEAREST;
  7691. minFilter = gl.NEAREST;
  7692. break;
  7693. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7694. magFilter = gl.LINEAR;
  7695. if (generateMipMaps) {
  7696. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7697. }
  7698. else {
  7699. minFilter = gl.NEAREST;
  7700. }
  7701. break;
  7702. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7703. magFilter = gl.LINEAR;
  7704. if (generateMipMaps) {
  7705. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7706. }
  7707. else {
  7708. minFilter = gl.NEAREST;
  7709. }
  7710. break;
  7711. case BABYLON.Texture.LINEAR_LINEAR:
  7712. magFilter = gl.LINEAR;
  7713. minFilter = gl.LINEAR;
  7714. break;
  7715. case BABYLON.Texture.LINEAR_NEAREST:
  7716. magFilter = gl.LINEAR;
  7717. minFilter = gl.NEAREST;
  7718. break;
  7719. }
  7720. return {
  7721. min: minFilter,
  7722. mag: magFilter
  7723. };
  7724. };
  7725. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7726. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7727. var img;
  7728. var onload = function () {
  7729. loadedImages[index] = img;
  7730. loadedImages._internalCount++;
  7731. if (scene) {
  7732. scene._removePendingData(img);
  7733. }
  7734. if (loadedImages._internalCount === 6) {
  7735. onfinish(loadedImages);
  7736. }
  7737. };
  7738. var onerror = function (message, exception) {
  7739. if (scene) {
  7740. scene._removePendingData(img);
  7741. }
  7742. if (onErrorCallBack) {
  7743. onErrorCallBack(message, exception);
  7744. }
  7745. };
  7746. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7747. if (scene) {
  7748. scene._addPendingData(img);
  7749. }
  7750. };
  7751. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7752. if (onError === void 0) { onError = null; }
  7753. var loadedImages = [];
  7754. loadedImages._internalCount = 0;
  7755. for (var index = 0; index < 6; index++) {
  7756. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7757. }
  7758. };
  7759. var BufferPointer = /** @class */ (function () {
  7760. function BufferPointer() {
  7761. }
  7762. return BufferPointer;
  7763. }());
  7764. var InstancingAttributeInfo = /** @class */ (function () {
  7765. function InstancingAttributeInfo() {
  7766. }
  7767. return InstancingAttributeInfo;
  7768. }());
  7769. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7770. /**
  7771. * Define options used to create a render target texture
  7772. */
  7773. var RenderTargetCreationOptions = /** @class */ (function () {
  7774. function RenderTargetCreationOptions() {
  7775. }
  7776. return RenderTargetCreationOptions;
  7777. }());
  7778. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7779. /**
  7780. * Regroup several parameters relative to the browser in use
  7781. */
  7782. var EngineCapabilities = /** @class */ (function () {
  7783. function EngineCapabilities() {
  7784. }
  7785. return EngineCapabilities;
  7786. }());
  7787. BABYLON.EngineCapabilities = EngineCapabilities;
  7788. /**
  7789. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7790. */
  7791. var Engine = /** @class */ (function () {
  7792. /**
  7793. * @constructor
  7794. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7795. * @param {boolean} [antialias] - enable antialias
  7796. * @param options - further options to be sent to the getContext function
  7797. */
  7798. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7799. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7800. var _this = this;
  7801. // Public members
  7802. this.forcePOTTextures = false;
  7803. this.isFullscreen = false;
  7804. this.isPointerLock = false;
  7805. this.cullBackFaces = true;
  7806. this.renderEvenInBackground = true;
  7807. this.preventCacheWipeBetweenFrames = false;
  7808. // To enable/disable IDB support and avoid XHR on .manifest
  7809. this.enableOfflineSupport = false;
  7810. this.scenes = new Array();
  7811. this.postProcesses = new Array();
  7812. // Observables
  7813. /**
  7814. * Observable event triggered each time the rendering canvas is resized
  7815. */
  7816. this.onResizeObservable = new BABYLON.Observable();
  7817. /**
  7818. * Observable event triggered each time the canvas loses focus
  7819. */
  7820. this.onCanvasBlurObservable = new BABYLON.Observable();
  7821. /**
  7822. * Observable event triggered each time the canvas gains focus
  7823. */
  7824. this.onCanvasFocusObservable = new BABYLON.Observable();
  7825. /**
  7826. * Observable event triggered each time the canvas receives pointerout event
  7827. */
  7828. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7829. /**
  7830. * Observable event triggered before each texture is initialized
  7831. */
  7832. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7833. //WebVR
  7834. this._vrDisplay = undefined;
  7835. this._vrSupported = false;
  7836. this._vrExclusivePointerMode = false;
  7837. // Uniform buffers list
  7838. this.disableUniformBuffers = false;
  7839. this._uniformBuffers = new Array();
  7840. // Observables
  7841. /**
  7842. * Observable raised when the engine begins a new frame
  7843. */
  7844. this.onBeginFrameObservable = new BABYLON.Observable();
  7845. /**
  7846. * Observable raised when the engine ends the current frame
  7847. */
  7848. this.onEndFrameObservable = new BABYLON.Observable();
  7849. /**
  7850. * Observable raised when the engine is about to compile a shader
  7851. */
  7852. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7853. /**
  7854. * Observable raised when the engine has jsut compiled a shader
  7855. */
  7856. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7857. this._windowIsBackground = false;
  7858. this._webGLVersion = 1.0;
  7859. this._badOS = false;
  7860. this._badDesktopOS = false;
  7861. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7862. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7863. this.onVRRequestPresentStart = new BABYLON.Observable();
  7864. this._colorWrite = true;
  7865. this._drawCalls = new BABYLON.PerfCounter();
  7866. this._renderingQueueLaunched = false;
  7867. this._activeRenderLoops = new Array();
  7868. // Deterministic lockstepMaxSteps
  7869. this._deterministicLockstep = false;
  7870. this._lockstepMaxSteps = 4;
  7871. // Lost context
  7872. this.onContextLostObservable = new BABYLON.Observable();
  7873. this.onContextRestoredObservable = new BABYLON.Observable();
  7874. this._contextWasLost = false;
  7875. this._doNotHandleContextLost = false;
  7876. // FPS
  7877. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7878. this._fps = 60;
  7879. this._deltaTime = 0;
  7880. /**
  7881. * Turn this value on if you want to pause FPS computation when in background
  7882. */
  7883. this.disablePerformanceMonitorInBackground = false;
  7884. // States
  7885. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7886. this._stencilState = new BABYLON.Internals._StencilState();
  7887. this._alphaState = new BABYLON.Internals._AlphaState();
  7888. this._alphaMode = Engine.ALPHA_DISABLE;
  7889. // Cache
  7890. this._internalTexturesCache = new Array();
  7891. this._activeTexturesCache = {};
  7892. this._compiledEffects = {};
  7893. this._vertexAttribArraysEnabled = [];
  7894. this._uintIndicesCurrentlySet = false;
  7895. this._currentBoundBuffer = new Array();
  7896. this._currentBufferPointers = new Array();
  7897. this._currentInstanceLocations = new Array();
  7898. this._currentInstanceBuffers = new Array();
  7899. this._vaoRecordInProgress = false;
  7900. this._mustWipeVertexAttributes = false;
  7901. // Hardware supported Compressed Textures
  7902. this._texturesSupported = new Array();
  7903. this._onVRFullScreenTriggered = function () {
  7904. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7905. //get the old size before we change
  7906. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7907. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7908. //get the width and height, change the render size
  7909. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7910. _this.setHardwareScalingLevel(1);
  7911. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7912. }
  7913. else {
  7914. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7915. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7916. }
  7917. };
  7918. var canvas = null;
  7919. Engine.Instances.push(this);
  7920. if (!canvasOrContext) {
  7921. return;
  7922. }
  7923. options = options || {};
  7924. if (canvasOrContext.getContext) {
  7925. canvas = canvasOrContext;
  7926. this._renderingCanvas = canvas;
  7927. if (antialias != null) {
  7928. options.antialias = antialias;
  7929. }
  7930. if (options.deterministicLockstep === undefined) {
  7931. options.deterministicLockstep = false;
  7932. }
  7933. if (options.lockstepMaxSteps === undefined) {
  7934. options.lockstepMaxSteps = 4;
  7935. }
  7936. if (options.preserveDrawingBuffer === undefined) {
  7937. options.preserveDrawingBuffer = false;
  7938. }
  7939. if (options.audioEngine === undefined) {
  7940. options.audioEngine = true;
  7941. }
  7942. if (options.stencil === undefined) {
  7943. options.stencil = true;
  7944. }
  7945. this._deterministicLockstep = options.deterministicLockstep;
  7946. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7947. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7948. // GL
  7949. if (!options.disableWebGL2Support) {
  7950. try {
  7951. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7952. if (this._gl) {
  7953. this._webGLVersion = 2.0;
  7954. }
  7955. }
  7956. catch (e) {
  7957. // Do nothing
  7958. }
  7959. }
  7960. if (!this._gl) {
  7961. if (!canvas) {
  7962. throw new Error("The provided canvas is null or undefined.");
  7963. }
  7964. try {
  7965. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7966. }
  7967. catch (e) {
  7968. throw new Error("WebGL not supported");
  7969. }
  7970. }
  7971. if (!this._gl) {
  7972. throw new Error("WebGL not supported");
  7973. }
  7974. this._onCanvasFocus = function () {
  7975. _this.onCanvasFocusObservable.notifyObservers(_this);
  7976. };
  7977. this._onCanvasBlur = function () {
  7978. _this.onCanvasBlurObservable.notifyObservers(_this);
  7979. };
  7980. canvas.addEventListener("focus", this._onCanvasFocus);
  7981. canvas.addEventListener("blur", this._onCanvasBlur);
  7982. this._onBlur = function () {
  7983. if (_this.disablePerformanceMonitorInBackground) {
  7984. _this._performanceMonitor.disable();
  7985. }
  7986. _this._windowIsBackground = true;
  7987. };
  7988. this._onFocus = function () {
  7989. if (_this.disablePerformanceMonitorInBackground) {
  7990. _this._performanceMonitor.enable();
  7991. }
  7992. _this._windowIsBackground = false;
  7993. };
  7994. this._onCanvasPointerOut = function () {
  7995. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7996. };
  7997. window.addEventListener("blur", this._onBlur);
  7998. window.addEventListener("focus", this._onFocus);
  7999. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8000. // Context lost
  8001. if (!this._doNotHandleContextLost) {
  8002. this._onContextLost = function (evt) {
  8003. evt.preventDefault();
  8004. _this._contextWasLost = true;
  8005. BABYLON.Tools.Warn("WebGL context lost.");
  8006. _this.onContextLostObservable.notifyObservers(_this);
  8007. };
  8008. this._onContextRestored = function (evt) {
  8009. // Adding a timeout to avoid race condition at browser level
  8010. setTimeout(function () {
  8011. // Rebuild gl context
  8012. _this._initGLContext();
  8013. // Rebuild effects
  8014. _this._rebuildEffects();
  8015. // Rebuild textures
  8016. _this._rebuildInternalTextures();
  8017. // Rebuild buffers
  8018. _this._rebuildBuffers();
  8019. // Cache
  8020. _this.wipeCaches(true);
  8021. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8022. _this.onContextRestoredObservable.notifyObservers(_this);
  8023. _this._contextWasLost = false;
  8024. }, 0);
  8025. };
  8026. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8027. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8028. }
  8029. }
  8030. else {
  8031. this._gl = canvasOrContext;
  8032. this._renderingCanvas = this._gl.canvas;
  8033. if (this._gl.renderbufferStorageMultisample) {
  8034. this._webGLVersion = 2.0;
  8035. }
  8036. options.stencil = this._gl.getContextAttributes().stencil;
  8037. }
  8038. // Viewport
  8039. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8040. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8041. this.resize();
  8042. this._isStencilEnable = options.stencil ? true : false;
  8043. this._initGLContext();
  8044. if (canvas) {
  8045. // Fullscreen
  8046. this._onFullscreenChange = function () {
  8047. if (document.fullscreen !== undefined) {
  8048. _this.isFullscreen = document.fullscreen;
  8049. }
  8050. else if (document.mozFullScreen !== undefined) {
  8051. _this.isFullscreen = document.mozFullScreen;
  8052. }
  8053. else if (document.webkitIsFullScreen !== undefined) {
  8054. _this.isFullscreen = document.webkitIsFullScreen;
  8055. }
  8056. else if (document.msIsFullScreen !== undefined) {
  8057. _this.isFullscreen = document.msIsFullScreen;
  8058. }
  8059. // Pointer lock
  8060. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8061. canvas.requestPointerLock = canvas.requestPointerLock ||
  8062. canvas.msRequestPointerLock ||
  8063. canvas.mozRequestPointerLock ||
  8064. canvas.webkitRequestPointerLock;
  8065. if (canvas.requestPointerLock) {
  8066. canvas.requestPointerLock();
  8067. }
  8068. }
  8069. };
  8070. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8071. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8072. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8073. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8074. // Pointer lock
  8075. this._onPointerLockChange = function () {
  8076. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8077. document.webkitPointerLockElement === canvas ||
  8078. document.msPointerLockElement === canvas ||
  8079. document.pointerLockElement === canvas);
  8080. };
  8081. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8082. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8083. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8084. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8085. this._onVRDisplayPointerRestricted = function () {
  8086. if (canvas) {
  8087. canvas.requestPointerLock();
  8088. }
  8089. };
  8090. this._onVRDisplayPointerUnrestricted = function () {
  8091. document.exitPointerLock();
  8092. };
  8093. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8094. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8095. }
  8096. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8097. Engine.audioEngine = new BABYLON.AudioEngine();
  8098. }
  8099. // Prepare buffer pointers
  8100. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8101. this._currentBufferPointers[i] = new BufferPointer();
  8102. }
  8103. // Load WebVR Devices
  8104. if (options.autoEnableWebVR) {
  8105. this.initWebVR();
  8106. }
  8107. // Detect if we are running on a faulty buggy OS.
  8108. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8109. // Detect if we are running on a faulty buggy desktop OS.
  8110. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8111. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8112. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8113. }
  8114. Object.defineProperty(Engine, "LastCreatedEngine", {
  8115. get: function () {
  8116. if (Engine.Instances.length === 0) {
  8117. return null;
  8118. }
  8119. return Engine.Instances[Engine.Instances.length - 1];
  8120. },
  8121. enumerable: true,
  8122. configurable: true
  8123. });
  8124. Object.defineProperty(Engine, "LastCreatedScene", {
  8125. get: function () {
  8126. var lastCreatedEngine = Engine.LastCreatedEngine;
  8127. if (!lastCreatedEngine) {
  8128. return null;
  8129. }
  8130. if (lastCreatedEngine.scenes.length === 0) {
  8131. return null;
  8132. }
  8133. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. /**
  8139. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8140. */
  8141. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8142. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8143. var engine = Engine.Instances[engineIndex];
  8144. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8145. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8146. }
  8147. }
  8148. };
  8149. Object.defineProperty(Engine, "NEVER", {
  8150. get: function () {
  8151. return Engine._NEVER;
  8152. },
  8153. enumerable: true,
  8154. configurable: true
  8155. });
  8156. Object.defineProperty(Engine, "ALWAYS", {
  8157. get: function () {
  8158. return Engine._ALWAYS;
  8159. },
  8160. enumerable: true,
  8161. configurable: true
  8162. });
  8163. Object.defineProperty(Engine, "LESS", {
  8164. get: function () {
  8165. return Engine._LESS;
  8166. },
  8167. enumerable: true,
  8168. configurable: true
  8169. });
  8170. Object.defineProperty(Engine, "EQUAL", {
  8171. get: function () {
  8172. return Engine._EQUAL;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "LEQUAL", {
  8178. get: function () {
  8179. return Engine._LEQUAL;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "GREATER", {
  8185. get: function () {
  8186. return Engine._GREATER;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "GEQUAL", {
  8192. get: function () {
  8193. return Engine._GEQUAL;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "NOTEQUAL", {
  8199. get: function () {
  8200. return Engine._NOTEQUAL;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "KEEP", {
  8206. get: function () {
  8207. return Engine._KEEP;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "REPLACE", {
  8213. get: function () {
  8214. return Engine._REPLACE;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "INCR", {
  8220. get: function () {
  8221. return Engine._INCR;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "DECR", {
  8227. get: function () {
  8228. return Engine._DECR;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "INVERT", {
  8234. get: function () {
  8235. return Engine._INVERT;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "INCR_WRAP", {
  8241. get: function () {
  8242. return Engine._INCR_WRAP;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "DECR_WRAP", {
  8248. get: function () {
  8249. return Engine._DECR_WRAP;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8255. get: function () {
  8256. return Engine._ALPHA_DISABLE;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8262. get: function () {
  8263. return Engine._ALPHA_ONEONE;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "ALPHA_ADD", {
  8269. get: function () {
  8270. return Engine._ALPHA_ADD;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8276. get: function () {
  8277. return Engine._ALPHA_COMBINE;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8283. get: function () {
  8284. return Engine._ALPHA_SUBTRACT;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8290. get: function () {
  8291. return Engine._ALPHA_MULTIPLY;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8297. get: function () {
  8298. return Engine._ALPHA_MAXIMIZED;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8304. get: function () {
  8305. return Engine._ALPHA_PREMULTIPLIED;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8311. get: function () {
  8312. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8318. get: function () {
  8319. return Engine._ALPHA_INTERPOLATE;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8325. get: function () {
  8326. return Engine._ALPHA_SCREENMODE;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8332. get: function () {
  8333. return Engine._DELAYLOADSTATE_NONE;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8339. get: function () {
  8340. return Engine._DELAYLOADSTATE_LOADED;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8346. get: function () {
  8347. return Engine._DELAYLOADSTATE_LOADING;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NOTLOADED;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8360. get: function () {
  8361. return Engine._TEXTUREFORMAT_ALPHA;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8367. get: function () {
  8368. return Engine._TEXTUREFORMAT_LUMINANCE;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8374. get: function () {
  8375. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_RGB;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_RGBA;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8395. get: function () {
  8396. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8402. get: function () {
  8403. return Engine._TEXTURETYPE_FLOAT;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8409. get: function () {
  8410. return Engine._TEXTURETYPE_HALF_FLOAT;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8416. get: function () {
  8417. return Engine._SCALEMODE_FLOOR;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8423. get: function () {
  8424. return Engine._SCALEMODE_NEAREST;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8430. get: function () {
  8431. return Engine._SCALEMODE_CEILING;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "Version", {
  8437. get: function () {
  8438. return "3.1-alpha";
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8444. get: function () {
  8445. return this._vrExclusivePointerMode;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8451. get: function () {
  8452. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8458. get: function () {
  8459. return this._webGLVersion < 2 || this.forcePOTTextures;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "badOS", {
  8465. get: function () {
  8466. return this._badOS;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8472. get: function () {
  8473. return this._badDesktopOS;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8479. get: function () {
  8480. return this._performanceMonitor;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8486. get: function () {
  8487. return this._texturesSupported;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8493. get: function () {
  8494. return this._textureFormatInUse;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "currentViewport", {
  8500. get: function () {
  8501. return this._cachedViewport;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8507. // Empty texture
  8508. get: function () {
  8509. if (!this._emptyTexture) {
  8510. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8511. }
  8512. return this._emptyTexture;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8518. get: function () {
  8519. if (!this._emptyTexture3D) {
  8520. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8521. }
  8522. return this._emptyTexture3D;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8528. get: function () {
  8529. if (!this._emptyCubeTexture) {
  8530. var faceData = new Uint8Array(4);
  8531. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8532. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8533. }
  8534. return this._emptyCubeTexture;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Engine.prototype._rebuildInternalTextures = function () {
  8540. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8541. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8542. var internalTexture = currentState_1[_i];
  8543. internalTexture._rebuild();
  8544. }
  8545. };
  8546. Engine.prototype._rebuildEffects = function () {
  8547. for (var key in this._compiledEffects) {
  8548. var effect = this._compiledEffects[key];
  8549. effect._prepareEffect();
  8550. }
  8551. BABYLON.Effect.ResetCache();
  8552. };
  8553. Engine.prototype._rebuildBuffers = function () {
  8554. // Index / Vertex
  8555. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8556. var scene = _a[_i];
  8557. scene.resetCachedMaterial();
  8558. scene._rebuildGeometries();
  8559. scene._rebuildTextures();
  8560. }
  8561. // Uniforms
  8562. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8563. var uniformBuffer = _c[_b];
  8564. uniformBuffer._rebuild();
  8565. }
  8566. };
  8567. Engine.prototype._initGLContext = function () {
  8568. // Caps
  8569. this._caps = new EngineCapabilities();
  8570. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8571. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8572. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8573. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8574. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8575. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8576. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8577. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8578. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8579. // Infos
  8580. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8581. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8582. if (rendererInfo != null) {
  8583. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8584. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8585. }
  8586. if (!this._glVendor) {
  8587. this._glVendor = "Unknown vendor";
  8588. }
  8589. if (!this._glRenderer) {
  8590. this._glRenderer = "Unknown renderer";
  8591. }
  8592. // Constants
  8593. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8594. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8595. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8596. this._gl.DEPTH24_STENCIL8 = 35056;
  8597. // Extensions
  8598. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8599. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8600. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8601. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8602. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8603. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8604. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8605. 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');
  8606. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8607. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8608. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8609. this._caps.highPrecisionShaderSupported = true;
  8610. this._caps.timerQuery = this._gl.getExtension("EXT_disjoint_timer_query") || this._gl.getExtension('EXT_disjoint_timer_query_webgl2');
  8611. if (this._caps.timerQuery) {
  8612. if (this._webGLVersion === 1) {
  8613. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8614. }
  8615. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8616. }
  8617. // Checks if some of the format renders first to allow the use of webgl inspector.
  8618. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8619. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8620. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8621. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8622. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8623. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8624. if (this._webGLVersion > 1) {
  8625. this._gl.HALF_FLOAT_OES = 0x140B;
  8626. }
  8627. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8628. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8629. // Draw buffers
  8630. if (this._webGLVersion > 1) {
  8631. this._caps.drawBuffersExtension = true;
  8632. }
  8633. else {
  8634. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8635. if (drawBuffersExtension !== null) {
  8636. this._caps.drawBuffersExtension = true;
  8637. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8638. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8639. for (var i = 0; i < 16; i++) {
  8640. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8641. }
  8642. }
  8643. else {
  8644. this._caps.drawBuffersExtension = false;
  8645. }
  8646. }
  8647. // Depth Texture
  8648. if (this._webGLVersion > 1) {
  8649. this._caps.depthTextureExtension = true;
  8650. }
  8651. else {
  8652. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8653. if (depthTextureExtension != null) {
  8654. this._caps.depthTextureExtension = true;
  8655. }
  8656. }
  8657. // Vertex array object
  8658. if (this._webGLVersion > 1) {
  8659. this._caps.vertexArrayObject = true;
  8660. }
  8661. else {
  8662. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8663. if (vertexArrayObjectExtension != null) {
  8664. this._caps.vertexArrayObject = true;
  8665. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8666. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8667. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8668. }
  8669. else {
  8670. this._caps.vertexArrayObject = false;
  8671. }
  8672. }
  8673. // Instances count
  8674. if (this._webGLVersion > 1) {
  8675. this._caps.instancedArrays = true;
  8676. }
  8677. else {
  8678. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8679. if (instanceExtension != null) {
  8680. this._caps.instancedArrays = true;
  8681. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8682. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8683. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8684. }
  8685. else {
  8686. this._caps.instancedArrays = false;
  8687. }
  8688. }
  8689. // Intelligently add supported compressed formats in order to check for.
  8690. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8691. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8692. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8693. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8694. if (this._caps.astc)
  8695. this.texturesSupported.push('-astc.ktx');
  8696. if (this._caps.s3tc)
  8697. this.texturesSupported.push('-dxt.ktx');
  8698. if (this._caps.pvrtc)
  8699. this.texturesSupported.push('-pvrtc.ktx');
  8700. if (this._caps.etc2)
  8701. this.texturesSupported.push('-etc2.ktx');
  8702. if (this._caps.etc1)
  8703. this.texturesSupported.push('-etc1.ktx');
  8704. if (this._gl.getShaderPrecisionFormat) {
  8705. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8706. if (highp) {
  8707. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8708. }
  8709. }
  8710. // Depth buffer
  8711. this.setDepthBuffer(true);
  8712. this.setDepthFunctionToLessOrEqual();
  8713. this.setDepthWrite(true);
  8714. };
  8715. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8716. get: function () {
  8717. return this._webGLVersion;
  8718. },
  8719. enumerable: true,
  8720. configurable: true
  8721. });
  8722. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8723. /**
  8724. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8725. */
  8726. get: function () {
  8727. return this._isStencilEnable;
  8728. },
  8729. enumerable: true,
  8730. configurable: true
  8731. });
  8732. Engine.prototype._prepareWorkingCanvas = function () {
  8733. if (this._workingCanvas) {
  8734. return;
  8735. }
  8736. this._workingCanvas = document.createElement("canvas");
  8737. var context = this._workingCanvas.getContext("2d");
  8738. if (context) {
  8739. this._workingContext = context;
  8740. }
  8741. };
  8742. Engine.prototype.resetTextureCache = function () {
  8743. for (var key in this._activeTexturesCache) {
  8744. this._activeTexturesCache[key] = null;
  8745. }
  8746. };
  8747. Engine.prototype.isDeterministicLockStep = function () {
  8748. return this._deterministicLockstep;
  8749. };
  8750. Engine.prototype.getLockstepMaxSteps = function () {
  8751. return this._lockstepMaxSteps;
  8752. };
  8753. Engine.prototype.getGlInfo = function () {
  8754. return {
  8755. vendor: this._glVendor,
  8756. renderer: this._glRenderer,
  8757. version: this._glVersion
  8758. };
  8759. };
  8760. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8761. if (useScreen === void 0) { useScreen = false; }
  8762. var viewport = camera.viewport;
  8763. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8764. };
  8765. Engine.prototype.getRenderWidth = function (useScreen) {
  8766. if (useScreen === void 0) { useScreen = false; }
  8767. if (!useScreen && this._currentRenderTarget) {
  8768. return this._currentRenderTarget.width;
  8769. }
  8770. return this._gl.drawingBufferWidth;
  8771. };
  8772. Engine.prototype.getRenderHeight = function (useScreen) {
  8773. if (useScreen === void 0) { useScreen = false; }
  8774. if (!useScreen && this._currentRenderTarget) {
  8775. return this._currentRenderTarget.height;
  8776. }
  8777. return this._gl.drawingBufferHeight;
  8778. };
  8779. Engine.prototype.getRenderingCanvas = function () {
  8780. return this._renderingCanvas;
  8781. };
  8782. Engine.prototype.getRenderingCanvasClientRect = function () {
  8783. if (!this._renderingCanvas) {
  8784. return null;
  8785. }
  8786. return this._renderingCanvas.getBoundingClientRect();
  8787. };
  8788. Engine.prototype.setHardwareScalingLevel = function (level) {
  8789. this._hardwareScalingLevel = level;
  8790. this.resize();
  8791. };
  8792. Engine.prototype.getHardwareScalingLevel = function () {
  8793. return this._hardwareScalingLevel;
  8794. };
  8795. Engine.prototype.getLoadedTexturesCache = function () {
  8796. return this._internalTexturesCache;
  8797. };
  8798. Engine.prototype.getCaps = function () {
  8799. return this._caps;
  8800. };
  8801. Object.defineProperty(Engine.prototype, "drawCalls", {
  8802. /** The number of draw calls submitted last frame */
  8803. get: function () {
  8804. return this._drawCalls.current;
  8805. },
  8806. enumerable: true,
  8807. configurable: true
  8808. });
  8809. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8810. get: function () {
  8811. return this._drawCalls;
  8812. },
  8813. enumerable: true,
  8814. configurable: true
  8815. });
  8816. Engine.prototype.getDepthFunction = function () {
  8817. return this._depthCullingState.depthFunc;
  8818. };
  8819. Engine.prototype.setDepthFunction = function (depthFunc) {
  8820. this._depthCullingState.depthFunc = depthFunc;
  8821. };
  8822. Engine.prototype.setDepthFunctionToGreater = function () {
  8823. this._depthCullingState.depthFunc = this._gl.GREATER;
  8824. };
  8825. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8826. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8827. };
  8828. Engine.prototype.setDepthFunctionToLess = function () {
  8829. this._depthCullingState.depthFunc = this._gl.LESS;
  8830. };
  8831. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8832. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8833. };
  8834. Engine.prototype.getStencilBuffer = function () {
  8835. return this._stencilState.stencilTest;
  8836. };
  8837. Engine.prototype.setStencilBuffer = function (enable) {
  8838. this._stencilState.stencilTest = enable;
  8839. };
  8840. Engine.prototype.getStencilMask = function () {
  8841. return this._stencilState.stencilMask;
  8842. };
  8843. Engine.prototype.setStencilMask = function (mask) {
  8844. this._stencilState.stencilMask = mask;
  8845. };
  8846. Engine.prototype.getStencilFunction = function () {
  8847. return this._stencilState.stencilFunc;
  8848. };
  8849. Engine.prototype.getStencilFunctionReference = function () {
  8850. return this._stencilState.stencilFuncRef;
  8851. };
  8852. Engine.prototype.getStencilFunctionMask = function () {
  8853. return this._stencilState.stencilFuncMask;
  8854. };
  8855. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8856. this._stencilState.stencilFunc = stencilFunc;
  8857. };
  8858. Engine.prototype.setStencilFunctionReference = function (reference) {
  8859. this._stencilState.stencilFuncRef = reference;
  8860. };
  8861. Engine.prototype.setStencilFunctionMask = function (mask) {
  8862. this._stencilState.stencilFuncMask = mask;
  8863. };
  8864. Engine.prototype.getStencilOperationFail = function () {
  8865. return this._stencilState.stencilOpStencilFail;
  8866. };
  8867. Engine.prototype.getStencilOperationDepthFail = function () {
  8868. return this._stencilState.stencilOpDepthFail;
  8869. };
  8870. Engine.prototype.getStencilOperationPass = function () {
  8871. return this._stencilState.stencilOpStencilDepthPass;
  8872. };
  8873. Engine.prototype.setStencilOperationFail = function (operation) {
  8874. this._stencilState.stencilOpStencilFail = operation;
  8875. };
  8876. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8877. this._stencilState.stencilOpDepthFail = operation;
  8878. };
  8879. Engine.prototype.setStencilOperationPass = function (operation) {
  8880. this._stencilState.stencilOpStencilDepthPass = operation;
  8881. };
  8882. Engine.prototype.setDitheringState = function (value) {
  8883. if (value) {
  8884. this._gl.enable(this._gl.DITHER);
  8885. }
  8886. else {
  8887. this._gl.disable(this._gl.DITHER);
  8888. }
  8889. };
  8890. /**
  8891. * stop executing a render loop function and remove it from the execution array
  8892. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8893. */
  8894. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8895. if (!renderFunction) {
  8896. this._activeRenderLoops = [];
  8897. return;
  8898. }
  8899. var index = this._activeRenderLoops.indexOf(renderFunction);
  8900. if (index >= 0) {
  8901. this._activeRenderLoops.splice(index, 1);
  8902. }
  8903. };
  8904. Engine.prototype._renderLoop = function () {
  8905. if (!this._contextWasLost) {
  8906. var shouldRender = true;
  8907. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8908. shouldRender = false;
  8909. }
  8910. if (shouldRender) {
  8911. // Start new frame
  8912. this.beginFrame();
  8913. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8914. var renderFunction = this._activeRenderLoops[index];
  8915. renderFunction();
  8916. }
  8917. // Present
  8918. this.endFrame();
  8919. }
  8920. }
  8921. if (this._activeRenderLoops.length > 0) {
  8922. // Register new frame
  8923. var requester = null;
  8924. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8925. requester = this._vrDisplay;
  8926. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8927. }
  8928. else {
  8929. this._renderingQueueLaunched = false;
  8930. }
  8931. };
  8932. /**
  8933. * Register and execute a render loop. The engine can have more than one render function.
  8934. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8935. * @example
  8936. * engine.runRenderLoop(function () {
  8937. * scene.render()
  8938. * })
  8939. */
  8940. Engine.prototype.runRenderLoop = function (renderFunction) {
  8941. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8942. return;
  8943. }
  8944. this._activeRenderLoops.push(renderFunction);
  8945. if (!this._renderingQueueLaunched) {
  8946. this._renderingQueueLaunched = true;
  8947. this._bindedRenderFunction = this._renderLoop.bind(this);
  8948. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8949. }
  8950. };
  8951. /**
  8952. * Toggle full screen mode.
  8953. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8954. * @param {any} options - an options object to be sent to the requestFullscreen function
  8955. */
  8956. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8957. if (this.isFullscreen) {
  8958. BABYLON.Tools.ExitFullscreen();
  8959. }
  8960. else {
  8961. this._pointerLockRequested = requestPointerLock;
  8962. if (this._renderingCanvas) {
  8963. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8964. }
  8965. }
  8966. };
  8967. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8968. if (stencil === void 0) { stencil = false; }
  8969. this.applyStates();
  8970. var mode = 0;
  8971. if (backBuffer && color) {
  8972. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8973. mode |= this._gl.COLOR_BUFFER_BIT;
  8974. }
  8975. if (depth) {
  8976. this._gl.clearDepth(1.0);
  8977. mode |= this._gl.DEPTH_BUFFER_BIT;
  8978. }
  8979. if (stencil) {
  8980. this._gl.clearStencil(0);
  8981. mode |= this._gl.STENCIL_BUFFER_BIT;
  8982. }
  8983. this._gl.clear(mode);
  8984. };
  8985. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8986. var gl = this._gl;
  8987. // Save state
  8988. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8989. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8990. // Change state
  8991. gl.enable(gl.SCISSOR_TEST);
  8992. gl.scissor(x, y, width, height);
  8993. // Clear
  8994. this.clear(clearColor, true, true, true);
  8995. // Restore state
  8996. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8997. if (curScissor === true) {
  8998. gl.enable(gl.SCISSOR_TEST);
  8999. }
  9000. else {
  9001. gl.disable(gl.SCISSOR_TEST);
  9002. }
  9003. };
  9004. /**
  9005. * Set the WebGL's viewport
  9006. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9007. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9008. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9009. */
  9010. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9011. var width = requiredWidth || this.getRenderWidth();
  9012. var height = requiredHeight || this.getRenderHeight();
  9013. var x = viewport.x || 0;
  9014. var y = viewport.y || 0;
  9015. this._cachedViewport = viewport;
  9016. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9017. };
  9018. /**
  9019. * Directly set the WebGL Viewport
  9020. * The x, y, width & height are directly passed to the WebGL call
  9021. * @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.
  9022. */
  9023. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9024. var currentViewport = this._cachedViewport;
  9025. this._cachedViewport = null;
  9026. this._gl.viewport(x, y, width, height);
  9027. return currentViewport;
  9028. };
  9029. Engine.prototype.beginFrame = function () {
  9030. this.onBeginFrameObservable.notifyObservers(this);
  9031. this._measureFps();
  9032. };
  9033. Engine.prototype.endFrame = function () {
  9034. //force a flush in case we are using a bad OS.
  9035. if (this._badOS) {
  9036. this.flushFramebuffer();
  9037. }
  9038. //submit frame to the vr device, if enabled
  9039. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9040. // TODO: We should only submit the frame if we read frameData successfully.
  9041. this._vrDisplay.submitFrame();
  9042. }
  9043. this.onEndFrameObservable.notifyObservers(this);
  9044. };
  9045. /**
  9046. * resize the view according to the canvas' size.
  9047. * @example
  9048. * window.addEventListener("resize", function () {
  9049. * engine.resize();
  9050. * });
  9051. */
  9052. Engine.prototype.resize = function () {
  9053. // We're not resizing the size of the canvas while in VR mode & presenting
  9054. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9055. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9056. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9057. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9058. }
  9059. };
  9060. /**
  9061. * force a specific size of the canvas
  9062. * @param {number} width - the new canvas' width
  9063. * @param {number} height - the new canvas' height
  9064. */
  9065. Engine.prototype.setSize = function (width, height) {
  9066. if (!this._renderingCanvas) {
  9067. return;
  9068. }
  9069. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9070. return;
  9071. }
  9072. this._renderingCanvas.width = width;
  9073. this._renderingCanvas.height = height;
  9074. for (var index = 0; index < this.scenes.length; index++) {
  9075. var scene = this.scenes[index];
  9076. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9077. var cam = scene.cameras[camIndex];
  9078. cam._currentRenderId = 0;
  9079. }
  9080. }
  9081. if (this.onResizeObservable.hasObservers) {
  9082. this.onResizeObservable.notifyObservers(this);
  9083. }
  9084. };
  9085. // WebVR functions
  9086. Engine.prototype.isVRDevicePresent = function () {
  9087. return !!this._vrDisplay;
  9088. };
  9089. Engine.prototype.getVRDevice = function () {
  9090. return this._vrDisplay;
  9091. };
  9092. Engine.prototype.initWebVR = function () {
  9093. var _this = this;
  9094. var notifyObservers = function () {
  9095. var eventArgs = {
  9096. vrDisplay: _this._vrDisplay,
  9097. vrSupported: _this._vrSupported
  9098. };
  9099. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9100. };
  9101. if (!this._onVrDisplayConnect) {
  9102. this._onVrDisplayConnect = function (event) {
  9103. _this._vrDisplay = event.display;
  9104. notifyObservers();
  9105. };
  9106. this._onVrDisplayDisconnect = function () {
  9107. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9108. _this._vrDisplay = undefined;
  9109. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9110. notifyObservers();
  9111. };
  9112. this._onVrDisplayPresentChange = function () {
  9113. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9114. };
  9115. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9116. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9117. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9118. }
  9119. this._getVRDisplays(notifyObservers);
  9120. return this.onVRDisplayChangedObservable;
  9121. };
  9122. Engine.prototype.enableVR = function () {
  9123. var _this = this;
  9124. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9125. var onResolved = function () {
  9126. _this.onVRRequestPresentComplete.notifyObservers(true);
  9127. _this._onVRFullScreenTriggered();
  9128. };
  9129. var onRejected = function () {
  9130. _this.onVRRequestPresentComplete.notifyObservers(false);
  9131. };
  9132. this.onVRRequestPresentStart.notifyObservers(this);
  9133. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9134. }
  9135. };
  9136. Engine.prototype.disableVR = function () {
  9137. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9138. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9139. }
  9140. };
  9141. Engine.prototype._getVRDisplays = function (callback) {
  9142. var _this = this;
  9143. var getWebVRDevices = function (devices) {
  9144. _this._vrSupported = true;
  9145. // note that devices may actually be an empty array. This is fine;
  9146. // we expect this._vrDisplay to be undefined in this case.
  9147. return _this._vrDisplay = devices[0];
  9148. };
  9149. if (navigator.getVRDisplays) {
  9150. // TODO: Backwards compatible for 1.0?
  9151. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9152. // TODO: System CANNOT support WebVR, despite API presence.
  9153. _this._vrSupported = false;
  9154. callback();
  9155. });
  9156. }
  9157. else {
  9158. // TODO: Browser does not support WebVR
  9159. this._vrDisplay = undefined;
  9160. this._vrSupported = false;
  9161. callback();
  9162. }
  9163. };
  9164. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9165. if (this._currentRenderTarget) {
  9166. this.unBindFramebuffer(this._currentRenderTarget);
  9167. }
  9168. this._currentRenderTarget = texture;
  9169. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9170. var gl = this._gl;
  9171. if (texture.isCube) {
  9172. if (faceIndex === undefined) {
  9173. faceIndex = 0;
  9174. }
  9175. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9176. }
  9177. if (this._cachedViewport && !forceFullscreenViewport) {
  9178. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9179. }
  9180. else {
  9181. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9182. }
  9183. this.wipeCaches();
  9184. };
  9185. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9186. if (this._currentFramebuffer !== framebuffer) {
  9187. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9188. this._currentFramebuffer = framebuffer;
  9189. }
  9190. };
  9191. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9192. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9193. this._currentRenderTarget = null;
  9194. // If MSAA, we need to bitblt back to main texture
  9195. var gl = this._gl;
  9196. if (texture._MSAAFramebuffer) {
  9197. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9198. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9199. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9200. }
  9201. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9202. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9203. gl.generateMipmap(gl.TEXTURE_2D);
  9204. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9205. }
  9206. if (onBeforeUnbind) {
  9207. if (texture._MSAAFramebuffer) {
  9208. // Bind the correct framebuffer
  9209. this.bindUnboundFramebuffer(texture._framebuffer);
  9210. }
  9211. onBeforeUnbind();
  9212. }
  9213. this.bindUnboundFramebuffer(null);
  9214. };
  9215. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9216. if (texture.generateMipMaps) {
  9217. var gl = this._gl;
  9218. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9219. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9220. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9221. }
  9222. };
  9223. Engine.prototype.flushFramebuffer = function () {
  9224. this._gl.flush();
  9225. };
  9226. Engine.prototype.restoreDefaultFramebuffer = function () {
  9227. if (this._currentRenderTarget) {
  9228. this.unBindFramebuffer(this._currentRenderTarget);
  9229. }
  9230. else {
  9231. this.bindUnboundFramebuffer(null);
  9232. }
  9233. if (this._cachedViewport) {
  9234. this.setViewport(this._cachedViewport);
  9235. }
  9236. this.wipeCaches();
  9237. };
  9238. // UBOs
  9239. Engine.prototype.createUniformBuffer = function (elements) {
  9240. var ubo = this._gl.createBuffer();
  9241. if (!ubo) {
  9242. throw new Error("Unable to create uniform buffer");
  9243. }
  9244. this.bindUniformBuffer(ubo);
  9245. if (elements instanceof Float32Array) {
  9246. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9247. }
  9248. else {
  9249. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9250. }
  9251. this.bindUniformBuffer(null);
  9252. ubo.references = 1;
  9253. return ubo;
  9254. };
  9255. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9256. var ubo = this._gl.createBuffer();
  9257. if (!ubo) {
  9258. throw new Error("Unable to create dynamic uniform buffer");
  9259. }
  9260. this.bindUniformBuffer(ubo);
  9261. if (elements instanceof Float32Array) {
  9262. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9263. }
  9264. else {
  9265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9266. }
  9267. this.bindUniformBuffer(null);
  9268. ubo.references = 1;
  9269. return ubo;
  9270. };
  9271. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9272. this.bindUniformBuffer(uniformBuffer);
  9273. if (offset === undefined) {
  9274. offset = 0;
  9275. }
  9276. if (count === undefined) {
  9277. if (elements instanceof Float32Array) {
  9278. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9279. }
  9280. else {
  9281. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9282. }
  9283. }
  9284. else {
  9285. if (elements instanceof Float32Array) {
  9286. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9287. }
  9288. else {
  9289. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9290. }
  9291. }
  9292. this.bindUniformBuffer(null);
  9293. };
  9294. // VBOs
  9295. Engine.prototype._resetVertexBufferBinding = function () {
  9296. this.bindArrayBuffer(null);
  9297. this._cachedVertexBuffers = null;
  9298. };
  9299. Engine.prototype.createVertexBuffer = function (vertices) {
  9300. var vbo = this._gl.createBuffer();
  9301. if (!vbo) {
  9302. throw new Error("Unable to create vertex buffer");
  9303. }
  9304. this.bindArrayBuffer(vbo);
  9305. if (vertices instanceof Float32Array) {
  9306. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9307. }
  9308. else {
  9309. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9310. }
  9311. this._resetVertexBufferBinding();
  9312. vbo.references = 1;
  9313. return vbo;
  9314. };
  9315. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9316. var vbo = this._gl.createBuffer();
  9317. if (!vbo) {
  9318. throw new Error("Unable to create dynamic vertex buffer");
  9319. }
  9320. this.bindArrayBuffer(vbo);
  9321. if (vertices instanceof Float32Array) {
  9322. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9323. }
  9324. else {
  9325. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9326. }
  9327. this._resetVertexBufferBinding();
  9328. vbo.references = 1;
  9329. return vbo;
  9330. };
  9331. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9332. if (offset === void 0) { offset = 0; }
  9333. // Force cache update
  9334. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9335. this.bindIndexBuffer(indexBuffer);
  9336. var arrayBuffer;
  9337. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9338. arrayBuffer = indices;
  9339. }
  9340. else {
  9341. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9342. }
  9343. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9344. this._resetIndexBufferBinding();
  9345. };
  9346. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9347. this.bindArrayBuffer(vertexBuffer);
  9348. if (offset === undefined) {
  9349. offset = 0;
  9350. }
  9351. if (count === undefined) {
  9352. if (vertices instanceof Float32Array) {
  9353. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9354. }
  9355. else {
  9356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9357. }
  9358. }
  9359. else {
  9360. if (vertices instanceof Float32Array) {
  9361. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9362. }
  9363. else {
  9364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9365. }
  9366. }
  9367. this._resetVertexBufferBinding();
  9368. };
  9369. Engine.prototype._resetIndexBufferBinding = function () {
  9370. this.bindIndexBuffer(null);
  9371. this._cachedIndexBuffer = null;
  9372. };
  9373. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9374. var vbo = this._gl.createBuffer();
  9375. if (!vbo) {
  9376. throw new Error("Unable to create index buffer");
  9377. }
  9378. this.bindIndexBuffer(vbo);
  9379. // Check for 32 bits indices
  9380. var arrayBuffer;
  9381. var need32Bits = false;
  9382. if (indices instanceof Uint16Array) {
  9383. arrayBuffer = indices;
  9384. }
  9385. else {
  9386. //check 32 bit support
  9387. if (this._caps.uintIndices) {
  9388. if (indices instanceof Uint32Array) {
  9389. arrayBuffer = indices;
  9390. need32Bits = true;
  9391. }
  9392. else {
  9393. //number[] or Int32Array, check if 32 bit is necessary
  9394. for (var index = 0; index < indices.length; index++) {
  9395. if (indices[index] > 65535) {
  9396. need32Bits = true;
  9397. break;
  9398. }
  9399. }
  9400. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9401. }
  9402. }
  9403. else {
  9404. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9405. arrayBuffer = new Uint16Array(indices);
  9406. }
  9407. }
  9408. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9409. this._resetIndexBufferBinding();
  9410. vbo.references = 1;
  9411. vbo.is32Bits = need32Bits;
  9412. return vbo;
  9413. };
  9414. Engine.prototype.bindArrayBuffer = function (buffer) {
  9415. if (!this._vaoRecordInProgress) {
  9416. this._unbindVertexArrayObject();
  9417. }
  9418. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9419. };
  9420. Engine.prototype.bindUniformBuffer = function (buffer) {
  9421. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9422. };
  9423. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9424. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9425. };
  9426. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9427. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9428. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9429. };
  9430. ;
  9431. Engine.prototype.bindIndexBuffer = function (buffer) {
  9432. if (!this._vaoRecordInProgress) {
  9433. this._unbindVertexArrayObject();
  9434. }
  9435. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9436. };
  9437. Engine.prototype.bindBuffer = function (buffer, target) {
  9438. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9439. this._gl.bindBuffer(target, buffer);
  9440. this._currentBoundBuffer[target] = buffer;
  9441. }
  9442. };
  9443. Engine.prototype.updateArrayBuffer = function (data) {
  9444. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9445. };
  9446. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9447. var pointer = this._currentBufferPointers[indx];
  9448. var changed = false;
  9449. if (!pointer.active) {
  9450. changed = true;
  9451. pointer.active = true;
  9452. pointer.index = indx;
  9453. pointer.size = size;
  9454. pointer.type = type;
  9455. pointer.normalized = normalized;
  9456. pointer.stride = stride;
  9457. pointer.offset = offset;
  9458. pointer.buffer = buffer;
  9459. }
  9460. else {
  9461. if (pointer.buffer !== buffer) {
  9462. pointer.buffer = buffer;
  9463. changed = true;
  9464. }
  9465. if (pointer.size !== size) {
  9466. pointer.size = size;
  9467. changed = true;
  9468. }
  9469. if (pointer.type !== type) {
  9470. pointer.type = type;
  9471. changed = true;
  9472. }
  9473. if (pointer.normalized !== normalized) {
  9474. pointer.normalized = normalized;
  9475. changed = true;
  9476. }
  9477. if (pointer.stride !== stride) {
  9478. pointer.stride = stride;
  9479. changed = true;
  9480. }
  9481. if (pointer.offset !== offset) {
  9482. pointer.offset = offset;
  9483. changed = true;
  9484. }
  9485. }
  9486. if (changed || this._vaoRecordInProgress) {
  9487. this.bindArrayBuffer(buffer);
  9488. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9489. }
  9490. };
  9491. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9492. if (indexBuffer == null) {
  9493. return;
  9494. }
  9495. if (this._cachedIndexBuffer !== indexBuffer) {
  9496. this._cachedIndexBuffer = indexBuffer;
  9497. this.bindIndexBuffer(indexBuffer);
  9498. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9499. }
  9500. };
  9501. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9502. var attributes = effect.getAttributesNames();
  9503. if (!this._vaoRecordInProgress) {
  9504. this._unbindVertexArrayObject();
  9505. }
  9506. this.unbindAllAttributes();
  9507. for (var index = 0; index < attributes.length; index++) {
  9508. var order = effect.getAttributeLocation(index);
  9509. if (order >= 0) {
  9510. var vertexBuffer = vertexBuffers[attributes[index]];
  9511. if (!vertexBuffer) {
  9512. continue;
  9513. }
  9514. this._gl.enableVertexAttribArray(order);
  9515. if (!this._vaoRecordInProgress) {
  9516. this._vertexAttribArraysEnabled[order] = true;
  9517. }
  9518. var buffer = vertexBuffer.getBuffer();
  9519. if (buffer) {
  9520. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9521. if (vertexBuffer.getIsInstanced()) {
  9522. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9523. if (!this._vaoRecordInProgress) {
  9524. this._currentInstanceLocations.push(order);
  9525. this._currentInstanceBuffers.push(buffer);
  9526. }
  9527. }
  9528. }
  9529. }
  9530. }
  9531. };
  9532. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9533. var vao = this._gl.createVertexArray();
  9534. this._vaoRecordInProgress = true;
  9535. this._gl.bindVertexArray(vao);
  9536. this._mustWipeVertexAttributes = true;
  9537. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9538. this.bindIndexBuffer(indexBuffer);
  9539. this._vaoRecordInProgress = false;
  9540. this._gl.bindVertexArray(null);
  9541. return vao;
  9542. };
  9543. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9544. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9545. this._cachedVertexArrayObject = vertexArrayObject;
  9546. this._gl.bindVertexArray(vertexArrayObject);
  9547. this._cachedVertexBuffers = null;
  9548. this._cachedIndexBuffer = null;
  9549. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9550. this._mustWipeVertexAttributes = true;
  9551. }
  9552. };
  9553. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9554. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9555. this._cachedVertexBuffers = vertexBuffer;
  9556. this._cachedEffectForVertexBuffers = effect;
  9557. var attributesCount = effect.getAttributesCount();
  9558. this._unbindVertexArrayObject();
  9559. this.unbindAllAttributes();
  9560. var offset = 0;
  9561. for (var index = 0; index < attributesCount; index++) {
  9562. if (index < vertexDeclaration.length) {
  9563. var order = effect.getAttributeLocation(index);
  9564. if (order >= 0) {
  9565. this._gl.enableVertexAttribArray(order);
  9566. this._vertexAttribArraysEnabled[order] = true;
  9567. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9568. }
  9569. offset += vertexDeclaration[index] * 4;
  9570. }
  9571. }
  9572. }
  9573. this._bindIndexBufferWithCache(indexBuffer);
  9574. };
  9575. Engine.prototype._unbindVertexArrayObject = function () {
  9576. if (!this._cachedVertexArrayObject) {
  9577. return;
  9578. }
  9579. this._cachedVertexArrayObject = null;
  9580. this._gl.bindVertexArray(null);
  9581. };
  9582. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9583. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9584. this._cachedVertexBuffers = vertexBuffers;
  9585. this._cachedEffectForVertexBuffers = effect;
  9586. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9587. }
  9588. this._bindIndexBufferWithCache(indexBuffer);
  9589. };
  9590. Engine.prototype.unbindInstanceAttributes = function () {
  9591. var boundBuffer;
  9592. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9593. var instancesBuffer = this._currentInstanceBuffers[i];
  9594. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9595. boundBuffer = instancesBuffer;
  9596. this.bindArrayBuffer(instancesBuffer);
  9597. }
  9598. var offsetLocation = this._currentInstanceLocations[i];
  9599. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9600. }
  9601. this._currentInstanceBuffers.length = 0;
  9602. this._currentInstanceLocations.length = 0;
  9603. };
  9604. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9605. this._gl.deleteVertexArray(vao);
  9606. };
  9607. Engine.prototype._releaseBuffer = function (buffer) {
  9608. buffer.references--;
  9609. if (buffer.references === 0) {
  9610. this._gl.deleteBuffer(buffer);
  9611. return true;
  9612. }
  9613. return false;
  9614. };
  9615. Engine.prototype.createInstancesBuffer = function (capacity) {
  9616. var buffer = this._gl.createBuffer();
  9617. if (!buffer) {
  9618. throw new Error("Unable to create instance buffer");
  9619. }
  9620. buffer.capacity = capacity;
  9621. this.bindArrayBuffer(buffer);
  9622. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9623. return buffer;
  9624. };
  9625. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9626. this._gl.deleteBuffer(buffer);
  9627. };
  9628. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9629. this.bindArrayBuffer(instancesBuffer);
  9630. if (data) {
  9631. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9632. }
  9633. if (offsetLocations[0].index !== undefined) {
  9634. var stride = 0;
  9635. for (var i = 0; i < offsetLocations.length; i++) {
  9636. var ai = offsetLocations[i];
  9637. stride += ai.attributeSize * 4;
  9638. }
  9639. for (var i = 0; i < offsetLocations.length; i++) {
  9640. var ai = offsetLocations[i];
  9641. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9642. this._gl.enableVertexAttribArray(ai.index);
  9643. this._vertexAttribArraysEnabled[ai.index] = true;
  9644. }
  9645. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9646. this._gl.vertexAttribDivisor(ai.index, 1);
  9647. this._currentInstanceLocations.push(ai.index);
  9648. this._currentInstanceBuffers.push(instancesBuffer);
  9649. }
  9650. }
  9651. else {
  9652. for (var index = 0; index < 4; index++) {
  9653. var offsetLocation = offsetLocations[index];
  9654. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9655. this._gl.enableVertexAttribArray(offsetLocation);
  9656. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9657. }
  9658. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9659. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9660. this._currentInstanceLocations.push(offsetLocation);
  9661. this._currentInstanceBuffers.push(instancesBuffer);
  9662. }
  9663. }
  9664. };
  9665. Engine.prototype.applyStates = function () {
  9666. this._depthCullingState.apply(this._gl);
  9667. this._stencilState.apply(this._gl);
  9668. this._alphaState.apply(this._gl);
  9669. };
  9670. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9671. // Apply states
  9672. this.applyStates();
  9673. this._drawCalls.addCount(1, false);
  9674. // Render
  9675. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9676. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9677. if (instancesCount) {
  9678. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9679. return;
  9680. }
  9681. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9682. };
  9683. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9684. // Apply states
  9685. this.applyStates();
  9686. this._drawCalls.addCount(1, false);
  9687. if (instancesCount) {
  9688. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9689. return;
  9690. }
  9691. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9692. };
  9693. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9694. // Apply states
  9695. this.applyStates();
  9696. this._drawCalls.addCount(1, false);
  9697. if (instancesCount) {
  9698. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9699. return;
  9700. }
  9701. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9702. };
  9703. // Shaders
  9704. Engine.prototype._releaseEffect = function (effect) {
  9705. if (this._compiledEffects[effect._key]) {
  9706. delete this._compiledEffects[effect._key];
  9707. this._deleteProgram(effect.getProgram());
  9708. }
  9709. };
  9710. Engine.prototype._deleteProgram = function (program) {
  9711. if (program) {
  9712. program.__SPECTOR_rebuildProgram = null;
  9713. this._gl.deleteProgram(program);
  9714. }
  9715. };
  9716. /**
  9717. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9718. * @param samplers An array of string used to represent textures
  9719. */
  9720. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9721. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9722. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9723. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9724. if (this._compiledEffects[name]) {
  9725. var compiledEffect = this._compiledEffects[name];
  9726. if (onCompiled && compiledEffect.isReady()) {
  9727. onCompiled(compiledEffect);
  9728. }
  9729. return compiledEffect;
  9730. }
  9731. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9732. effect._key = name;
  9733. this._compiledEffects[name] = effect;
  9734. return effect;
  9735. };
  9736. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9737. if (uniformsNames === void 0) { uniformsNames = []; }
  9738. if (samplers === void 0) { samplers = []; }
  9739. if (defines === void 0) { defines = ""; }
  9740. return this.createEffect({
  9741. vertex: "particles",
  9742. fragmentElement: fragmentName
  9743. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9744. };
  9745. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context) {
  9746. context = context || this._gl;
  9747. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9748. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9749. return this._createShaderProgram(vertexShader, fragmentShader, context);
  9750. };
  9751. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9752. context = context || this._gl;
  9753. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9754. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9755. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9756. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9757. var program = this._createShaderProgram(vertexShader, fragmentShader, context);
  9758. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9759. return program;
  9760. };
  9761. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context) {
  9762. var shaderProgram = context.createProgram();
  9763. if (!shaderProgram) {
  9764. throw new Error("Unable to create program");
  9765. }
  9766. context.attachShader(shaderProgram, vertexShader);
  9767. context.attachShader(shaderProgram, fragmentShader);
  9768. context.linkProgram(shaderProgram);
  9769. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9770. if (!linked) {
  9771. context.validateProgram(shaderProgram);
  9772. var error = context.getProgramInfoLog(shaderProgram);
  9773. if (error) {
  9774. throw new Error(error);
  9775. }
  9776. }
  9777. context.deleteShader(vertexShader);
  9778. context.deleteShader(fragmentShader);
  9779. return shaderProgram;
  9780. };
  9781. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9782. var results = new Array();
  9783. for (var index = 0; index < uniformsNames.length; index++) {
  9784. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9785. }
  9786. return results;
  9787. };
  9788. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9789. var results = [];
  9790. for (var index = 0; index < attributesNames.length; index++) {
  9791. try {
  9792. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9793. }
  9794. catch (e) {
  9795. results.push(-1);
  9796. }
  9797. }
  9798. return results;
  9799. };
  9800. Engine.prototype.enableEffect = function (effect) {
  9801. if (!effect) {
  9802. return;
  9803. }
  9804. // Use program
  9805. this.setProgram(effect.getProgram());
  9806. this._currentEffect = effect;
  9807. if (effect.onBind) {
  9808. effect.onBind(effect);
  9809. }
  9810. effect.onBindObservable.notifyObservers(effect);
  9811. };
  9812. Engine.prototype.setIntArray = function (uniform, array) {
  9813. if (!uniform)
  9814. return;
  9815. this._gl.uniform1iv(uniform, array);
  9816. };
  9817. Engine.prototype.setIntArray2 = function (uniform, array) {
  9818. if (!uniform || array.length % 2 !== 0)
  9819. return;
  9820. this._gl.uniform2iv(uniform, array);
  9821. };
  9822. Engine.prototype.setIntArray3 = function (uniform, array) {
  9823. if (!uniform || array.length % 3 !== 0)
  9824. return;
  9825. this._gl.uniform3iv(uniform, array);
  9826. };
  9827. Engine.prototype.setIntArray4 = function (uniform, array) {
  9828. if (!uniform || array.length % 4 !== 0)
  9829. return;
  9830. this._gl.uniform4iv(uniform, array);
  9831. };
  9832. Engine.prototype.setFloatArray = function (uniform, array) {
  9833. if (!uniform)
  9834. return;
  9835. this._gl.uniform1fv(uniform, array);
  9836. };
  9837. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9838. if (!uniform || array.length % 2 !== 0)
  9839. return;
  9840. this._gl.uniform2fv(uniform, array);
  9841. };
  9842. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9843. if (!uniform || array.length % 3 !== 0)
  9844. return;
  9845. this._gl.uniform3fv(uniform, array);
  9846. };
  9847. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9848. if (!uniform || array.length % 4 !== 0)
  9849. return;
  9850. this._gl.uniform4fv(uniform, array);
  9851. };
  9852. Engine.prototype.setArray = function (uniform, array) {
  9853. if (!uniform)
  9854. return;
  9855. this._gl.uniform1fv(uniform, array);
  9856. };
  9857. Engine.prototype.setArray2 = function (uniform, array) {
  9858. if (!uniform || array.length % 2 !== 0)
  9859. return;
  9860. this._gl.uniform2fv(uniform, array);
  9861. };
  9862. Engine.prototype.setArray3 = function (uniform, array) {
  9863. if (!uniform || array.length % 3 !== 0)
  9864. return;
  9865. this._gl.uniform3fv(uniform, array);
  9866. };
  9867. Engine.prototype.setArray4 = function (uniform, array) {
  9868. if (!uniform || array.length % 4 !== 0)
  9869. return;
  9870. this._gl.uniform4fv(uniform, array);
  9871. };
  9872. Engine.prototype.setMatrices = function (uniform, matrices) {
  9873. if (!uniform)
  9874. return;
  9875. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9876. };
  9877. Engine.prototype.setMatrix = function (uniform, matrix) {
  9878. if (!uniform)
  9879. return;
  9880. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9881. };
  9882. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9883. if (!uniform)
  9884. return;
  9885. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9886. };
  9887. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9888. if (!uniform)
  9889. return;
  9890. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9891. };
  9892. Engine.prototype.setFloat = function (uniform, value) {
  9893. if (!uniform)
  9894. return;
  9895. this._gl.uniform1f(uniform, value);
  9896. };
  9897. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9898. if (!uniform)
  9899. return;
  9900. this._gl.uniform2f(uniform, x, y);
  9901. };
  9902. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9903. if (!uniform)
  9904. return;
  9905. this._gl.uniform3f(uniform, x, y, z);
  9906. };
  9907. Engine.prototype.setBool = function (uniform, bool) {
  9908. if (!uniform)
  9909. return;
  9910. this._gl.uniform1i(uniform, bool);
  9911. };
  9912. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9913. if (!uniform)
  9914. return;
  9915. this._gl.uniform4f(uniform, x, y, z, w);
  9916. };
  9917. Engine.prototype.setColor3 = function (uniform, color3) {
  9918. if (!uniform)
  9919. return;
  9920. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9921. };
  9922. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9923. if (!uniform)
  9924. return;
  9925. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9926. };
  9927. // States
  9928. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9929. if (zOffset === void 0) { zOffset = 0; }
  9930. if (reverseSide === void 0) { reverseSide = false; }
  9931. // Culling
  9932. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9933. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9934. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9935. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9936. if (culling) {
  9937. this._depthCullingState.cullFace = cullFace;
  9938. this._depthCullingState.cull = true;
  9939. }
  9940. else {
  9941. this._depthCullingState.cull = false;
  9942. }
  9943. }
  9944. // Z offset
  9945. this.setZOffset(zOffset);
  9946. };
  9947. Engine.prototype.setZOffset = function (value) {
  9948. this._depthCullingState.zOffset = value;
  9949. };
  9950. Engine.prototype.getZOffset = function () {
  9951. return this._depthCullingState.zOffset;
  9952. };
  9953. Engine.prototype.setDepthBuffer = function (enable) {
  9954. this._depthCullingState.depthTest = enable;
  9955. };
  9956. Engine.prototype.getDepthWrite = function () {
  9957. return this._depthCullingState.depthMask;
  9958. };
  9959. Engine.prototype.setDepthWrite = function (enable) {
  9960. this._depthCullingState.depthMask = enable;
  9961. };
  9962. Engine.prototype.setColorWrite = function (enable) {
  9963. this._gl.colorMask(enable, enable, enable, enable);
  9964. this._colorWrite = enable;
  9965. };
  9966. Engine.prototype.getColorWrite = function () {
  9967. return this._colorWrite;
  9968. };
  9969. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9970. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9971. };
  9972. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9973. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9974. if (this._alphaMode === mode) {
  9975. return;
  9976. }
  9977. switch (mode) {
  9978. case Engine.ALPHA_DISABLE:
  9979. this._alphaState.alphaBlend = false;
  9980. break;
  9981. case Engine.ALPHA_PREMULTIPLIED:
  9982. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9983. this._alphaState.alphaBlend = true;
  9984. break;
  9985. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9987. this._alphaState.alphaBlend = true;
  9988. break;
  9989. case Engine.ALPHA_COMBINE:
  9990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9991. this._alphaState.alphaBlend = true;
  9992. break;
  9993. case Engine.ALPHA_ONEONE:
  9994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9995. this._alphaState.alphaBlend = true;
  9996. break;
  9997. case Engine.ALPHA_ADD:
  9998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9999. this._alphaState.alphaBlend = true;
  10000. break;
  10001. case Engine.ALPHA_SUBTRACT:
  10002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10003. this._alphaState.alphaBlend = true;
  10004. break;
  10005. case Engine.ALPHA_MULTIPLY:
  10006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10007. this._alphaState.alphaBlend = true;
  10008. break;
  10009. case Engine.ALPHA_MAXIMIZED:
  10010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10011. this._alphaState.alphaBlend = true;
  10012. break;
  10013. case Engine.ALPHA_INTERPOLATE:
  10014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10015. this._alphaState.alphaBlend = true;
  10016. break;
  10017. case Engine.ALPHA_SCREENMODE:
  10018. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10019. this._alphaState.alphaBlend = true;
  10020. break;
  10021. }
  10022. if (!noDepthWriteChange) {
  10023. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10024. }
  10025. this._alphaMode = mode;
  10026. };
  10027. Engine.prototype.getAlphaMode = function () {
  10028. return this._alphaMode;
  10029. };
  10030. Engine.prototype.setAlphaTesting = function (enable) {
  10031. this._alphaTest = enable;
  10032. };
  10033. Engine.prototype.getAlphaTesting = function () {
  10034. return !!this._alphaTest;
  10035. };
  10036. // Textures
  10037. Engine.prototype.wipeCaches = function (bruteForce) {
  10038. if (this.preventCacheWipeBetweenFrames) {
  10039. return;
  10040. }
  10041. this.resetTextureCache();
  10042. this._currentEffect = null;
  10043. // 6/8/2017: deltakosh: Should not be required anymore.
  10044. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10045. if (bruteForce) {
  10046. this._currentProgram = null;
  10047. this._stencilState.reset();
  10048. this._depthCullingState.reset();
  10049. this.setDepthFunctionToLessOrEqual();
  10050. this._alphaState.reset();
  10051. }
  10052. this._cachedVertexBuffers = null;
  10053. this._cachedIndexBuffer = null;
  10054. this._cachedEffectForVertexBuffers = null;
  10055. this._unbindVertexArrayObject();
  10056. this.bindIndexBuffer(null);
  10057. this.bindArrayBuffer(null);
  10058. };
  10059. /**
  10060. * Set the compressed texture format to use, based on the formats you have, and the formats
  10061. * supported by the hardware / browser.
  10062. *
  10063. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10064. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10065. * to API arguments needed to compressed textures. This puts the burden on the container
  10066. * generator to house the arcane code for determining these for current & future formats.
  10067. *
  10068. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10069. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10070. *
  10071. * Note: The result of this call is not taken into account when a texture is base64.
  10072. *
  10073. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10074. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10075. *
  10076. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10077. * @returns The extension selected.
  10078. */
  10079. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10080. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10081. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10082. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10083. return this._textureFormatInUse = this._texturesSupported[i];
  10084. }
  10085. }
  10086. }
  10087. // actively set format to nothing, to allow this to be called more than once
  10088. // and possibly fail the 2nd time
  10089. this._textureFormatInUse = null;
  10090. return null;
  10091. };
  10092. Engine.prototype._createTexture = function () {
  10093. var texture = this._gl.createTexture();
  10094. if (!texture) {
  10095. throw new Error("Unable to create texture");
  10096. }
  10097. return texture;
  10098. };
  10099. /**
  10100. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10101. * @param {string} urlArg- This contains one of the following:
  10102. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10103. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10104. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10105. *
  10106. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10107. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10108. * @param {Scene} scene- Needed for loading to the correct scene.
  10109. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10110. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10111. * @param {callback} onError- Optional callback to be called upon failure.
  10112. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10113. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10114. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10115. *
  10116. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10117. */
  10118. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10119. var _this = this;
  10120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10121. if (onLoad === void 0) { onLoad = null; }
  10122. if (onError === void 0) { onError = null; }
  10123. if (buffer === void 0) { buffer = null; }
  10124. if (fallBack === void 0) { fallBack = null; }
  10125. if (format === void 0) { format = null; }
  10126. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10127. var fromData = url.substr(0, 5) === "data:";
  10128. var fromBlob = url.substr(0, 5) === "blob:";
  10129. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10130. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10131. // establish the file extension, if possible
  10132. var lastDot = url.lastIndexOf('.');
  10133. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10134. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10135. var isTGA = (extension === ".tga");
  10136. // determine if a ktx file should be substituted
  10137. var isKTX = false;
  10138. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10139. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10140. isKTX = true;
  10141. }
  10142. if (scene) {
  10143. scene._addPendingData(texture);
  10144. }
  10145. texture.url = url;
  10146. texture.generateMipMaps = !noMipmap;
  10147. texture.samplingMode = samplingMode;
  10148. texture.invertY = invertY;
  10149. if (!this._doNotHandleContextLost) {
  10150. // Keep a link to the buffer only if we plan to handle context lost
  10151. texture._buffer = buffer;
  10152. }
  10153. if (onLoad) {
  10154. texture.onLoadedObservable.add(onLoad);
  10155. }
  10156. if (!fallBack)
  10157. this._internalTexturesCache.push(texture);
  10158. var onerror = function () {
  10159. if (scene) {
  10160. scene._removePendingData(texture);
  10161. }
  10162. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10163. if (isKTX) {
  10164. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10165. }
  10166. else if (onError) {
  10167. onError();
  10168. }
  10169. };
  10170. var callback = null;
  10171. // processing for non-image formats
  10172. if (isKTX || isTGA || isDDS) {
  10173. if (isKTX) {
  10174. callback = function (data) {
  10175. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10176. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10177. ktx.uploadLevels(_this._gl, !noMipmap);
  10178. return false;
  10179. }, samplingMode);
  10180. };
  10181. }
  10182. else if (isTGA) {
  10183. callback = function (arrayBuffer) {
  10184. var data = new Uint8Array(arrayBuffer);
  10185. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10186. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10187. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10188. return false;
  10189. }, samplingMode);
  10190. };
  10191. }
  10192. else if (isDDS) {
  10193. callback = function (data) {
  10194. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10195. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10196. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10197. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10198. return false;
  10199. }, samplingMode);
  10200. };
  10201. }
  10202. if (!buffer) {
  10203. BABYLON.Tools.LoadFile(url, function (data) {
  10204. if (callback) {
  10205. callback(data);
  10206. }
  10207. }, undefined, scene ? scene.database : undefined, true, onerror);
  10208. }
  10209. else {
  10210. if (callback) {
  10211. callback(buffer);
  10212. }
  10213. }
  10214. // image format processing
  10215. }
  10216. else {
  10217. var onload = function (img) {
  10218. if (fromBlob && !_this._doNotHandleContextLost) {
  10219. // We need to store the image if we need to rebuild the texture
  10220. // in case of a webgl context lost
  10221. texture._buffer = img;
  10222. }
  10223. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10224. var gl = _this._gl;
  10225. var isPot = (img.width === potWidth && img.height === potHeight);
  10226. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10227. if (isPot) {
  10228. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10229. return false;
  10230. }
  10231. // Using shaders to rescale because canvas.drawImage is lossy
  10232. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10233. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10234. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10239. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10240. _this._releaseTexture(source);
  10241. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10242. continuationCallback();
  10243. });
  10244. return true;
  10245. }, samplingMode);
  10246. };
  10247. if (!fromData || isBase64)
  10248. if (buffer instanceof HTMLImageElement) {
  10249. onload(buffer);
  10250. }
  10251. else {
  10252. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10253. }
  10254. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10255. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10256. else
  10257. onload(buffer);
  10258. }
  10259. return texture;
  10260. };
  10261. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10262. var _this = this;
  10263. var rtt = this.createRenderTargetTexture({
  10264. width: destination.width,
  10265. height: destination.height,
  10266. }, {
  10267. generateMipMaps: false,
  10268. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10269. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10270. generateDepthBuffer: false,
  10271. generateStencilBuffer: false
  10272. });
  10273. if (!this._rescalePostProcess) {
  10274. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10275. }
  10276. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10277. _this._rescalePostProcess.onApply = function (effect) {
  10278. effect._bindTexture("textureSampler", source);
  10279. };
  10280. var hostingScene = scene;
  10281. if (!hostingScene) {
  10282. hostingScene = _this.scenes[_this.scenes.length - 1];
  10283. }
  10284. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10285. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10286. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10287. _this.unBindFramebuffer(rtt);
  10288. _this._releaseTexture(rtt);
  10289. if (onComplete) {
  10290. onComplete();
  10291. }
  10292. });
  10293. };
  10294. Engine.prototype._getInternalFormat = function (format) {
  10295. var internalFormat = this._gl.RGBA;
  10296. switch (format) {
  10297. case Engine.TEXTUREFORMAT_ALPHA:
  10298. internalFormat = this._gl.ALPHA;
  10299. break;
  10300. case Engine.TEXTUREFORMAT_LUMINANCE:
  10301. internalFormat = this._gl.LUMINANCE;
  10302. break;
  10303. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10304. internalFormat = this._gl.LUMINANCE_ALPHA;
  10305. break;
  10306. case Engine.TEXTUREFORMAT_RGB:
  10307. internalFormat = this._gl.RGB;
  10308. break;
  10309. case Engine.TEXTUREFORMAT_RGBA:
  10310. internalFormat = this._gl.RGBA;
  10311. break;
  10312. }
  10313. return internalFormat;
  10314. };
  10315. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10316. if (compression === void 0) { compression = null; }
  10317. if (!texture) {
  10318. return;
  10319. }
  10320. var internalFormat = this._getInternalFormat(format);
  10321. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10322. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10323. if (!this._doNotHandleContextLost) {
  10324. texture._bufferView = data;
  10325. texture.format = format;
  10326. texture.invertY = invertY;
  10327. texture._compression = compression;
  10328. }
  10329. if (texture.width % 4 !== 0) {
  10330. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10331. }
  10332. if (compression && data) {
  10333. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10334. }
  10335. else {
  10336. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10337. }
  10338. if (texture.generateMipMaps) {
  10339. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10340. }
  10341. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10342. this.resetTextureCache();
  10343. texture.isReady = true;
  10344. };
  10345. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10346. if (compression === void 0) { compression = null; }
  10347. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10348. texture.baseWidth = width;
  10349. texture.baseHeight = height;
  10350. texture.width = width;
  10351. texture.height = height;
  10352. texture.format = format;
  10353. texture.generateMipMaps = generateMipMaps;
  10354. texture.samplingMode = samplingMode;
  10355. texture.invertY = invertY;
  10356. texture._compression = compression;
  10357. if (!this._doNotHandleContextLost) {
  10358. texture._bufferView = data;
  10359. }
  10360. this.updateRawTexture(texture, data, format, invertY, compression);
  10361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10362. // Filters
  10363. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10364. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10365. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10366. if (generateMipMaps) {
  10367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10368. }
  10369. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10370. this._internalTexturesCache.push(texture);
  10371. return texture;
  10372. };
  10373. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10374. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10375. texture.baseWidth = width;
  10376. texture.baseHeight = height;
  10377. if (generateMipMaps) {
  10378. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10379. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10380. }
  10381. this.resetTextureCache();
  10382. texture.width = width;
  10383. texture.height = height;
  10384. texture.isReady = false;
  10385. texture.generateMipMaps = generateMipMaps;
  10386. texture.samplingMode = samplingMode;
  10387. this.updateTextureSamplingMode(samplingMode, texture);
  10388. this._internalTexturesCache.push(texture);
  10389. return texture;
  10390. };
  10391. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10392. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10393. if (texture.isCube) {
  10394. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10395. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10396. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10397. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10398. }
  10399. else if (texture.is3D) {
  10400. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10401. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10402. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10403. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10404. }
  10405. else {
  10406. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10407. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10408. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10410. }
  10411. texture.samplingMode = samplingMode;
  10412. };
  10413. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10414. if (premulAlpha === void 0) { premulAlpha = false; }
  10415. if (!texture) {
  10416. return;
  10417. }
  10418. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10419. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10420. if (premulAlpha) {
  10421. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10422. }
  10423. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10424. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10425. if (texture.generateMipMaps) {
  10426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10427. }
  10428. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10429. if (premulAlpha) {
  10430. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10431. }
  10432. this.resetTextureCache();
  10433. texture.isReady = true;
  10434. };
  10435. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10436. if (!texture || texture._isDisabled) {
  10437. return;
  10438. }
  10439. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10440. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10441. try {
  10442. // Testing video texture support
  10443. if (this._videoTextureSupported === undefined) {
  10444. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10445. if (this._gl.getError() !== 0) {
  10446. this._videoTextureSupported = false;
  10447. }
  10448. else {
  10449. this._videoTextureSupported = true;
  10450. }
  10451. }
  10452. // Copy video through the current working canvas if video texture is not supported
  10453. if (!this._videoTextureSupported) {
  10454. if (!texture._workingCanvas) {
  10455. texture._workingCanvas = document.createElement("canvas");
  10456. var context = texture._workingCanvas.getContext("2d");
  10457. if (!context) {
  10458. throw new Error("Unable to get 2d context");
  10459. }
  10460. texture._workingContext = context;
  10461. texture._workingCanvas.width = texture.width;
  10462. texture._workingCanvas.height = texture.height;
  10463. }
  10464. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10465. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10466. }
  10467. else {
  10468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10469. }
  10470. if (texture.generateMipMaps) {
  10471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10472. }
  10473. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10474. this.resetTextureCache();
  10475. texture.isReady = true;
  10476. }
  10477. catch (ex) {
  10478. // Something unexpected
  10479. // Let's disable the texture
  10480. texture._isDisabled = true;
  10481. }
  10482. };
  10483. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10484. var fullOptions = new RenderTargetCreationOptions();
  10485. if (options !== undefined && typeof options === "object") {
  10486. fullOptions.generateMipMaps = options.generateMipMaps;
  10487. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10488. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10489. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10490. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10491. }
  10492. else {
  10493. fullOptions.generateMipMaps = options;
  10494. fullOptions.generateDepthBuffer = true;
  10495. fullOptions.generateStencilBuffer = false;
  10496. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10497. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10498. }
  10499. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10500. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10501. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10502. }
  10503. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10504. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10505. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10506. }
  10507. var gl = this._gl;
  10508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10509. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10510. var width = size.width || size;
  10511. var height = size.height || size;
  10512. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10513. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10514. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10515. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10516. }
  10517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10520. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10521. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10522. // Create the framebuffer
  10523. var framebuffer = gl.createFramebuffer();
  10524. this.bindUnboundFramebuffer(framebuffer);
  10525. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10526. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10527. if (fullOptions.generateMipMaps) {
  10528. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10529. }
  10530. // Unbind
  10531. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10532. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10533. this.bindUnboundFramebuffer(null);
  10534. texture._framebuffer = framebuffer;
  10535. texture.baseWidth = width;
  10536. texture.baseHeight = height;
  10537. texture.width = width;
  10538. texture.height = height;
  10539. texture.isReady = true;
  10540. texture.samples = 1;
  10541. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10542. texture.samplingMode = fullOptions.samplingMode;
  10543. texture.type = fullOptions.type;
  10544. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10545. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10546. this.resetTextureCache();
  10547. this._internalTexturesCache.push(texture);
  10548. return texture;
  10549. };
  10550. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10551. var generateMipMaps = false;
  10552. var generateDepthBuffer = true;
  10553. var generateStencilBuffer = false;
  10554. var generateDepthTexture = false;
  10555. var textureCount = 1;
  10556. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10557. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10558. var types = [], samplingModes = [];
  10559. if (options !== undefined) {
  10560. generateMipMaps = options.generateMipMaps;
  10561. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10562. generateStencilBuffer = options.generateStencilBuffer;
  10563. generateDepthTexture = options.generateDepthTexture;
  10564. textureCount = options.textureCount || 1;
  10565. if (options.types) {
  10566. types = options.types;
  10567. }
  10568. if (options.samplingModes) {
  10569. samplingModes = options.samplingModes;
  10570. }
  10571. }
  10572. var gl = this._gl;
  10573. // Create the framebuffer
  10574. var framebuffer = gl.createFramebuffer();
  10575. this.bindUnboundFramebuffer(framebuffer);
  10576. var width = size.width || size;
  10577. var height = size.height || size;
  10578. var textures = [];
  10579. var attachments = [];
  10580. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10581. for (var i = 0; i < textureCount; i++) {
  10582. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10583. var type = types[i] || defaultType;
  10584. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10585. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10586. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10587. }
  10588. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10589. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10590. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10591. }
  10592. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10593. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10594. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10595. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10596. }
  10597. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10598. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10599. textures.push(texture);
  10600. attachments.push(attachment);
  10601. gl.activeTexture(gl["TEXTURE" + i]);
  10602. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10607. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10608. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10609. if (generateMipMaps) {
  10610. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10611. }
  10612. // Unbind
  10613. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10614. texture._framebuffer = framebuffer;
  10615. texture._depthStencilBuffer = depthStencilBuffer;
  10616. texture.baseWidth = width;
  10617. texture.baseHeight = height;
  10618. texture.width = width;
  10619. texture.height = height;
  10620. texture.isReady = true;
  10621. texture.samples = 1;
  10622. texture.generateMipMaps = generateMipMaps;
  10623. texture.samplingMode = samplingMode;
  10624. texture.type = type;
  10625. texture._generateDepthBuffer = generateDepthBuffer;
  10626. texture._generateStencilBuffer = generateStencilBuffer;
  10627. this._internalTexturesCache.push(texture);
  10628. }
  10629. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10630. // Depth texture
  10631. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10632. gl.activeTexture(gl.TEXTURE0);
  10633. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10634. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10635. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10638. 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);
  10639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10640. depthTexture._framebuffer = framebuffer;
  10641. depthTexture.baseWidth = width;
  10642. depthTexture.baseHeight = height;
  10643. depthTexture.width = width;
  10644. depthTexture.height = height;
  10645. depthTexture.isReady = true;
  10646. depthTexture.samples = 1;
  10647. depthTexture.generateMipMaps = generateMipMaps;
  10648. depthTexture.samplingMode = gl.NEAREST;
  10649. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10650. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10651. textures.push(depthTexture);
  10652. this._internalTexturesCache.push(depthTexture);
  10653. }
  10654. gl.drawBuffers(attachments);
  10655. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10656. this.bindUnboundFramebuffer(null);
  10657. this.resetTextureCache();
  10658. return textures;
  10659. };
  10660. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10661. if (samples === void 0) { samples = 1; }
  10662. var depthStencilBuffer = null;
  10663. var gl = this._gl;
  10664. // Create the depth/stencil buffer
  10665. if (generateStencilBuffer) {
  10666. depthStencilBuffer = gl.createRenderbuffer();
  10667. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10668. if (samples > 1) {
  10669. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10670. }
  10671. else {
  10672. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10673. }
  10674. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10675. }
  10676. else if (generateDepthBuffer) {
  10677. depthStencilBuffer = gl.createRenderbuffer();
  10678. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10679. if (samples > 1) {
  10680. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10681. }
  10682. else {
  10683. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10684. }
  10685. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10686. }
  10687. return depthStencilBuffer;
  10688. };
  10689. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10690. if (this.webGLVersion < 2 || !texture) {
  10691. return 1;
  10692. }
  10693. if (texture.samples === samples) {
  10694. return samples;
  10695. }
  10696. var gl = this._gl;
  10697. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10698. // Dispose previous render buffers
  10699. if (texture._depthStencilBuffer) {
  10700. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10701. }
  10702. if (texture._MSAAFramebuffer) {
  10703. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10704. }
  10705. if (texture._MSAARenderBuffer) {
  10706. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10707. }
  10708. if (samples > 1) {
  10709. var framebuffer = gl.createFramebuffer();
  10710. if (!framebuffer) {
  10711. throw new Error("Unable to create multi sampled framebuffer");
  10712. }
  10713. texture._MSAAFramebuffer = framebuffer;
  10714. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10715. var colorRenderbuffer = gl.createRenderbuffer();
  10716. if (!colorRenderbuffer) {
  10717. throw new Error("Unable to create multi sampled framebuffer");
  10718. }
  10719. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10720. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10721. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10722. texture._MSAARenderBuffer = colorRenderbuffer;
  10723. }
  10724. else {
  10725. this.bindUnboundFramebuffer(texture._framebuffer);
  10726. }
  10727. texture.samples = samples;
  10728. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10729. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10730. this.bindUnboundFramebuffer(null);
  10731. return samples;
  10732. };
  10733. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10734. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10735. };
  10736. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10737. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10738. };
  10739. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10740. var gl = this._gl;
  10741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10742. var generateMipMaps = true;
  10743. var generateDepthBuffer = true;
  10744. var generateStencilBuffer = false;
  10745. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10746. if (options !== undefined) {
  10747. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10748. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10749. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10750. if (options.samplingMode !== undefined) {
  10751. samplingMode = options.samplingMode;
  10752. }
  10753. }
  10754. texture.isCube = true;
  10755. texture.generateMipMaps = generateMipMaps;
  10756. texture.samples = 1;
  10757. texture.samplingMode = samplingMode;
  10758. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10759. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10760. for (var face = 0; face < 6; face++) {
  10761. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10762. }
  10763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10767. // Create the framebuffer
  10768. var framebuffer = gl.createFramebuffer();
  10769. this.bindUnboundFramebuffer(framebuffer);
  10770. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10771. // Mipmaps
  10772. if (texture.generateMipMaps) {
  10773. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10774. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10775. }
  10776. // Unbind
  10777. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10778. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10779. this.bindUnboundFramebuffer(null);
  10780. texture._framebuffer = framebuffer;
  10781. texture.width = size;
  10782. texture.height = size;
  10783. texture.isReady = true;
  10784. this.resetTextureCache();
  10785. this._internalTexturesCache.push(texture);
  10786. return texture;
  10787. };
  10788. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10789. var _this = this;
  10790. if (onLoad === void 0) { onLoad = null; }
  10791. if (onError === void 0) { onError = null; }
  10792. if (forcedExtension === void 0) { forcedExtension = null; }
  10793. var callback = function (loadData) {
  10794. if (!loadData) {
  10795. if (onLoad) {
  10796. onLoad(null);
  10797. }
  10798. return;
  10799. }
  10800. var texture = loadData.texture;
  10801. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10802. texture._lodGenerationScale = scale;
  10803. texture._lodGenerationOffset = offset;
  10804. if (_this._caps.textureLOD) {
  10805. // Do not add extra process if texture lod is supported.
  10806. if (onLoad) {
  10807. onLoad(texture);
  10808. }
  10809. return;
  10810. }
  10811. var mipSlices = 3;
  10812. var gl = _this._gl;
  10813. var width = loadData.width;
  10814. if (!width) {
  10815. return;
  10816. }
  10817. var textures = [];
  10818. for (var i = 0; i < mipSlices; i++) {
  10819. //compute LOD from even spacing in smoothness (matching shader calculation)
  10820. var smoothness = i / (mipSlices - 1);
  10821. var roughness = 1 - smoothness;
  10822. var minLODIndex = offset; // roughness = 0
  10823. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10824. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10825. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10826. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10827. glTextureFromLod.isCube = true;
  10828. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10833. if (loadData.isDDS) {
  10834. var info = loadData.info;
  10835. var data = loadData.data;
  10836. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10837. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10838. }
  10839. else {
  10840. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10841. }
  10842. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10843. // Wrap in a base texture for easy binding.
  10844. var lodTexture = new BABYLON.BaseTexture(scene);
  10845. lodTexture.isCube = true;
  10846. lodTexture._texture = glTextureFromLod;
  10847. glTextureFromLod.isReady = true;
  10848. textures.push(lodTexture);
  10849. }
  10850. texture._lodTextureHigh = textures[2];
  10851. texture._lodTextureMid = textures[1];
  10852. texture._lodTextureLow = textures[0];
  10853. if (onLoad) {
  10854. onLoad(texture);
  10855. }
  10856. };
  10857. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10858. };
  10859. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10860. var _this = this;
  10861. if (onLoad === void 0) { onLoad = null; }
  10862. if (onError === void 0) { onError = null; }
  10863. if (forcedExtension === void 0) { forcedExtension = null; }
  10864. var gl = this._gl;
  10865. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10866. texture.isCube = true;
  10867. texture.url = rootUrl;
  10868. texture.generateMipMaps = !noMipmap;
  10869. if (!this._doNotHandleContextLost) {
  10870. texture._extension = forcedExtension;
  10871. texture._files = files;
  10872. }
  10873. var isKTX = false;
  10874. var isDDS = false;
  10875. var lastDot = rootUrl.lastIndexOf('.');
  10876. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10877. if (this._textureFormatInUse) {
  10878. extension = this._textureFormatInUse;
  10879. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10880. isKTX = true;
  10881. }
  10882. else {
  10883. isDDS = (extension === ".dds");
  10884. }
  10885. var onerror = function (request, exception) {
  10886. if (onError) {
  10887. onError(request.status + " " + request.statusText, exception);
  10888. }
  10889. };
  10890. if (isKTX) {
  10891. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10892. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10893. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10894. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10895. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10896. ktx.uploadLevels(_this._gl, !noMipmap);
  10897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10899. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10900. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10901. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10902. _this.resetTextureCache();
  10903. texture.width = ktx.pixelWidth;
  10904. texture.height = ktx.pixelHeight;
  10905. texture.isReady = true;
  10906. }, undefined, undefined, true, onerror);
  10907. }
  10908. else if (isDDS) {
  10909. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10910. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10911. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10912. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10913. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10914. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10915. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10916. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10917. }
  10918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10922. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10923. _this.resetTextureCache();
  10924. texture.width = info.width;
  10925. texture.height = info.height;
  10926. texture.isReady = true;
  10927. texture.type = info.textureType;
  10928. if (onLoad) {
  10929. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10930. }
  10931. }, undefined, undefined, true, onerror);
  10932. }
  10933. else {
  10934. if (!files) {
  10935. throw new Error("Cannot load cubemap because files were not defined");
  10936. }
  10937. cascadeLoad(rootUrl, scene, function (imgs) {
  10938. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10939. var height = width;
  10940. _this._prepareWorkingCanvas();
  10941. if (!_this._workingCanvas || !_this._workingContext) {
  10942. return;
  10943. }
  10944. _this._workingCanvas.width = width;
  10945. _this._workingCanvas.height = height;
  10946. var faces = [
  10947. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10948. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10949. ];
  10950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10951. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10952. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10953. for (var index = 0; index < faces.length; index++) {
  10954. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10955. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10956. }
  10957. if (!noMipmap) {
  10958. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10959. }
  10960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10964. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10965. _this.resetTextureCache();
  10966. texture.width = width;
  10967. texture.height = height;
  10968. texture.isReady = true;
  10969. if (format) {
  10970. texture.format = format;
  10971. }
  10972. texture.onLoadedObservable.notifyObservers(texture);
  10973. texture.onLoadedObservable.clear();
  10974. if (onLoad) {
  10975. onLoad();
  10976. }
  10977. }, files, onError);
  10978. }
  10979. this._internalTexturesCache.push(texture);
  10980. return texture;
  10981. };
  10982. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10983. if (compression === void 0) { compression = null; }
  10984. if (level === void 0) { level = 0; }
  10985. texture._bufferViewArray = data;
  10986. texture.format = format;
  10987. texture.type = type;
  10988. texture.invertY = invertY;
  10989. texture._compression = compression;
  10990. var gl = this._gl;
  10991. var textureType = this._getWebGLTextureType(type);
  10992. var internalFormat = this._getInternalFormat(format);
  10993. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10994. var needConversion = false;
  10995. if (internalFormat === gl.RGB) {
  10996. internalFormat = gl.RGBA;
  10997. needConversion = true;
  10998. }
  10999. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11000. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11001. if (texture.width % 4 !== 0) {
  11002. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11003. }
  11004. // Data are known to be in +X +Y +Z -X -Y -Z
  11005. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11006. var faceData = data[faceIndex];
  11007. if (compression) {
  11008. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11009. }
  11010. else {
  11011. if (needConversion) {
  11012. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11013. }
  11014. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11015. }
  11016. }
  11017. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11018. if (isPot && texture.generateMipMaps && level === 0) {
  11019. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11020. }
  11021. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11022. this.resetTextureCache();
  11023. texture.isReady = true;
  11024. };
  11025. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11026. if (compression === void 0) { compression = null; }
  11027. var gl = this._gl;
  11028. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11029. texture.isCube = true;
  11030. texture.generateMipMaps = generateMipMaps;
  11031. texture.format = format;
  11032. texture.type = type;
  11033. if (!this._doNotHandleContextLost) {
  11034. texture._bufferViewArray = data;
  11035. }
  11036. var textureType = this._getWebGLTextureType(type);
  11037. var internalFormat = this._getInternalFormat(format);
  11038. var needConversion = false;
  11039. if (internalFormat === gl.RGB) {
  11040. internalFormat = gl.RGBA;
  11041. needConversion = true;
  11042. }
  11043. var width = size;
  11044. var height = width;
  11045. texture.width = width;
  11046. texture.height = height;
  11047. // Double check on POT to generate Mips.
  11048. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11049. if (!isPot) {
  11050. generateMipMaps = false;
  11051. }
  11052. // Upload data if needed. The texture won't be ready until then.
  11053. if (data) {
  11054. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11055. }
  11056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11057. // Filters
  11058. if (data && generateMipMaps) {
  11059. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11060. }
  11061. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11064. }
  11065. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11068. }
  11069. else {
  11070. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11073. }
  11074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11076. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11077. return texture;
  11078. };
  11079. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11080. var _this = this;
  11081. if (onLoad === void 0) { onLoad = null; }
  11082. if (onError === void 0) { onError = null; }
  11083. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11084. if (invertY === void 0) { invertY = false; }
  11085. var gl = this._gl;
  11086. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11087. scene._addPendingData(texture);
  11088. texture.url = url;
  11089. this._internalTexturesCache.push(texture);
  11090. var onerror = function (request, exception) {
  11091. scene._removePendingData(texture);
  11092. if (onError) {
  11093. onError(request.status + " " + request.statusText, exception);
  11094. }
  11095. };
  11096. var internalCallback = function (data) {
  11097. var width = texture.width;
  11098. var faceDataArrays = callback(data);
  11099. if (!faceDataArrays) {
  11100. return;
  11101. }
  11102. if (mipmmapGenerator) {
  11103. var textureType = _this._getWebGLTextureType(type);
  11104. var internalFormat = _this._getInternalFormat(format);
  11105. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11106. var needConversion = false;
  11107. if (internalFormat === gl.RGB) {
  11108. internalFormat = gl.RGBA;
  11109. needConversion = true;
  11110. }
  11111. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11112. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11113. var mipData = mipmmapGenerator(faceDataArrays);
  11114. for (var level = 0; level < mipData.length; level++) {
  11115. var mipSize = width >> level;
  11116. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11117. var mipFaceData = mipData[level][faceIndex];
  11118. if (needConversion) {
  11119. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11120. }
  11121. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11122. }
  11123. }
  11124. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11125. }
  11126. else {
  11127. texture.generateMipMaps = !noMipmap;
  11128. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11129. }
  11130. texture.isReady = true;
  11131. _this.resetTextureCache();
  11132. scene._removePendingData(texture);
  11133. if (onLoad) {
  11134. onLoad();
  11135. }
  11136. };
  11137. BABYLON.Tools.LoadFile(url, function (data) {
  11138. internalCallback(data);
  11139. }, undefined, scene.database, true, onerror);
  11140. return texture;
  11141. };
  11142. ;
  11143. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11144. if (compression === void 0) { compression = null; }
  11145. var internalFormat = this._getInternalFormat(format);
  11146. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11147. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11148. if (!this._doNotHandleContextLost) {
  11149. texture._bufferView = data;
  11150. texture.format = format;
  11151. texture.invertY = invertY;
  11152. texture._compression = compression;
  11153. }
  11154. if (texture.width % 4 !== 0) {
  11155. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11156. }
  11157. if (compression && data) {
  11158. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11159. }
  11160. else {
  11161. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11162. }
  11163. if (texture.generateMipMaps) {
  11164. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11165. }
  11166. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11167. this.resetTextureCache();
  11168. texture.isReady = true;
  11169. };
  11170. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11171. if (compression === void 0) { compression = null; }
  11172. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11173. texture.baseWidth = width;
  11174. texture.baseHeight = height;
  11175. texture.baseDepth = depth;
  11176. texture.width = width;
  11177. texture.height = height;
  11178. texture.depth = depth;
  11179. texture.format = format;
  11180. texture.generateMipMaps = generateMipMaps;
  11181. texture.samplingMode = samplingMode;
  11182. texture.is3D = true;
  11183. if (!this._doNotHandleContextLost) {
  11184. texture._bufferView = data;
  11185. }
  11186. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11187. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11188. // Filters
  11189. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11190. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11191. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11192. if (generateMipMaps) {
  11193. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11194. }
  11195. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11196. this._internalTexturesCache.push(texture);
  11197. return texture;
  11198. };
  11199. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11200. var gl = this._gl;
  11201. if (!gl) {
  11202. return;
  11203. }
  11204. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11205. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11206. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11207. if (!noMipmap && !isCompressed) {
  11208. gl.generateMipmap(gl.TEXTURE_2D);
  11209. }
  11210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11211. this.resetTextureCache();
  11212. if (scene) {
  11213. scene._removePendingData(texture);
  11214. }
  11215. texture.onLoadedObservable.notifyObservers(texture);
  11216. texture.onLoadedObservable.clear();
  11217. };
  11218. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11219. var _this = this;
  11220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11221. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11222. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11223. var gl = this._gl;
  11224. if (!gl) {
  11225. return;
  11226. }
  11227. if (!texture._webGLTexture) {
  11228. this.resetTextureCache();
  11229. if (scene) {
  11230. scene._removePendingData(texture);
  11231. }
  11232. return;
  11233. }
  11234. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11235. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11236. texture.baseWidth = width;
  11237. texture.baseHeight = height;
  11238. texture.width = potWidth;
  11239. texture.height = potHeight;
  11240. texture.isReady = true;
  11241. if (processFunction(potWidth, potHeight, function () {
  11242. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11243. })) {
  11244. // Returning as texture needs extra async steps
  11245. return;
  11246. }
  11247. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11248. };
  11249. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11250. // Create new RGBA data container.
  11251. var rgbaData;
  11252. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11253. rgbaData = new Float32Array(width * height * 4);
  11254. }
  11255. else {
  11256. rgbaData = new Uint32Array(width * height * 4);
  11257. }
  11258. // Convert each pixel.
  11259. for (var x = 0; x < width; x++) {
  11260. for (var y = 0; y < height; y++) {
  11261. var index = (y * width + x) * 3;
  11262. var newIndex = (y * width + x) * 4;
  11263. // Map Old Value to new value.
  11264. rgbaData[newIndex + 0] = rgbData[index + 0];
  11265. rgbaData[newIndex + 1] = rgbData[index + 1];
  11266. rgbaData[newIndex + 2] = rgbData[index + 2];
  11267. // Add fully opaque alpha channel.
  11268. rgbaData[newIndex + 3] = 1;
  11269. }
  11270. }
  11271. return rgbaData;
  11272. };
  11273. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11274. var gl = this._gl;
  11275. if (texture._framebuffer) {
  11276. gl.deleteFramebuffer(texture._framebuffer);
  11277. texture._framebuffer = null;
  11278. }
  11279. if (texture._depthStencilBuffer) {
  11280. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11281. texture._depthStencilBuffer = null;
  11282. }
  11283. if (texture._MSAAFramebuffer) {
  11284. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11285. texture._MSAAFramebuffer = null;
  11286. }
  11287. if (texture._MSAARenderBuffer) {
  11288. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11289. texture._MSAARenderBuffer = null;
  11290. }
  11291. };
  11292. Engine.prototype._releaseTexture = function (texture) {
  11293. var gl = this._gl;
  11294. this._releaseFramebufferObjects(texture);
  11295. gl.deleteTexture(texture._webGLTexture);
  11296. // Unbind channels
  11297. this.unbindAllTextures();
  11298. var index = this._internalTexturesCache.indexOf(texture);
  11299. if (index !== -1) {
  11300. this._internalTexturesCache.splice(index, 1);
  11301. }
  11302. // Integrated fixed lod samplers.
  11303. if (texture._lodTextureHigh) {
  11304. texture._lodTextureHigh.dispose();
  11305. }
  11306. if (texture._lodTextureMid) {
  11307. texture._lodTextureMid.dispose();
  11308. }
  11309. if (texture._lodTextureLow) {
  11310. texture._lodTextureLow.dispose();
  11311. }
  11312. };
  11313. Engine.prototype.setProgram = function (program) {
  11314. if (this._currentProgram !== program) {
  11315. this._gl.useProgram(program);
  11316. this._currentProgram = program;
  11317. }
  11318. };
  11319. Engine.prototype.bindSamplers = function (effect) {
  11320. this.setProgram(effect.getProgram());
  11321. var samplers = effect.getSamplers();
  11322. for (var index = 0; index < samplers.length; index++) {
  11323. var uniform = effect.getUniform(samplers[index]);
  11324. this._gl.uniform1i(uniform, index);
  11325. }
  11326. this._currentEffect = null;
  11327. };
  11328. Engine.prototype.activateTexture = function (texture) {
  11329. if (this._activeTexture !== texture) {
  11330. this._gl.activeTexture(texture);
  11331. this._activeTexture = texture;
  11332. }
  11333. };
  11334. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11335. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11336. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11337. this._activeTexturesCache[this._activeTexture] = texture;
  11338. }
  11339. };
  11340. Engine.prototype._bindTexture = function (channel, texture) {
  11341. if (channel < 0) {
  11342. return;
  11343. }
  11344. this.activateTexture(this._gl.TEXTURE0 + channel);
  11345. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11346. };
  11347. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11348. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11349. };
  11350. Engine.prototype.unbindAllTextures = function () {
  11351. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11352. this.activateTexture(this._gl["TEXTURE" + channel]);
  11353. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11354. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11355. if (this.webGLVersion > 1) {
  11356. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11357. }
  11358. }
  11359. };
  11360. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11361. if (channel < 0) {
  11362. return;
  11363. }
  11364. this._gl.uniform1i(uniform, channel);
  11365. this._setTexture(channel, texture);
  11366. };
  11367. Engine.prototype._setTexture = function (channel, texture) {
  11368. // Not ready?
  11369. if (!texture) {
  11370. if (this._activeTexturesCache[channel] != null) {
  11371. this.activateTexture(this._gl["TEXTURE" + channel]);
  11372. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11373. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11374. if (this.webGLVersion > 1) {
  11375. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11376. }
  11377. }
  11378. return;
  11379. }
  11380. // Video
  11381. var alreadyActivated = false;
  11382. if (texture.video) {
  11383. this.activateTexture(this._gl["TEXTURE" + channel]);
  11384. alreadyActivated = true;
  11385. texture.update();
  11386. }
  11387. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11388. texture.delayLoad();
  11389. return;
  11390. }
  11391. var internalTexture;
  11392. if (texture.isReady()) {
  11393. internalTexture = texture.getInternalTexture();
  11394. }
  11395. else if (texture.isCube) {
  11396. internalTexture = this.emptyCubeTexture;
  11397. }
  11398. else if (texture.is3D) {
  11399. internalTexture = this.emptyTexture3D;
  11400. }
  11401. else {
  11402. internalTexture = this.emptyTexture;
  11403. }
  11404. if (this._activeTexturesCache[channel] === internalTexture) {
  11405. return;
  11406. }
  11407. if (!alreadyActivated) {
  11408. this.activateTexture(this._gl["TEXTURE" + channel]);
  11409. }
  11410. if (internalTexture && internalTexture.is3D) {
  11411. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11412. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11413. internalTexture._cachedWrapU = texture.wrapU;
  11414. switch (texture.wrapU) {
  11415. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11416. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11417. break;
  11418. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11419. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11420. break;
  11421. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11422. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11423. break;
  11424. }
  11425. }
  11426. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11427. internalTexture._cachedWrapV = texture.wrapV;
  11428. switch (texture.wrapV) {
  11429. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11430. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11431. break;
  11432. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11433. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11434. break;
  11435. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11436. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11437. break;
  11438. }
  11439. }
  11440. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11441. internalTexture._cachedWrapR = texture.wrapR;
  11442. switch (texture.wrapV) {
  11443. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11444. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11445. break;
  11446. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11447. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11448. break;
  11449. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11450. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11451. break;
  11452. }
  11453. }
  11454. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11455. }
  11456. else if (internalTexture && internalTexture.isCube) {
  11457. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11458. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11459. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11460. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11461. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11462. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11463. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11464. }
  11465. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11466. }
  11467. else {
  11468. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11469. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11470. internalTexture._cachedWrapU = texture.wrapU;
  11471. switch (texture.wrapU) {
  11472. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11473. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11474. break;
  11475. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11476. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11477. break;
  11478. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11479. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11480. break;
  11481. }
  11482. }
  11483. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11484. internalTexture._cachedWrapV = texture.wrapV;
  11485. switch (texture.wrapV) {
  11486. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11487. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11488. break;
  11489. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11490. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11491. break;
  11492. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11493. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11494. break;
  11495. }
  11496. }
  11497. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11498. }
  11499. };
  11500. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11501. if (channel < 0 || !uniform) {
  11502. return;
  11503. }
  11504. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11505. this._textureUnits = new Int32Array(textures.length);
  11506. }
  11507. for (var i = 0; i < textures.length; i++) {
  11508. this._textureUnits[i] = channel + i;
  11509. }
  11510. this._gl.uniform1iv(uniform, this._textureUnits);
  11511. for (var index = 0; index < textures.length; index++) {
  11512. this._setTexture(channel + index, textures[index]);
  11513. }
  11514. };
  11515. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11516. var internalTexture = texture.getInternalTexture();
  11517. if (!internalTexture) {
  11518. return;
  11519. }
  11520. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11521. var value = texture.anisotropicFilteringLevel;
  11522. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11523. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11524. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11525. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11526. }
  11527. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11528. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11529. internalTexture._cachedAnisotropicFilteringLevel = value;
  11530. }
  11531. };
  11532. Engine.prototype.readPixels = function (x, y, width, height) {
  11533. var data = new Uint8Array(height * width * 4);
  11534. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11535. return data;
  11536. };
  11537. /**
  11538. * Add an externaly attached data from its key.
  11539. * This method call will fail and return false, if such key already exists.
  11540. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11541. * @param key the unique key that identifies the data
  11542. * @param data the data object to associate to the key for this Engine instance
  11543. * @return true if no such key were already present and the data was added successfully, false otherwise
  11544. */
  11545. Engine.prototype.addExternalData = function (key, data) {
  11546. if (!this._externalData) {
  11547. this._externalData = new BABYLON.StringDictionary();
  11548. }
  11549. return this._externalData.add(key, data);
  11550. };
  11551. /**
  11552. * Get an externaly attached data from its key
  11553. * @param key the unique key that identifies the data
  11554. * @return the associated data, if present (can be null), or undefined if not present
  11555. */
  11556. Engine.prototype.getExternalData = function (key) {
  11557. if (!this._externalData) {
  11558. this._externalData = new BABYLON.StringDictionary();
  11559. }
  11560. return this._externalData.get(key);
  11561. };
  11562. /**
  11563. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11564. * @param key the unique key that identifies the data
  11565. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11566. * @return the associated data, can be null if the factory returned null.
  11567. */
  11568. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11569. if (!this._externalData) {
  11570. this._externalData = new BABYLON.StringDictionary();
  11571. }
  11572. return this._externalData.getOrAddWithFactory(key, factory);
  11573. };
  11574. /**
  11575. * Remove an externaly attached data from the Engine instance
  11576. * @param key the unique key that identifies the data
  11577. * @return true if the data was successfully removed, false if it doesn't exist
  11578. */
  11579. Engine.prototype.removeExternalData = function (key) {
  11580. if (!this._externalData) {
  11581. this._externalData = new BABYLON.StringDictionary();
  11582. }
  11583. return this._externalData.remove(key);
  11584. };
  11585. Engine.prototype.unbindAllAttributes = function () {
  11586. if (this._mustWipeVertexAttributes) {
  11587. this._mustWipeVertexAttributes = false;
  11588. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11589. this._gl.disableVertexAttribArray(i);
  11590. this._vertexAttribArraysEnabled[i] = false;
  11591. this._currentBufferPointers[i].active = false;
  11592. }
  11593. return;
  11594. }
  11595. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11596. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11597. continue;
  11598. }
  11599. this._gl.disableVertexAttribArray(i);
  11600. this._vertexAttribArraysEnabled[i] = false;
  11601. this._currentBufferPointers[i].active = false;
  11602. }
  11603. };
  11604. Engine.prototype.releaseEffects = function () {
  11605. for (var name in this._compiledEffects) {
  11606. this._deleteProgram(this._compiledEffects[name]._program);
  11607. }
  11608. this._compiledEffects = {};
  11609. };
  11610. // Dispose
  11611. Engine.prototype.dispose = function () {
  11612. this.hideLoadingUI();
  11613. this.stopRenderLoop();
  11614. // Release postProcesses
  11615. while (this.postProcesses.length) {
  11616. this.postProcesses[0].dispose();
  11617. }
  11618. // Empty texture
  11619. if (this._emptyTexture) {
  11620. this._releaseTexture(this._emptyTexture);
  11621. this._emptyTexture = null;
  11622. }
  11623. if (this._emptyCubeTexture) {
  11624. this._releaseTexture(this._emptyCubeTexture);
  11625. this._emptyCubeTexture = null;
  11626. }
  11627. // Rescale PP
  11628. if (this._rescalePostProcess) {
  11629. this._rescalePostProcess.dispose();
  11630. }
  11631. // Release scenes
  11632. while (this.scenes.length) {
  11633. this.scenes[0].dispose();
  11634. }
  11635. // Release audio engine
  11636. if (Engine.audioEngine) {
  11637. Engine.audioEngine.dispose();
  11638. }
  11639. // Release effects
  11640. this.releaseEffects();
  11641. // Unbind
  11642. this.unbindAllAttributes();
  11643. if (this._dummyFramebuffer) {
  11644. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11645. }
  11646. //WebVR
  11647. this.disableVR();
  11648. // Events
  11649. window.removeEventListener("blur", this._onBlur);
  11650. window.removeEventListener("focus", this._onFocus);
  11651. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11652. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11653. if (this._renderingCanvas) {
  11654. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11655. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11656. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11657. if (!this._doNotHandleContextLost) {
  11658. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11659. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11660. }
  11661. }
  11662. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11663. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11664. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11665. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11666. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11667. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11668. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11669. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11670. if (this._onVrDisplayConnect) {
  11671. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11672. if (this._onVrDisplayDisconnect) {
  11673. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11674. }
  11675. if (this._onVrDisplayPresentChange) {
  11676. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11677. }
  11678. this._onVrDisplayConnect = null;
  11679. this._onVrDisplayDisconnect = null;
  11680. }
  11681. // Remove from Instances
  11682. var index = Engine.Instances.indexOf(this);
  11683. if (index >= 0) {
  11684. Engine.Instances.splice(index, 1);
  11685. }
  11686. this._workingCanvas = null;
  11687. this._workingContext = null;
  11688. this._currentBufferPointers = [];
  11689. this._renderingCanvas = null;
  11690. this._currentProgram = null;
  11691. this.onResizeObservable.clear();
  11692. this.onCanvasBlurObservable.clear();
  11693. this.onCanvasFocusObservable.clear();
  11694. this.onCanvasPointerOutObservable.clear();
  11695. this.onBeginFrameObservable.clear();
  11696. this.onEndFrameObservable.clear();
  11697. BABYLON.Effect.ResetCache();
  11698. };
  11699. // Loading screen
  11700. Engine.prototype.displayLoadingUI = function () {
  11701. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11702. return;
  11703. }
  11704. var loadingScreen = this.loadingScreen;
  11705. if (loadingScreen) {
  11706. loadingScreen.displayLoadingUI();
  11707. }
  11708. };
  11709. Engine.prototype.hideLoadingUI = function () {
  11710. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11711. return;
  11712. }
  11713. var loadingScreen = this.loadingScreen;
  11714. if (loadingScreen) {
  11715. loadingScreen.hideLoadingUI();
  11716. }
  11717. };
  11718. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11719. get: function () {
  11720. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11721. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11722. return this._loadingScreen;
  11723. },
  11724. set: function (loadingScreen) {
  11725. this._loadingScreen = loadingScreen;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11731. set: function (text) {
  11732. this.loadingScreen.loadingUIText = text;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11738. set: function (color) {
  11739. this.loadingScreen.loadingUIBackgroundColor = color;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Engine.prototype.attachContextLostEvent = function (callback) {
  11745. if (this._renderingCanvas) {
  11746. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11747. }
  11748. };
  11749. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11750. if (this._renderingCanvas) {
  11751. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11752. }
  11753. };
  11754. Engine.prototype.getVertexShaderSource = function (program) {
  11755. var shaders = this._gl.getAttachedShaders(program);
  11756. if (!shaders) {
  11757. return null;
  11758. }
  11759. return this._gl.getShaderSource(shaders[0]);
  11760. };
  11761. Engine.prototype.getFragmentShaderSource = function (program) {
  11762. var shaders = this._gl.getAttachedShaders(program);
  11763. if (!shaders) {
  11764. return null;
  11765. }
  11766. return this._gl.getShaderSource(shaders[1]);
  11767. };
  11768. Engine.prototype.getError = function () {
  11769. return this._gl.getError();
  11770. };
  11771. // FPS
  11772. Engine.prototype.getFps = function () {
  11773. return this._fps;
  11774. };
  11775. Engine.prototype.getDeltaTime = function () {
  11776. return this._deltaTime;
  11777. };
  11778. Engine.prototype._measureFps = function () {
  11779. this._performanceMonitor.sampleFrame();
  11780. this._fps = this._performanceMonitor.averageFPS;
  11781. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11782. };
  11783. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11784. if (faceIndex === void 0) { faceIndex = -1; }
  11785. var gl = this._gl;
  11786. if (!this._dummyFramebuffer) {
  11787. var dummy = gl.createFramebuffer();
  11788. if (!dummy) {
  11789. throw new Error("Unable to create dummy framebuffer");
  11790. }
  11791. this._dummyFramebuffer = dummy;
  11792. }
  11793. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11794. if (faceIndex > -1) {
  11795. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11796. }
  11797. else {
  11798. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11799. }
  11800. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11801. var buffer;
  11802. switch (readType) {
  11803. case gl.UNSIGNED_BYTE:
  11804. buffer = new Uint8Array(4 * width * height);
  11805. readType = gl.UNSIGNED_BYTE;
  11806. break;
  11807. default:
  11808. buffer = new Float32Array(4 * width * height);
  11809. readType = gl.FLOAT;
  11810. break;
  11811. }
  11812. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11813. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11814. return buffer;
  11815. };
  11816. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11817. if (this._webGLVersion > 1) {
  11818. return this._caps.colorBufferFloat;
  11819. }
  11820. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11821. };
  11822. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11823. if (this._webGLVersion > 1) {
  11824. return this._caps.colorBufferFloat;
  11825. }
  11826. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11827. };
  11828. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11829. Engine.prototype._canRenderToFramebuffer = function (type) {
  11830. var gl = this._gl;
  11831. //clear existing errors
  11832. while (gl.getError() !== gl.NO_ERROR) { }
  11833. var successful = true;
  11834. var texture = gl.createTexture();
  11835. gl.bindTexture(gl.TEXTURE_2D, texture);
  11836. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11837. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11838. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11839. var fb = gl.createFramebuffer();
  11840. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11841. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11842. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11843. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11844. successful = successful && (gl.getError() === gl.NO_ERROR);
  11845. //try render by clearing frame buffer's color buffer
  11846. if (successful) {
  11847. gl.clear(gl.COLOR_BUFFER_BIT);
  11848. successful = successful && (gl.getError() === gl.NO_ERROR);
  11849. }
  11850. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11851. if (successful) {
  11852. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11853. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11854. var readFormat = gl.RGBA;
  11855. var readType = gl.UNSIGNED_BYTE;
  11856. var buffer = new Uint8Array(4);
  11857. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11858. successful = successful && (gl.getError() === gl.NO_ERROR);
  11859. }
  11860. //clean up
  11861. gl.deleteTexture(texture);
  11862. gl.deleteFramebuffer(fb);
  11863. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11864. //clear accumulated errors
  11865. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11866. return successful;
  11867. };
  11868. Engine.prototype._getWebGLTextureType = function (type) {
  11869. if (type === Engine.TEXTURETYPE_FLOAT) {
  11870. return this._gl.FLOAT;
  11871. }
  11872. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11873. // Add Half Float Constant.
  11874. return this._gl.HALF_FLOAT_OES;
  11875. }
  11876. return this._gl.UNSIGNED_BYTE;
  11877. };
  11878. ;
  11879. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11880. if (this._webGLVersion === 1) {
  11881. return this._gl.RGBA;
  11882. }
  11883. if (type === Engine.TEXTURETYPE_FLOAT) {
  11884. return this._gl.RGBA32F;
  11885. }
  11886. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11887. return this._gl.RGBA16F;
  11888. }
  11889. return this._gl.RGBA;
  11890. };
  11891. ;
  11892. Engine.prototype.createQuery = function () {
  11893. return this._gl.createQuery();
  11894. };
  11895. Engine.prototype.deleteQuery = function (query) {
  11896. this._gl.deleteQuery(query);
  11897. return this;
  11898. };
  11899. Engine.prototype.isQueryResultAvailable = function (query) {
  11900. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11901. };
  11902. Engine.prototype.getQueryResult = function (query) {
  11903. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11904. };
  11905. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11906. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11907. this._gl.beginQuery(glAlgorithm, query);
  11908. return this;
  11909. };
  11910. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11911. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11912. this._gl.endQuery(glAlgorithm);
  11913. return this;
  11914. };
  11915. /* Time queries */
  11916. Engine.prototype._createTimeQuery = function () {
  11917. var timerQuery = this._caps.timerQuery;
  11918. if (timerQuery.createQueryEXT) {
  11919. return timerQuery.createQueryEXT();
  11920. }
  11921. return this.createQuery();
  11922. };
  11923. Engine.prototype._deleteTimeQuery = function (query) {
  11924. var timerQuery = this._caps.timerQuery;
  11925. if (timerQuery.deleteQueryEXT) {
  11926. timerQuery.deleteQueryEXT(query);
  11927. return;
  11928. }
  11929. this.deleteQuery(query);
  11930. };
  11931. Engine.prototype._getTimeQueryResult = function (query) {
  11932. var timerQuery = this._caps.timerQuery;
  11933. if (timerQuery.getQueryObjectEXT) {
  11934. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11935. }
  11936. return this.getQueryResult(query);
  11937. };
  11938. Engine.prototype._getTimeQueryAvailability = function (query) {
  11939. var timerQuery = this._caps.timerQuery;
  11940. if (timerQuery.getQueryObjectEXT) {
  11941. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11942. }
  11943. return this.isQueryResultAvailable(query);
  11944. };
  11945. Engine.prototype.startTimeQuery = function () {
  11946. var timerQuery = this._caps.timerQuery;
  11947. if (!timerQuery) {
  11948. return null;
  11949. }
  11950. var token = new BABYLON._TimeToken();
  11951. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11952. if (this._caps.canUseTimestampForTimerQuery) {
  11953. token._startTimeQuery = this._createTimeQuery();
  11954. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  11955. }
  11956. else {
  11957. token._timeElapsedQuery = this._createTimeQuery();
  11958. if (timerQuery.beginQueryEXT) {
  11959. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11960. }
  11961. else {
  11962. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  11963. }
  11964. }
  11965. return token;
  11966. };
  11967. Engine.prototype.endTimeQuery = function (token) {
  11968. var timerQuery = this._caps.timerQuery;
  11969. if (!timerQuery || !token) {
  11970. return -1;
  11971. }
  11972. if (this._caps.canUseTimestampForTimerQuery) {
  11973. if (!token._startTimeQuery) {
  11974. return -1;
  11975. }
  11976. if (!token._endTimeQuery) {
  11977. token._endTimeQuery = this._createTimeQuery();
  11978. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  11979. }
  11980. }
  11981. else if (!token._timeElapsedQueryEnded) {
  11982. if (!token._timeElapsedQuery) {
  11983. return -1;
  11984. }
  11985. if (timerQuery.endQueryEXT) {
  11986. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  11987. }
  11988. else {
  11989. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  11990. }
  11991. token._timeElapsedQueryEnded = true;
  11992. }
  11993. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  11994. var available = false;
  11995. if (token._endTimeQuery) {
  11996. available = this._getTimeQueryAvailability(token._endTimeQuery);
  11997. }
  11998. else if (token._timeElapsedQuery) {
  11999. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12000. }
  12001. if (available && !disjoint) {
  12002. var result = 0;
  12003. if (this._caps.canUseTimestampForTimerQuery) {
  12004. if (!token._startTimeQuery || !token._endTimeQuery) {
  12005. return -1;
  12006. }
  12007. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12008. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12009. result = timeEnd - timeStart;
  12010. this._deleteTimeQuery(token._startTimeQuery);
  12011. this._deleteTimeQuery(token._endTimeQuery);
  12012. token._startTimeQuery = null;
  12013. token._endTimeQuery = null;
  12014. }
  12015. else {
  12016. if (!token._timeElapsedQuery) {
  12017. return -1;
  12018. }
  12019. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12020. this._deleteTimeQuery(token._timeElapsedQuery);
  12021. token._timeElapsedQuery = null;
  12022. token._timeElapsedQueryEnded = false;
  12023. }
  12024. return result;
  12025. }
  12026. return -1;
  12027. };
  12028. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12029. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12030. };
  12031. // Statics
  12032. Engine.isSupported = function () {
  12033. try {
  12034. var tempcanvas = document.createElement("canvas");
  12035. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12036. return gl != null && !!window.WebGLRenderingContext;
  12037. }
  12038. catch (e) {
  12039. return false;
  12040. }
  12041. };
  12042. Engine.Instances = new Array();
  12043. // Const statics
  12044. Engine._ALPHA_DISABLE = 0;
  12045. Engine._ALPHA_ADD = 1;
  12046. Engine._ALPHA_COMBINE = 2;
  12047. Engine._ALPHA_SUBTRACT = 3;
  12048. Engine._ALPHA_MULTIPLY = 4;
  12049. Engine._ALPHA_MAXIMIZED = 5;
  12050. Engine._ALPHA_ONEONE = 6;
  12051. Engine._ALPHA_PREMULTIPLIED = 7;
  12052. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12053. Engine._ALPHA_INTERPOLATE = 9;
  12054. Engine._ALPHA_SCREENMODE = 10;
  12055. Engine._DELAYLOADSTATE_NONE = 0;
  12056. Engine._DELAYLOADSTATE_LOADED = 1;
  12057. Engine._DELAYLOADSTATE_LOADING = 2;
  12058. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12059. Engine._TEXTUREFORMAT_ALPHA = 0;
  12060. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12061. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12062. Engine._TEXTUREFORMAT_RGB = 4;
  12063. Engine._TEXTUREFORMAT_RGBA = 5;
  12064. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12065. Engine._TEXTURETYPE_FLOAT = 1;
  12066. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12067. // Depht or Stencil test Constants.
  12068. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12069. 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.
  12070. 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.
  12071. 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.
  12072. 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.
  12073. 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.
  12074. 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.
  12075. 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.
  12076. // Stencil Actions Constants.
  12077. Engine._KEEP = 0x1E00;
  12078. Engine._REPLACE = 0x1E01;
  12079. Engine._INCR = 0x1E02;
  12080. Engine._DECR = 0x1E03;
  12081. Engine._INVERT = 0x150A;
  12082. Engine._INCR_WRAP = 0x8507;
  12083. Engine._DECR_WRAP = 0x8508;
  12084. // Texture rescaling mode
  12085. Engine._SCALEMODE_FLOOR = 1;
  12086. Engine._SCALEMODE_NEAREST = 2;
  12087. Engine._SCALEMODE_CEILING = 3;
  12088. // Updatable statics so stick with vars here
  12089. Engine.CollisionsEpsilon = 0.001;
  12090. Engine.CodeRepository = "src/";
  12091. Engine.ShadersRepository = "src/Shaders/";
  12092. return Engine;
  12093. }());
  12094. BABYLON.Engine = Engine;
  12095. })(BABYLON || (BABYLON = {}));
  12096. //# sourceMappingURL=babylon.engine.js.map
  12097. var BABYLON;
  12098. (function (BABYLON) {
  12099. /**
  12100. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12101. */
  12102. var Node = /** @class */ (function () {
  12103. /**
  12104. * @constructor
  12105. * @param {string} name - the name and id to be given to this node
  12106. * @param {BABYLON.Scene} the scene this node will be added to
  12107. */
  12108. function Node(name, scene) {
  12109. if (scene === void 0) { scene = null; }
  12110. this.state = "";
  12111. this.metadata = null;
  12112. this.doNotSerialize = false;
  12113. this.animations = new Array();
  12114. this._ranges = {};
  12115. this._isEnabled = true;
  12116. this._isReady = true;
  12117. this._currentRenderId = -1;
  12118. this._parentRenderId = -1;
  12119. /**
  12120. * An event triggered when the mesh is disposed.
  12121. * @type {BABYLON.Observable}
  12122. */
  12123. this.onDisposeObservable = new BABYLON.Observable();
  12124. // Behaviors
  12125. this._behaviors = new Array();
  12126. this.name = name;
  12127. this.id = name;
  12128. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12129. this.uniqueId = this._scene.getUniqueId();
  12130. this._initCache();
  12131. }
  12132. Object.defineProperty(Node.prototype, "parent", {
  12133. get: function () {
  12134. return this._parentNode;
  12135. },
  12136. set: function (parent) {
  12137. if (this._parentNode === parent) {
  12138. return;
  12139. }
  12140. if (this._parentNode) {
  12141. var index = this._parentNode._children.indexOf(this);
  12142. if (index !== -1) {
  12143. this._parentNode._children.splice(index, 1);
  12144. }
  12145. }
  12146. this._parentNode = parent;
  12147. if (this._parentNode) {
  12148. if (!this._parentNode._children) {
  12149. this._parentNode._children = new Array();
  12150. }
  12151. this._parentNode._children.push(this);
  12152. }
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Node.prototype.getClassName = function () {
  12158. return "Node";
  12159. };
  12160. Object.defineProperty(Node.prototype, "onDispose", {
  12161. set: function (callback) {
  12162. if (this._onDisposeObserver) {
  12163. this.onDisposeObservable.remove(this._onDisposeObserver);
  12164. }
  12165. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Node.prototype.getScene = function () {
  12171. return this._scene;
  12172. };
  12173. Node.prototype.getEngine = function () {
  12174. return this._scene.getEngine();
  12175. };
  12176. Node.prototype.addBehavior = function (behavior) {
  12177. var index = this._behaviors.indexOf(behavior);
  12178. if (index !== -1) {
  12179. return this;
  12180. }
  12181. behavior.attach(this);
  12182. this._behaviors.push(behavior);
  12183. return this;
  12184. };
  12185. Node.prototype.removeBehavior = function (behavior) {
  12186. var index = this._behaviors.indexOf(behavior);
  12187. if (index === -1) {
  12188. return this;
  12189. }
  12190. this._behaviors[index].detach();
  12191. this._behaviors.splice(index, 1);
  12192. return this;
  12193. };
  12194. Object.defineProperty(Node.prototype, "behaviors", {
  12195. get: function () {
  12196. return this._behaviors;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Node.prototype.getBehaviorByName = function (name) {
  12202. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12203. var behavior = _a[_i];
  12204. if (behavior.name === name) {
  12205. return behavior;
  12206. }
  12207. }
  12208. return null;
  12209. };
  12210. // override it in derived class
  12211. Node.prototype.getWorldMatrix = function () {
  12212. return BABYLON.Matrix.Identity();
  12213. };
  12214. // override it in derived class if you add new variables to the cache
  12215. // and call the parent class method
  12216. Node.prototype._initCache = function () {
  12217. this._cache = {};
  12218. this._cache.parent = undefined;
  12219. };
  12220. Node.prototype.updateCache = function (force) {
  12221. if (!force && this.isSynchronized())
  12222. return;
  12223. this._cache.parent = this.parent;
  12224. this._updateCache();
  12225. };
  12226. // override it in derived class if you add new variables to the cache
  12227. // and call the parent class method if !ignoreParentClass
  12228. Node.prototype._updateCache = function (ignoreParentClass) {
  12229. };
  12230. // override it in derived class if you add new variables to the cache
  12231. Node.prototype._isSynchronized = function () {
  12232. return true;
  12233. };
  12234. Node.prototype._markSyncedWithParent = function () {
  12235. if (this.parent) {
  12236. this._parentRenderId = this.parent._currentRenderId;
  12237. }
  12238. };
  12239. Node.prototype.isSynchronizedWithParent = function () {
  12240. if (!this.parent) {
  12241. return true;
  12242. }
  12243. if (this._parentRenderId !== this.parent._currentRenderId) {
  12244. return false;
  12245. }
  12246. return this.parent.isSynchronized();
  12247. };
  12248. Node.prototype.isSynchronized = function (updateCache) {
  12249. var check = this.hasNewParent();
  12250. check = check || !this.isSynchronizedWithParent();
  12251. check = check || !this._isSynchronized();
  12252. if (updateCache)
  12253. this.updateCache(true);
  12254. return !check;
  12255. };
  12256. Node.prototype.hasNewParent = function (update) {
  12257. if (this._cache.parent === this.parent)
  12258. return false;
  12259. if (update)
  12260. this._cache.parent = this.parent;
  12261. return true;
  12262. };
  12263. /**
  12264. * Is this node ready to be used/rendered
  12265. * @return {boolean} is it ready
  12266. */
  12267. Node.prototype.isReady = function () {
  12268. return this._isReady;
  12269. };
  12270. /**
  12271. * Is this node enabled.
  12272. * If the node has a parent and is enabled, the parent will be inspected as well.
  12273. * @return {boolean} whether this node (and its parent) is enabled.
  12274. * @see setEnabled
  12275. */
  12276. Node.prototype.isEnabled = function () {
  12277. if (!this._isEnabled) {
  12278. return false;
  12279. }
  12280. if (this.parent) {
  12281. return this.parent.isEnabled();
  12282. }
  12283. return true;
  12284. };
  12285. /**
  12286. * Set the enabled state of this node.
  12287. * @param {boolean} value - the new enabled state
  12288. * @see isEnabled
  12289. */
  12290. Node.prototype.setEnabled = function (value) {
  12291. this._isEnabled = value;
  12292. };
  12293. /**
  12294. * Is this node a descendant of the given node.
  12295. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12296. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12297. * @see parent
  12298. */
  12299. Node.prototype.isDescendantOf = function (ancestor) {
  12300. if (this.parent) {
  12301. if (this.parent === ancestor) {
  12302. return true;
  12303. }
  12304. return this.parent.isDescendantOf(ancestor);
  12305. }
  12306. return false;
  12307. };
  12308. /**
  12309. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12310. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12311. * @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.
  12312. * @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.
  12313. */
  12314. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12315. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12316. if (!this._children) {
  12317. return;
  12318. }
  12319. for (var index = 0; index < this._children.length; index++) {
  12320. var item = this._children[index];
  12321. if (!predicate || predicate(item)) {
  12322. results.push(item);
  12323. }
  12324. if (!directDescendantsOnly) {
  12325. item._getDescendants(results, false, predicate);
  12326. }
  12327. }
  12328. };
  12329. /**
  12330. * Will return all nodes that have this node as ascendant.
  12331. * @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.
  12332. * @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.
  12333. * @return {BABYLON.Node[]} all children nodes of all types.
  12334. */
  12335. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12336. var results = new Array();
  12337. this._getDescendants(results, directDescendantsOnly, predicate);
  12338. return results;
  12339. };
  12340. /**
  12341. * Get all child-meshes of this node.
  12342. */
  12343. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12344. var results = [];
  12345. this._getDescendants(results, directDecendantsOnly, function (node) {
  12346. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12347. });
  12348. return results;
  12349. };
  12350. /**
  12351. * Get all direct children of this node.
  12352. */
  12353. Node.prototype.getChildren = function (predicate) {
  12354. return this.getDescendants(true, predicate);
  12355. };
  12356. Node.prototype._setReady = function (state) {
  12357. if (state === this._isReady) {
  12358. return;
  12359. }
  12360. if (!state) {
  12361. this._isReady = false;
  12362. return;
  12363. }
  12364. this._isReady = true;
  12365. if (this.onReady) {
  12366. this.onReady(this);
  12367. }
  12368. };
  12369. Node.prototype.getAnimationByName = function (name) {
  12370. for (var i = 0; i < this.animations.length; i++) {
  12371. var animation = this.animations[i];
  12372. if (animation.name === name) {
  12373. return animation;
  12374. }
  12375. }
  12376. return null;
  12377. };
  12378. Node.prototype.createAnimationRange = function (name, from, to) {
  12379. // check name not already in use
  12380. if (!this._ranges[name]) {
  12381. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12382. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12383. if (this.animations[i]) {
  12384. this.animations[i].createRange(name, from, to);
  12385. }
  12386. }
  12387. }
  12388. };
  12389. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12390. if (deleteFrames === void 0) { deleteFrames = true; }
  12391. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12392. if (this.animations[i]) {
  12393. this.animations[i].deleteRange(name, deleteFrames);
  12394. }
  12395. }
  12396. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12397. };
  12398. Node.prototype.getAnimationRange = function (name) {
  12399. return this._ranges[name];
  12400. };
  12401. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12402. var range = this.getAnimationRange(name);
  12403. if (!range) {
  12404. return;
  12405. }
  12406. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12407. };
  12408. Node.prototype.serializeAnimationRanges = function () {
  12409. var serializationRanges = [];
  12410. for (var name in this._ranges) {
  12411. var localRange = this._ranges[name];
  12412. if (!localRange) {
  12413. continue;
  12414. }
  12415. var range = {};
  12416. range.name = name;
  12417. range.from = localRange.from;
  12418. range.to = localRange.to;
  12419. serializationRanges.push(range);
  12420. }
  12421. return serializationRanges;
  12422. };
  12423. Node.prototype.dispose = function () {
  12424. this.parent = null;
  12425. // Callback
  12426. this.onDisposeObservable.notifyObservers(this);
  12427. this.onDisposeObservable.clear();
  12428. // Behaviors
  12429. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12430. var behavior = _a[_i];
  12431. behavior.detach();
  12432. }
  12433. this._behaviors = [];
  12434. };
  12435. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12436. if (parsedNode.ranges) {
  12437. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12438. var data = parsedNode.ranges[index];
  12439. node.createAnimationRange(data.name, data.from, data.to);
  12440. }
  12441. }
  12442. };
  12443. __decorate([
  12444. BABYLON.serialize()
  12445. ], Node.prototype, "name", void 0);
  12446. __decorate([
  12447. BABYLON.serialize()
  12448. ], Node.prototype, "id", void 0);
  12449. __decorate([
  12450. BABYLON.serialize()
  12451. ], Node.prototype, "uniqueId", void 0);
  12452. __decorate([
  12453. BABYLON.serialize()
  12454. ], Node.prototype, "state", void 0);
  12455. __decorate([
  12456. BABYLON.serialize()
  12457. ], Node.prototype, "metadata", void 0);
  12458. return Node;
  12459. }());
  12460. BABYLON.Node = Node;
  12461. })(BABYLON || (BABYLON = {}));
  12462. //# sourceMappingURL=babylon.node.js.map
  12463. var BABYLON;
  12464. (function (BABYLON) {
  12465. var BoundingSphere = /** @class */ (function () {
  12466. function BoundingSphere(minimum, maximum) {
  12467. this.minimum = minimum;
  12468. this.maximum = maximum;
  12469. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12470. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12471. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12472. this.radius = distance * 0.5;
  12473. this.centerWorld = BABYLON.Vector3.Zero();
  12474. this._update(BABYLON.Matrix.Identity());
  12475. }
  12476. // Methods
  12477. BoundingSphere.prototype._update = function (world) {
  12478. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12479. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12480. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12481. };
  12482. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12483. for (var i = 0; i < 6; i++) {
  12484. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12485. return false;
  12486. }
  12487. return true;
  12488. };
  12489. BoundingSphere.prototype.intersectsPoint = function (point) {
  12490. var x = this.centerWorld.x - point.x;
  12491. var y = this.centerWorld.y - point.y;
  12492. var z = this.centerWorld.z - point.z;
  12493. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12494. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12495. return false;
  12496. return true;
  12497. };
  12498. // Statics
  12499. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12500. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12501. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12502. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12503. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12504. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12505. return false;
  12506. return true;
  12507. };
  12508. return BoundingSphere;
  12509. }());
  12510. BABYLON.BoundingSphere = BoundingSphere;
  12511. })(BABYLON || (BABYLON = {}));
  12512. //# sourceMappingURL=babylon.boundingSphere.js.map
  12513. var BABYLON;
  12514. (function (BABYLON) {
  12515. var BoundingBox = /** @class */ (function () {
  12516. function BoundingBox(minimum, maximum) {
  12517. this.minimum = minimum;
  12518. this.maximum = maximum;
  12519. this.vectors = new Array();
  12520. this.vectorsWorld = new Array();
  12521. // Bounding vectors
  12522. this.vectors.push(this.minimum.clone());
  12523. this.vectors.push(this.maximum.clone());
  12524. this.vectors.push(this.minimum.clone());
  12525. this.vectors[2].x = this.maximum.x;
  12526. this.vectors.push(this.minimum.clone());
  12527. this.vectors[3].y = this.maximum.y;
  12528. this.vectors.push(this.minimum.clone());
  12529. this.vectors[4].z = this.maximum.z;
  12530. this.vectors.push(this.maximum.clone());
  12531. this.vectors[5].z = this.minimum.z;
  12532. this.vectors.push(this.maximum.clone());
  12533. this.vectors[6].x = this.minimum.x;
  12534. this.vectors.push(this.maximum.clone());
  12535. this.vectors[7].y = this.minimum.y;
  12536. // OBB
  12537. this.center = this.maximum.add(this.minimum).scale(0.5);
  12538. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12539. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12540. // World
  12541. for (var index = 0; index < this.vectors.length; index++) {
  12542. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12543. }
  12544. this.minimumWorld = BABYLON.Vector3.Zero();
  12545. this.maximumWorld = BABYLON.Vector3.Zero();
  12546. this.centerWorld = BABYLON.Vector3.Zero();
  12547. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12548. this._update(BABYLON.Matrix.Identity());
  12549. }
  12550. // Methods
  12551. BoundingBox.prototype.getWorldMatrix = function () {
  12552. return this._worldMatrix;
  12553. };
  12554. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12555. this._worldMatrix.copyFrom(matrix);
  12556. return this;
  12557. };
  12558. BoundingBox.prototype._update = function (world) {
  12559. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12560. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12561. for (var index = 0; index < this.vectors.length; index++) {
  12562. var v = this.vectorsWorld[index];
  12563. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12564. if (v.x < this.minimumWorld.x)
  12565. this.minimumWorld.x = v.x;
  12566. if (v.y < this.minimumWorld.y)
  12567. this.minimumWorld.y = v.y;
  12568. if (v.z < this.minimumWorld.z)
  12569. this.minimumWorld.z = v.z;
  12570. if (v.x > this.maximumWorld.x)
  12571. this.maximumWorld.x = v.x;
  12572. if (v.y > this.maximumWorld.y)
  12573. this.maximumWorld.y = v.y;
  12574. if (v.z > this.maximumWorld.z)
  12575. this.maximumWorld.z = v.z;
  12576. }
  12577. // Extend
  12578. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12579. this.extendSizeWorld.scaleInPlace(0.5);
  12580. // OBB
  12581. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12582. this.centerWorld.scaleInPlace(0.5);
  12583. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12584. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12585. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12586. this._worldMatrix = world;
  12587. };
  12588. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12589. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12590. };
  12591. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12592. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12593. };
  12594. BoundingBox.prototype.intersectsPoint = function (point) {
  12595. var delta = -BABYLON.Epsilon;
  12596. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12597. return false;
  12598. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12599. return false;
  12600. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12601. return false;
  12602. return true;
  12603. };
  12604. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12605. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12606. };
  12607. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12608. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12609. return false;
  12610. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12611. return false;
  12612. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12613. return false;
  12614. return true;
  12615. };
  12616. // Statics
  12617. BoundingBox.Intersects = function (box0, box1) {
  12618. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12619. return false;
  12620. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12621. return false;
  12622. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12623. return false;
  12624. return true;
  12625. };
  12626. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12627. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12628. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12629. return (num <= (sphereRadius * sphereRadius));
  12630. };
  12631. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12632. for (var p = 0; p < 6; p++) {
  12633. for (var i = 0; i < 8; i++) {
  12634. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12635. return false;
  12636. }
  12637. }
  12638. }
  12639. return true;
  12640. };
  12641. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12642. for (var p = 0; p < 6; p++) {
  12643. var inCount = 8;
  12644. for (var i = 0; i < 8; i++) {
  12645. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12646. --inCount;
  12647. }
  12648. else {
  12649. break;
  12650. }
  12651. }
  12652. if (inCount === 0)
  12653. return false;
  12654. }
  12655. return true;
  12656. };
  12657. return BoundingBox;
  12658. }());
  12659. BABYLON.BoundingBox = BoundingBox;
  12660. })(BABYLON || (BABYLON = {}));
  12661. //# sourceMappingURL=babylon.boundingBox.js.map
  12662. var BABYLON;
  12663. (function (BABYLON) {
  12664. var computeBoxExtents = function (axis, box) {
  12665. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12666. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12667. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12668. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12669. var r = r0 + r1 + r2;
  12670. return {
  12671. min: p - r,
  12672. max: p + r
  12673. };
  12674. };
  12675. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12676. var axisOverlap = function (axis, box0, box1) {
  12677. var result0 = computeBoxExtents(axis, box0);
  12678. var result1 = computeBoxExtents(axis, box1);
  12679. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12680. };
  12681. var BoundingInfo = /** @class */ (function () {
  12682. function BoundingInfo(minimum, maximum) {
  12683. this.minimum = minimum;
  12684. this.maximum = maximum;
  12685. this._isLocked = false;
  12686. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12687. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12688. }
  12689. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12690. get: function () {
  12691. return this._isLocked;
  12692. },
  12693. set: function (value) {
  12694. this._isLocked = value;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. // Methods
  12700. BoundingInfo.prototype.update = function (world) {
  12701. if (this._isLocked) {
  12702. return;
  12703. }
  12704. this.boundingBox._update(world);
  12705. this.boundingSphere._update(world);
  12706. };
  12707. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12708. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12709. return false;
  12710. return this.boundingBox.isInFrustum(frustumPlanes);
  12711. };
  12712. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12713. /**
  12714. * Gets the world distance between the min and max points of the bounding box
  12715. */
  12716. get: function () {
  12717. var boundingBox = this.boundingBox;
  12718. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12719. return size.length();
  12720. },
  12721. enumerable: true,
  12722. configurable: true
  12723. });
  12724. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12725. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12726. };
  12727. BoundingInfo.prototype._checkCollision = function (collider) {
  12728. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12729. };
  12730. BoundingInfo.prototype.intersectsPoint = function (point) {
  12731. if (!this.boundingSphere.centerWorld) {
  12732. return false;
  12733. }
  12734. if (!this.boundingSphere.intersectsPoint(point)) {
  12735. return false;
  12736. }
  12737. if (!this.boundingBox.intersectsPoint(point)) {
  12738. return false;
  12739. }
  12740. return true;
  12741. };
  12742. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12743. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12744. return false;
  12745. }
  12746. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12747. return false;
  12748. }
  12749. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12750. return false;
  12751. }
  12752. if (!precise) {
  12753. return true;
  12754. }
  12755. var box0 = this.boundingBox;
  12756. var box1 = boundingInfo.boundingBox;
  12757. if (!axisOverlap(box0.directions[0], box0, box1))
  12758. return false;
  12759. if (!axisOverlap(box0.directions[1], box0, box1))
  12760. return false;
  12761. if (!axisOverlap(box0.directions[2], box0, box1))
  12762. return false;
  12763. if (!axisOverlap(box1.directions[0], box0, box1))
  12764. return false;
  12765. if (!axisOverlap(box1.directions[1], box0, box1))
  12766. return false;
  12767. if (!axisOverlap(box1.directions[2], box0, box1))
  12768. return false;
  12769. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12770. return false;
  12771. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12772. return false;
  12773. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12774. return false;
  12775. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12776. return false;
  12777. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12778. return false;
  12779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12780. return false;
  12781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12782. return false;
  12783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12784. return false;
  12785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12786. return false;
  12787. return true;
  12788. };
  12789. return BoundingInfo;
  12790. }());
  12791. BABYLON.BoundingInfo = BoundingInfo;
  12792. })(BABYLON || (BABYLON = {}));
  12793. //# sourceMappingURL=babylon.boundingInfo.js.map
  12794. var BABYLON;
  12795. (function (BABYLON) {
  12796. var AbstractMesh = /** @class */ (function (_super) {
  12797. __extends(AbstractMesh, _super);
  12798. // Constructor
  12799. function AbstractMesh(name, scene) {
  12800. if (scene === void 0) { scene = null; }
  12801. var _this = _super.call(this, name, scene) || this;
  12802. _this._facetNb = 0; // facet number
  12803. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12804. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12805. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12806. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12807. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12808. _this._subDiv = {
  12809. max: 1,
  12810. X: 1,
  12811. Y: 1,
  12812. Z: 1
  12813. };
  12814. // Normal matrix
  12815. _this._nonUniformScaling = false;
  12816. // Events
  12817. /**
  12818. * An event triggered when this mesh collides with another one
  12819. * @type {BABYLON.Observable}
  12820. */
  12821. _this.onCollideObservable = new BABYLON.Observable();
  12822. /**
  12823. * An event triggered when the collision's position changes
  12824. * @type {BABYLON.Observable}
  12825. */
  12826. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12827. /**
  12828. * An event triggered after the world matrix is updated
  12829. * @type {BABYLON.Observable}
  12830. */
  12831. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12832. /**
  12833. * An event triggered when material is changed
  12834. * @type {BABYLON.Observable}
  12835. */
  12836. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12837. // Properties
  12838. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12839. _this.position = BABYLON.Vector3.Zero();
  12840. /**
  12841. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12842. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12843. * or
  12844. * 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.
  12845. * for more info check WebGl documentations
  12846. */
  12847. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12848. /**
  12849. * 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:
  12850. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12851. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12852. * 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.
  12853. */
  12854. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12855. /**
  12856. * 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.
  12857. * The default value is -1 which means don't break the query and wait till the result.
  12858. */
  12859. _this.occlusionRetryCount = -1;
  12860. _this._occlusionInternalRetryCounter = 0;
  12861. _this._isOccluded = false;
  12862. _this._isOcclusionQueryInProgress = false;
  12863. _this._rotation = BABYLON.Vector3.Zero();
  12864. _this._scaling = BABYLON.Vector3.One();
  12865. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12866. _this.visibility = 1.0;
  12867. _this.alphaIndex = Number.MAX_VALUE;
  12868. _this.infiniteDistance = false;
  12869. _this.isVisible = true;
  12870. _this.isPickable = true;
  12871. _this.showBoundingBox = false;
  12872. _this.showSubMeshesBoundingBox = false;
  12873. _this.isBlocker = false;
  12874. _this.enablePointerMoveEvents = false;
  12875. _this.renderingGroupId = 0;
  12876. _this._receiveShadows = false;
  12877. _this.renderOutline = false;
  12878. _this.outlineColor = BABYLON.Color3.Red();
  12879. _this.outlineWidth = 0.02;
  12880. _this.renderOverlay = false;
  12881. _this.overlayColor = BABYLON.Color3.Red();
  12882. _this.overlayAlpha = 0.5;
  12883. _this._hasVertexAlpha = false;
  12884. _this._useVertexColors = true;
  12885. _this._computeBonesUsingShaders = true;
  12886. _this._numBoneInfluencers = 4;
  12887. _this._applyFog = true;
  12888. _this.scalingDeterminant = 1;
  12889. _this.useOctreeForRenderingSelection = true;
  12890. _this.useOctreeForPicking = true;
  12891. _this.useOctreeForCollisions = true;
  12892. _this._layerMask = 0x0FFFFFFF;
  12893. /**
  12894. * True if the mesh must be rendered in any case.
  12895. */
  12896. _this.alwaysSelectAsActiveMesh = false;
  12897. // Collisions
  12898. _this._checkCollisions = false;
  12899. _this._collisionMask = -1;
  12900. _this._collisionGroup = -1;
  12901. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12902. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12903. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12904. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12905. // Edges
  12906. _this.edgesWidth = 1;
  12907. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12908. // Cache
  12909. _this._localWorld = BABYLON.Matrix.Zero();
  12910. _this._worldMatrix = BABYLON.Matrix.Zero();
  12911. _this._absolutePosition = BABYLON.Vector3.Zero();
  12912. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12913. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12914. _this._isDirty = false;
  12915. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12916. _this._postMultiplyPivotMatrix = false;
  12917. _this._isDisposed = false;
  12918. _this._renderId = 0;
  12919. _this._intersectionsInProgress = new Array();
  12920. _this._isWorldMatrixFrozen = false;
  12921. _this._unIndexed = false;
  12922. _this._lightSources = new Array();
  12923. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12924. if (collidedMesh === void 0) { collidedMesh = null; }
  12925. //TODO move this to the collision coordinator!
  12926. if (_this.getScene().workerCollisions)
  12927. newPosition.multiplyInPlace(_this._collider.radius);
  12928. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12929. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12930. _this.position.addInPlace(_this._diffPositionForCollisions);
  12931. }
  12932. if (collidedMesh) {
  12933. _this.onCollideObservable.notifyObservers(collidedMesh);
  12934. }
  12935. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12936. };
  12937. _this.getScene().addMesh(_this);
  12938. _this._resyncLightSources();
  12939. return _this;
  12940. }
  12941. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12942. get: function () {
  12943. return AbstractMesh._BILLBOARDMODE_NONE;
  12944. },
  12945. enumerable: true,
  12946. configurable: true
  12947. });
  12948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12949. get: function () {
  12950. return AbstractMesh._BILLBOARDMODE_X;
  12951. },
  12952. enumerable: true,
  12953. configurable: true
  12954. });
  12955. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12956. get: function () {
  12957. return AbstractMesh._BILLBOARDMODE_Y;
  12958. },
  12959. enumerable: true,
  12960. configurable: true
  12961. });
  12962. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12963. get: function () {
  12964. return AbstractMesh._BILLBOARDMODE_Z;
  12965. },
  12966. enumerable: true,
  12967. configurable: true
  12968. });
  12969. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12970. get: function () {
  12971. return AbstractMesh._BILLBOARDMODE_ALL;
  12972. },
  12973. enumerable: true,
  12974. configurable: true
  12975. });
  12976. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12977. /**
  12978. * Read-only : the number of facets in the mesh
  12979. */
  12980. get: function () {
  12981. return this._facetNb;
  12982. },
  12983. enumerable: true,
  12984. configurable: true
  12985. });
  12986. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12987. /**
  12988. * The number (integer) of subdivisions per axis in the partioning space
  12989. */
  12990. get: function () {
  12991. return this._partitioningSubdivisions;
  12992. },
  12993. set: function (nb) {
  12994. this._partitioningSubdivisions = nb;
  12995. },
  12996. enumerable: true,
  12997. configurable: true
  12998. });
  12999. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13000. /**
  13001. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13002. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13003. */
  13004. get: function () {
  13005. return this._partitioningBBoxRatio;
  13006. },
  13007. set: function (ratio) {
  13008. this._partitioningBBoxRatio = ratio;
  13009. },
  13010. enumerable: true,
  13011. configurable: true
  13012. });
  13013. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13014. /**
  13015. * Read-only boolean : is the feature facetData enabled ?
  13016. */
  13017. get: function () {
  13018. return this._facetDataEnabled;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13024. get: function () {
  13025. return this._nonUniformScaling;
  13026. },
  13027. set: function (value) {
  13028. if (this._nonUniformScaling === value) {
  13029. return;
  13030. }
  13031. this._nonUniformScaling = true;
  13032. this._markSubMeshesAsMiscDirty();
  13033. },
  13034. enumerable: true,
  13035. configurable: true
  13036. });
  13037. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13038. set: function (callback) {
  13039. if (this._onCollideObserver) {
  13040. this.onCollideObservable.remove(this._onCollideObserver);
  13041. }
  13042. this._onCollideObserver = this.onCollideObservable.add(callback);
  13043. },
  13044. enumerable: true,
  13045. configurable: true
  13046. });
  13047. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13048. set: function (callback) {
  13049. if (this._onCollisionPositionChangeObserver) {
  13050. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13051. }
  13052. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13053. },
  13054. enumerable: true,
  13055. configurable: true
  13056. });
  13057. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13058. /**
  13059. * 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.
  13060. */
  13061. get: function () {
  13062. return this._isOccluded;
  13063. },
  13064. set: function (value) {
  13065. this._isOccluded = value;
  13066. },
  13067. enumerable: true,
  13068. configurable: true
  13069. });
  13070. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13071. /**
  13072. * Flag to check the progress status of the query
  13073. */
  13074. get: function () {
  13075. return this._isOcclusionQueryInProgress;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. Object.defineProperty(AbstractMesh.prototype, "material", {
  13081. get: function () {
  13082. return this._material;
  13083. },
  13084. set: function (value) {
  13085. if (this._material === value) {
  13086. return;
  13087. }
  13088. this._material = value;
  13089. if (this.onMaterialChangedObservable.hasObservers) {
  13090. this.onMaterialChangedObservable.notifyObservers(this);
  13091. }
  13092. if (!this.subMeshes) {
  13093. return;
  13094. }
  13095. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13096. var subMesh = _a[_i];
  13097. subMesh.setEffect(null);
  13098. }
  13099. },
  13100. enumerable: true,
  13101. configurable: true
  13102. });
  13103. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13104. get: function () {
  13105. return this._receiveShadows;
  13106. },
  13107. set: function (value) {
  13108. if (this._receiveShadows === value) {
  13109. return;
  13110. }
  13111. this._receiveShadows = value;
  13112. this._markSubMeshesAsLightDirty();
  13113. },
  13114. enumerable: true,
  13115. configurable: true
  13116. });
  13117. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13118. get: function () {
  13119. return this._hasVertexAlpha;
  13120. },
  13121. set: function (value) {
  13122. if (this._hasVertexAlpha === value) {
  13123. return;
  13124. }
  13125. this._hasVertexAlpha = value;
  13126. this._markSubMeshesAsAttributesDirty();
  13127. },
  13128. enumerable: true,
  13129. configurable: true
  13130. });
  13131. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13132. get: function () {
  13133. return this._useVertexColors;
  13134. },
  13135. set: function (value) {
  13136. if (this._useVertexColors === value) {
  13137. return;
  13138. }
  13139. this._useVertexColors = value;
  13140. this._markSubMeshesAsAttributesDirty();
  13141. },
  13142. enumerable: true,
  13143. configurable: true
  13144. });
  13145. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13146. get: function () {
  13147. return this._computeBonesUsingShaders;
  13148. },
  13149. set: function (value) {
  13150. if (this._computeBonesUsingShaders === value) {
  13151. return;
  13152. }
  13153. this._computeBonesUsingShaders = value;
  13154. this._markSubMeshesAsAttributesDirty();
  13155. },
  13156. enumerable: true,
  13157. configurable: true
  13158. });
  13159. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13160. get: function () {
  13161. return this._numBoneInfluencers;
  13162. },
  13163. set: function (value) {
  13164. if (this._numBoneInfluencers === value) {
  13165. return;
  13166. }
  13167. this._numBoneInfluencers = value;
  13168. this._markSubMeshesAsAttributesDirty();
  13169. },
  13170. enumerable: true,
  13171. configurable: true
  13172. });
  13173. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13174. get: function () {
  13175. return this._applyFog;
  13176. },
  13177. set: function (value) {
  13178. if (this._applyFog === value) {
  13179. return;
  13180. }
  13181. this._applyFog = value;
  13182. this._markSubMeshesAsMiscDirty();
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13188. get: function () {
  13189. return this._layerMask;
  13190. },
  13191. set: function (value) {
  13192. if (value === this._layerMask) {
  13193. return;
  13194. }
  13195. this._layerMask = value;
  13196. this._resyncLightSources();
  13197. },
  13198. enumerable: true,
  13199. configurable: true
  13200. });
  13201. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13202. get: function () {
  13203. return this._collisionMask;
  13204. },
  13205. set: function (mask) {
  13206. this._collisionMask = !isNaN(mask) ? mask : -1;
  13207. },
  13208. enumerable: true,
  13209. configurable: true
  13210. });
  13211. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13212. get: function () {
  13213. return this._collisionGroup;
  13214. },
  13215. set: function (mask) {
  13216. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13217. },
  13218. enumerable: true,
  13219. configurable: true
  13220. });
  13221. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13222. get: function () {
  13223. return null;
  13224. },
  13225. enumerable: true,
  13226. configurable: true
  13227. });
  13228. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13229. get: function () {
  13230. return this._skeleton;
  13231. },
  13232. set: function (value) {
  13233. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13234. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13235. }
  13236. if (value && value.needInitialSkinMatrix) {
  13237. value._registerMeshWithPoseMatrix(this);
  13238. }
  13239. this._skeleton = value;
  13240. if (!this._skeleton) {
  13241. this._bonesTransformMatrices = null;
  13242. }
  13243. this._markSubMeshesAsAttributesDirty();
  13244. },
  13245. enumerable: true,
  13246. configurable: true
  13247. });
  13248. /**
  13249. * Boolean : true if the mesh has been disposed.
  13250. */
  13251. AbstractMesh.prototype.isDisposed = function () {
  13252. return this._isDisposed;
  13253. };
  13254. /**
  13255. * Returns the string "AbstractMesh"
  13256. */
  13257. AbstractMesh.prototype.getClassName = function () {
  13258. return "AbstractMesh";
  13259. };
  13260. /**
  13261. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13262. */
  13263. AbstractMesh.prototype.toString = function (fullDetails) {
  13264. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13265. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13266. if (this._skeleton) {
  13267. ret += ", skeleton: " + this._skeleton.name;
  13268. }
  13269. if (fullDetails) {
  13270. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13271. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13272. }
  13273. return ret;
  13274. };
  13275. AbstractMesh.prototype._rebuild = function () {
  13276. if (this._occlusionQuery) {
  13277. this._occlusionQuery = null;
  13278. }
  13279. if (this._edgesRenderer) {
  13280. this._edgesRenderer._rebuild();
  13281. }
  13282. if (!this.subMeshes) {
  13283. return;
  13284. }
  13285. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13286. var subMesh = _a[_i];
  13287. subMesh._rebuild();
  13288. }
  13289. };
  13290. AbstractMesh.prototype._resyncLightSources = function () {
  13291. this._lightSources.length = 0;
  13292. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13293. var light = _a[_i];
  13294. if (!light.isEnabled()) {
  13295. continue;
  13296. }
  13297. if (light.canAffectMesh(this)) {
  13298. this._lightSources.push(light);
  13299. }
  13300. }
  13301. this._markSubMeshesAsLightDirty();
  13302. };
  13303. AbstractMesh.prototype._resyncLighSource = function (light) {
  13304. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13305. var index = this._lightSources.indexOf(light);
  13306. if (index === -1) {
  13307. if (!isIn) {
  13308. return;
  13309. }
  13310. this._lightSources.push(light);
  13311. }
  13312. else {
  13313. if (isIn) {
  13314. return;
  13315. }
  13316. this._lightSources.splice(index, 1);
  13317. }
  13318. this._markSubMeshesAsLightDirty();
  13319. };
  13320. AbstractMesh.prototype._removeLightSource = function (light) {
  13321. var index = this._lightSources.indexOf(light);
  13322. if (index === -1) {
  13323. return;
  13324. }
  13325. this._lightSources.splice(index, 1);
  13326. };
  13327. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13328. if (!this.subMeshes) {
  13329. return;
  13330. }
  13331. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13332. var subMesh = _a[_i];
  13333. if (subMesh._materialDefines) {
  13334. func(subMesh._materialDefines);
  13335. }
  13336. }
  13337. };
  13338. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13339. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13340. };
  13341. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13342. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13343. };
  13344. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13345. if (!this.subMeshes) {
  13346. return;
  13347. }
  13348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13349. var subMesh = _a[_i];
  13350. var material = subMesh.getMaterial();
  13351. if (material) {
  13352. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13353. }
  13354. }
  13355. };
  13356. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13357. /**
  13358. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13359. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13360. * Default : (0.0, 0.0, 0.0)
  13361. */
  13362. get: function () {
  13363. return this._rotation;
  13364. },
  13365. set: function (newRotation) {
  13366. this._rotation = newRotation;
  13367. },
  13368. enumerable: true,
  13369. configurable: true
  13370. });
  13371. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13372. /**
  13373. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13374. * Default : (1.0, 1.0, 1.0)
  13375. */
  13376. get: function () {
  13377. return this._scaling;
  13378. },
  13379. set: function (newScaling) {
  13380. this._scaling = newScaling;
  13381. if (this.physicsImpostor) {
  13382. this.physicsImpostor.forceUpdate();
  13383. }
  13384. },
  13385. enumerable: true,
  13386. configurable: true
  13387. });
  13388. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13389. /**
  13390. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13391. * It's null by default.
  13392. * 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)
  13393. */
  13394. get: function () {
  13395. return this._rotationQuaternion;
  13396. },
  13397. set: function (quaternion) {
  13398. this._rotationQuaternion = quaternion;
  13399. //reset the rotation vector.
  13400. if (quaternion && this.rotation.length()) {
  13401. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13402. }
  13403. },
  13404. enumerable: true,
  13405. configurable: true
  13406. });
  13407. // Methods
  13408. /**
  13409. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13410. * Returns the AbstractMesh.
  13411. */
  13412. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13413. this._poseMatrix.copyFrom(matrix);
  13414. return this;
  13415. };
  13416. /**
  13417. * Returns the mesh Pose matrix.
  13418. * Returned object : Matrix
  13419. */
  13420. AbstractMesh.prototype.getPoseMatrix = function () {
  13421. return this._poseMatrix;
  13422. };
  13423. /**
  13424. * Disables the mesh edger rendering mode.
  13425. * Returns the AbstractMesh.
  13426. */
  13427. AbstractMesh.prototype.disableEdgesRendering = function () {
  13428. if (this._edgesRenderer) {
  13429. this._edgesRenderer.dispose();
  13430. this._edgesRenderer = null;
  13431. }
  13432. return this;
  13433. };
  13434. /**
  13435. * Enables the edge rendering mode on the mesh.
  13436. * This mode makes the mesh edges visible.
  13437. * Returns the AbstractMesh.
  13438. */
  13439. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13440. if (epsilon === void 0) { epsilon = 0.95; }
  13441. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13442. this.disableEdgesRendering();
  13443. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13444. return this;
  13445. };
  13446. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13447. /**
  13448. * Returns true if the mesh is blocked. Used by the class Mesh.
  13449. * Returns the boolean `false` by default.
  13450. */
  13451. get: function () {
  13452. return false;
  13453. },
  13454. enumerable: true,
  13455. configurable: true
  13456. });
  13457. /**
  13458. * Returns the mesh itself by default, used by the class Mesh.
  13459. * Returned type : AbstractMesh
  13460. */
  13461. AbstractMesh.prototype.getLOD = function (camera) {
  13462. return this;
  13463. };
  13464. /**
  13465. * Returns 0 by default, used by the class Mesh.
  13466. * Returns an integer.
  13467. */
  13468. AbstractMesh.prototype.getTotalVertices = function () {
  13469. return 0;
  13470. };
  13471. /**
  13472. * Returns null by default, used by the class Mesh.
  13473. * Returned type : integer array
  13474. */
  13475. AbstractMesh.prototype.getIndices = function () {
  13476. return null;
  13477. };
  13478. /**
  13479. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13480. * Returned type : float array or Float32Array
  13481. */
  13482. AbstractMesh.prototype.getVerticesData = function (kind) {
  13483. return null;
  13484. };
  13485. /**
  13486. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13487. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13488. * The `data` are either a numeric array either a Float32Array.
  13489. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13490. * 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).
  13491. * Note that a new underlying VertexBuffer object is created each call.
  13492. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13493. *
  13494. * Possible `kind` values :
  13495. * - BABYLON.VertexBuffer.PositionKind
  13496. * - BABYLON.VertexBuffer.UVKind
  13497. * - BABYLON.VertexBuffer.UV2Kind
  13498. * - BABYLON.VertexBuffer.UV3Kind
  13499. * - BABYLON.VertexBuffer.UV4Kind
  13500. * - BABYLON.VertexBuffer.UV5Kind
  13501. * - BABYLON.VertexBuffer.UV6Kind
  13502. * - BABYLON.VertexBuffer.ColorKind
  13503. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13504. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13505. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13506. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13507. *
  13508. * Returns the Mesh.
  13509. */
  13510. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13511. return this;
  13512. };
  13513. /**
  13514. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13515. * If the mesh has no geometry, it is simply returned as it is.
  13516. * The `data` are either a numeric array either a Float32Array.
  13517. * No new underlying VertexBuffer object is created.
  13518. * 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.
  13519. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13520. *
  13521. * Possible `kind` values :
  13522. * - BABYLON.VertexBuffer.PositionKind
  13523. * - BABYLON.VertexBuffer.UVKind
  13524. * - BABYLON.VertexBuffer.UV2Kind
  13525. * - BABYLON.VertexBuffer.UV3Kind
  13526. * - BABYLON.VertexBuffer.UV4Kind
  13527. * - BABYLON.VertexBuffer.UV5Kind
  13528. * - BABYLON.VertexBuffer.UV6Kind
  13529. * - BABYLON.VertexBuffer.ColorKind
  13530. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13531. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13532. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13533. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13534. *
  13535. * Returns the Mesh.
  13536. */
  13537. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13538. return this;
  13539. };
  13540. /**
  13541. * Sets the mesh indices.
  13542. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13543. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13544. * This method creates a new index buffer each call.
  13545. * Returns the Mesh.
  13546. */
  13547. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13548. return this;
  13549. };
  13550. /** Returns false by default, used by the class Mesh.
  13551. * Returns a boolean
  13552. */
  13553. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13554. return false;
  13555. };
  13556. /**
  13557. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13558. * Returns a BoundingInfo
  13559. */
  13560. AbstractMesh.prototype.getBoundingInfo = function () {
  13561. if (this._masterMesh) {
  13562. return this._masterMesh.getBoundingInfo();
  13563. }
  13564. if (!this._boundingInfo) {
  13565. this._updateBoundingInfo();
  13566. }
  13567. return this._boundingInfo;
  13568. };
  13569. /**
  13570. * Sets a mesh new object BoundingInfo.
  13571. * Returns the AbstractMesh.
  13572. */
  13573. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13574. this._boundingInfo = boundingInfo;
  13575. return this;
  13576. };
  13577. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13578. get: function () {
  13579. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13580. },
  13581. enumerable: true,
  13582. configurable: true
  13583. });
  13584. AbstractMesh.prototype._preActivate = function () {
  13585. };
  13586. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13587. };
  13588. AbstractMesh.prototype._activate = function (renderId) {
  13589. this._renderId = renderId;
  13590. };
  13591. /**
  13592. * Returns the last update of the World matrix
  13593. * Returns a Matrix.
  13594. */
  13595. AbstractMesh.prototype.getWorldMatrix = function () {
  13596. if (this._masterMesh) {
  13597. return this._masterMesh.getWorldMatrix();
  13598. }
  13599. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13600. this.computeWorldMatrix();
  13601. }
  13602. return this._worldMatrix;
  13603. };
  13604. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13605. /**
  13606. * Returns directly the last state of the mesh World matrix.
  13607. * A Matrix is returned.
  13608. */
  13609. get: function () {
  13610. return this._worldMatrix;
  13611. },
  13612. enumerable: true,
  13613. configurable: true
  13614. });
  13615. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13616. /**
  13617. * Returns the current mesh absolute position.
  13618. * Retuns a Vector3.
  13619. */
  13620. get: function () {
  13621. return this._absolutePosition;
  13622. },
  13623. enumerable: true,
  13624. configurable: true
  13625. });
  13626. /**
  13627. * Prevents the World matrix to be computed any longer.
  13628. * Returns the AbstractMesh.
  13629. */
  13630. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13631. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13632. this.computeWorldMatrix(true);
  13633. this._isWorldMatrixFrozen = true;
  13634. return this;
  13635. };
  13636. /**
  13637. * Allows back the World matrix computation.
  13638. * Returns the AbstractMesh.
  13639. */
  13640. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13641. this._isWorldMatrixFrozen = false;
  13642. this.computeWorldMatrix(true);
  13643. return this;
  13644. };
  13645. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13646. /**
  13647. * True if the World matrix has been frozen.
  13648. * Returns a boolean.
  13649. */
  13650. get: function () {
  13651. return this._isWorldMatrixFrozen;
  13652. },
  13653. enumerable: true,
  13654. configurable: true
  13655. });
  13656. /**
  13657. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13658. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13659. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13660. * The passed axis is also normalized.
  13661. * Returns the AbstractMesh.
  13662. */
  13663. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13664. axis.normalize();
  13665. if (!this.rotationQuaternion) {
  13666. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13667. this.rotation = BABYLON.Vector3.Zero();
  13668. }
  13669. var rotationQuaternion;
  13670. if (!space || space === BABYLON.Space.LOCAL) {
  13671. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13672. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13673. }
  13674. else {
  13675. if (this.parent) {
  13676. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13677. invertParentWorldMatrix.invert();
  13678. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13679. }
  13680. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13681. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13682. }
  13683. return this;
  13684. };
  13685. /**
  13686. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13687. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13688. * The passed axis is also normalized.
  13689. * Returns the AbstractMesh.
  13690. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13691. */
  13692. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13693. axis.normalize();
  13694. if (!this.rotationQuaternion) {
  13695. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13696. this.rotation.copyFromFloats(0, 0, 0);
  13697. }
  13698. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13699. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13700. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13701. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13702. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13703. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13704. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13705. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13706. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13707. return this;
  13708. };
  13709. /**
  13710. * Translates the mesh along the axis vector for the passed distance in the given space.
  13711. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13712. * Returns the AbstractMesh.
  13713. */
  13714. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13715. var displacementVector = axis.scale(distance);
  13716. if (!space || space === BABYLON.Space.LOCAL) {
  13717. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13718. this.setPositionWithLocalVector(tempV3);
  13719. }
  13720. else {
  13721. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13722. }
  13723. return this;
  13724. };
  13725. /**
  13726. * Adds a rotation step to the mesh current rotation.
  13727. * x, y, z are Euler angles expressed in radians.
  13728. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13729. * This means this rotation is made in the mesh local space only.
  13730. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13731. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13732. * ```javascript
  13733. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13734. * ```
  13735. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13736. * 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.
  13737. * Returns the AbstractMesh.
  13738. */
  13739. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13740. var rotationQuaternion;
  13741. if (this.rotationQuaternion) {
  13742. rotationQuaternion = this.rotationQuaternion;
  13743. }
  13744. else {
  13745. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13746. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13747. }
  13748. var accumulation = BABYLON.Tmp.Quaternion[0];
  13749. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13750. rotationQuaternion.multiplyInPlace(accumulation);
  13751. if (!this.rotationQuaternion) {
  13752. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13753. }
  13754. return this;
  13755. };
  13756. /**
  13757. * Retuns the mesh absolute position in the World.
  13758. * Returns a Vector3.
  13759. */
  13760. AbstractMesh.prototype.getAbsolutePosition = function () {
  13761. this.computeWorldMatrix();
  13762. return this._absolutePosition;
  13763. };
  13764. /**
  13765. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13766. * Returns the AbstractMesh.
  13767. */
  13768. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13769. if (!absolutePosition) {
  13770. return this;
  13771. }
  13772. var absolutePositionX;
  13773. var absolutePositionY;
  13774. var absolutePositionZ;
  13775. if (absolutePosition.x === undefined) {
  13776. if (arguments.length < 3) {
  13777. return this;
  13778. }
  13779. absolutePositionX = arguments[0];
  13780. absolutePositionY = arguments[1];
  13781. absolutePositionZ = arguments[2];
  13782. }
  13783. else {
  13784. absolutePositionX = absolutePosition.x;
  13785. absolutePositionY = absolutePosition.y;
  13786. absolutePositionZ = absolutePosition.z;
  13787. }
  13788. if (this.parent) {
  13789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13790. invertParentWorldMatrix.invert();
  13791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13793. }
  13794. else {
  13795. this.position.x = absolutePositionX;
  13796. this.position.y = absolutePositionY;
  13797. this.position.z = absolutePositionZ;
  13798. }
  13799. return this;
  13800. };
  13801. // ================================== Point of View Movement =================================
  13802. /**
  13803. * Perform relative position change from the point of view of behind the front of the mesh.
  13804. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13805. * Supports definition of mesh facing forward or backward.
  13806. * @param {number} amountRight
  13807. * @param {number} amountUp
  13808. * @param {number} amountForward
  13809. *
  13810. * Returns the AbstractMesh.
  13811. */
  13812. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13813. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13814. return this;
  13815. };
  13816. /**
  13817. * Calculate relative position change from the point of view of behind the front of the mesh.
  13818. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13819. * Supports definition of mesh facing forward or backward.
  13820. * @param {number} amountRight
  13821. * @param {number} amountUp
  13822. * @param {number} amountForward
  13823. *
  13824. * Returns a new Vector3.
  13825. */
  13826. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13827. var rotMatrix = new BABYLON.Matrix();
  13828. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13829. rotQuaternion.toRotationMatrix(rotMatrix);
  13830. var translationDelta = BABYLON.Vector3.Zero();
  13831. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13832. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13833. return translationDelta;
  13834. };
  13835. // ================================== Point of View Rotation =================================
  13836. /**
  13837. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13838. * Supports definition of mesh facing forward or backward.
  13839. * @param {number} flipBack
  13840. * @param {number} twirlClockwise
  13841. * @param {number} tiltRight
  13842. *
  13843. * Returns the AbstractMesh.
  13844. */
  13845. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13846. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13847. return this;
  13848. };
  13849. /**
  13850. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13851. * Supports definition of mesh facing forward or backward.
  13852. * @param {number} flipBack
  13853. * @param {number} twirlClockwise
  13854. * @param {number} tiltRight
  13855. *
  13856. * Returns a new Vector3.
  13857. */
  13858. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13859. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13860. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13861. };
  13862. /**
  13863. * Sets a new pivot matrix to the mesh.
  13864. * Returns the AbstractMesh.
  13865. */
  13866. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13867. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13868. this._pivotMatrix = matrix.clone();
  13869. this._cache.pivotMatrixUpdated = true;
  13870. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13871. if (this._postMultiplyPivotMatrix) {
  13872. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13873. }
  13874. return this;
  13875. };
  13876. /**
  13877. * Returns the mesh pivot matrix.
  13878. * Default : Identity.
  13879. * A Matrix is returned.
  13880. */
  13881. AbstractMesh.prototype.getPivotMatrix = function () {
  13882. return this._pivotMatrix;
  13883. };
  13884. AbstractMesh.prototype._isSynchronized = function () {
  13885. if (this._isDirty) {
  13886. return false;
  13887. }
  13888. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13889. return false;
  13890. if (this._cache.pivotMatrixUpdated) {
  13891. return false;
  13892. }
  13893. if (this.infiniteDistance) {
  13894. return false;
  13895. }
  13896. if (!this._cache.position.equals(this.position))
  13897. return false;
  13898. if (this.rotationQuaternion) {
  13899. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13900. return false;
  13901. }
  13902. if (!this._cache.rotation.equals(this.rotation))
  13903. return false;
  13904. if (!this._cache.scaling.equals(this.scaling))
  13905. return false;
  13906. return true;
  13907. };
  13908. AbstractMesh.prototype._initCache = function () {
  13909. _super.prototype._initCache.call(this);
  13910. this._cache.localMatrixUpdated = false;
  13911. this._cache.position = BABYLON.Vector3.Zero();
  13912. this._cache.scaling = BABYLON.Vector3.Zero();
  13913. this._cache.rotation = BABYLON.Vector3.Zero();
  13914. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13915. this._cache.billboardMode = -1;
  13916. };
  13917. AbstractMesh.prototype.markAsDirty = function (property) {
  13918. if (property === "rotation") {
  13919. this.rotationQuaternion = null;
  13920. }
  13921. this._currentRenderId = Number.MAX_VALUE;
  13922. this._isDirty = true;
  13923. return this;
  13924. };
  13925. /**
  13926. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13927. */
  13928. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13929. this.computeWorldMatrix(true);
  13930. var min;
  13931. var max;
  13932. var boundingInfo = this.getBoundingInfo();
  13933. if (!this.subMeshes || !boundingInfo) {
  13934. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13935. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13936. }
  13937. else {
  13938. min = boundingInfo.boundingBox.minimumWorld;
  13939. max = boundingInfo.boundingBox.maximumWorld;
  13940. }
  13941. var descendants = this.getDescendants(false);
  13942. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13943. var descendant = descendants_1[_i];
  13944. var childMesh = descendant;
  13945. childMesh.computeWorldMatrix(true);
  13946. var childBoundingInfo = childMesh.getBoundingInfo();
  13947. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  13948. continue;
  13949. }
  13950. var boundingBox = childBoundingInfo.boundingBox;
  13951. var minBox = boundingBox.minimumWorld;
  13952. var maxBox = boundingBox.maximumWorld;
  13953. BABYLON.Tools.CheckExtends(minBox, min, max);
  13954. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13955. }
  13956. return {
  13957. min: min,
  13958. max: max
  13959. };
  13960. };
  13961. /**
  13962. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13963. * Returns the AbstractMesh.
  13964. */
  13965. AbstractMesh.prototype._updateBoundingInfo = function () {
  13966. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13967. this._boundingInfo.update(this.worldMatrixFromCache);
  13968. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13969. return this;
  13970. };
  13971. /**
  13972. * Update a mesh's children BoundingInfo objects only.
  13973. * Returns the AbstractMesh.
  13974. */
  13975. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13976. if (!this.subMeshes) {
  13977. return this;
  13978. }
  13979. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13980. var subMesh = this.subMeshes[subIndex];
  13981. if (!subMesh.IsGlobal) {
  13982. subMesh.updateBoundingInfo(matrix);
  13983. }
  13984. }
  13985. return this;
  13986. };
  13987. /**
  13988. * Computes the mesh World matrix and returns it.
  13989. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13990. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13991. * If the parameter `force`is set to `true`, the actual computation is done.
  13992. * Returns the mesh World Matrix.
  13993. */
  13994. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13995. if (this._isWorldMatrixFrozen) {
  13996. return this._worldMatrix;
  13997. }
  13998. if (!force && this.isSynchronized(true)) {
  13999. this._currentRenderId = this.getScene().getRenderId();
  14000. return this._worldMatrix;
  14001. }
  14002. this._cache.position.copyFrom(this.position);
  14003. this._cache.scaling.copyFrom(this.scaling);
  14004. this._cache.pivotMatrixUpdated = false;
  14005. this._cache.billboardMode = this.billboardMode;
  14006. this._currentRenderId = this.getScene().getRenderId();
  14007. this._isDirty = false;
  14008. // Scaling
  14009. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14010. // Rotation
  14011. //rotate, if quaternion is set and rotation was used
  14012. if (this.rotationQuaternion) {
  14013. var len = this.rotation.length();
  14014. if (len) {
  14015. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14016. this.rotation.copyFromFloats(0, 0, 0);
  14017. }
  14018. }
  14019. if (this.rotationQuaternion) {
  14020. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14021. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14022. }
  14023. else {
  14024. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14025. this._cache.rotation.copyFrom(this.rotation);
  14026. }
  14027. // Translation
  14028. var camera = this.getScene().activeCamera;
  14029. if (this.infiniteDistance && !this.parent && camera) {
  14030. var cameraWorldMatrix = camera.getWorldMatrix();
  14031. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14032. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14033. }
  14034. else {
  14035. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14036. }
  14037. // Composing transformations
  14038. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14039. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14040. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14041. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14042. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14043. // Need to decompose each rotation here
  14044. var currentPosition = BABYLON.Tmp.Vector3[3];
  14045. if (this.parent && this.parent.getWorldMatrix) {
  14046. if (this._meshToBoneReferal) {
  14047. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14048. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14049. }
  14050. else {
  14051. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14052. }
  14053. }
  14054. else {
  14055. currentPosition.copyFrom(this.position);
  14056. }
  14057. currentPosition.subtractInPlace(camera.globalPosition);
  14058. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14059. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14060. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14061. }
  14062. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14063. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14064. }
  14065. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14066. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14067. }
  14068. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14069. }
  14070. else {
  14071. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14072. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14073. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14074. }
  14075. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14076. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14077. }
  14078. // Local world
  14079. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14080. // Parent
  14081. if (this.parent && this.parent.getWorldMatrix) {
  14082. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14083. if (this._meshToBoneReferal) {
  14084. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14085. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14086. }
  14087. else {
  14088. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14089. }
  14090. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14091. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14092. this._worldMatrix.copyFrom(this._localWorld);
  14093. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14094. }
  14095. else {
  14096. if (this._meshToBoneReferal) {
  14097. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14098. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14099. }
  14100. else {
  14101. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14102. }
  14103. }
  14104. this._markSyncedWithParent();
  14105. }
  14106. else {
  14107. this._worldMatrix.copyFrom(this._localWorld);
  14108. }
  14109. // Post multiply inverse of pivotMatrix
  14110. if (this._postMultiplyPivotMatrix) {
  14111. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14112. }
  14113. // Normal matrix
  14114. if (this.scaling.isNonUniform) {
  14115. this.nonUniformScaling = true;
  14116. }
  14117. else if (this.parent && this.parent._nonUniformScaling) {
  14118. this.nonUniformScaling = this.parent._nonUniformScaling;
  14119. }
  14120. else {
  14121. this.nonUniformScaling = false;
  14122. }
  14123. // Bounding info
  14124. this._updateBoundingInfo();
  14125. // Absolute position
  14126. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14127. // Callbacks
  14128. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14129. if (!this._poseMatrix) {
  14130. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14131. }
  14132. return this._worldMatrix;
  14133. };
  14134. /**
  14135. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14136. * @param func: callback function to add
  14137. *
  14138. * Returns the AbstractMesh.
  14139. */
  14140. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14141. this.onAfterWorldMatrixUpdateObservable.add(func);
  14142. return this;
  14143. };
  14144. /**
  14145. * Removes a registered callback function.
  14146. * Returns the AbstractMesh.
  14147. */
  14148. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14149. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14150. return this;
  14151. };
  14152. /**
  14153. * Sets the mesh position in its local space.
  14154. * Returns the AbstractMesh.
  14155. */
  14156. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14157. this.computeWorldMatrix();
  14158. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14159. return this;
  14160. };
  14161. /**
  14162. * Returns the mesh position in the local space from the current World matrix values.
  14163. * Returns a new Vector3.
  14164. */
  14165. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14166. this.computeWorldMatrix();
  14167. var invLocalWorldMatrix = this._localWorld.clone();
  14168. invLocalWorldMatrix.invert();
  14169. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14170. };
  14171. /**
  14172. * Translates the mesh along the passed Vector3 in its local space.
  14173. * Returns the AbstractMesh.
  14174. */
  14175. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14176. this.computeWorldMatrix(true);
  14177. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14178. return this;
  14179. };
  14180. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14181. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14182. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14183. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14184. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14185. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14186. /// <returns>Mesh oriented towards targetMesh</returns>
  14187. if (yawCor === void 0) { yawCor = 0; }
  14188. if (pitchCor === void 0) { pitchCor = 0; }
  14189. if (rollCor === void 0) { rollCor = 0; }
  14190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14191. var dv = AbstractMesh._lookAtVectorCache;
  14192. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14193. targetPoint.subtractToRef(pos, dv);
  14194. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14195. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14196. var pitch = Math.atan2(dv.y, len);
  14197. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14198. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14199. return this;
  14200. };
  14201. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14202. this._meshToBoneReferal = affectedMesh;
  14203. this.parent = bone;
  14204. if (bone.getWorldMatrix().determinant() < 0) {
  14205. this.scalingDeterminant *= -1;
  14206. }
  14207. return this;
  14208. };
  14209. AbstractMesh.prototype.detachFromBone = function () {
  14210. if (!this.parent) {
  14211. return this;
  14212. }
  14213. if (this.parent.getWorldMatrix().determinant() < 0) {
  14214. this.scalingDeterminant *= -1;
  14215. }
  14216. this._meshToBoneReferal = null;
  14217. this.parent = null;
  14218. return this;
  14219. };
  14220. /**
  14221. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14222. * A mesh is in the frustum if its bounding box intersects the frustum.
  14223. * Boolean returned.
  14224. */
  14225. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14226. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14227. };
  14228. /**
  14229. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14230. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14231. * Boolean returned.
  14232. */
  14233. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14234. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14235. ;
  14236. };
  14237. /**
  14238. * True if the mesh intersects another mesh or a SolidParticle object.
  14239. * 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)
  14240. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14241. * Returns a boolean.
  14242. */
  14243. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14244. if (precise === void 0) { precise = false; }
  14245. if (!this._boundingInfo || !mesh._boundingInfo) {
  14246. return false;
  14247. }
  14248. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14249. return true;
  14250. }
  14251. if (includeDescendants) {
  14252. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14253. var child = _a[_i];
  14254. if (child.intersectsMesh(mesh, precise, true)) {
  14255. return true;
  14256. }
  14257. }
  14258. }
  14259. return false;
  14260. };
  14261. /**
  14262. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14263. * Returns a boolean.
  14264. */
  14265. AbstractMesh.prototype.intersectsPoint = function (point) {
  14266. if (!this._boundingInfo) {
  14267. return false;
  14268. }
  14269. return this._boundingInfo.intersectsPoint(point);
  14270. };
  14271. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14272. return this.physicsImpostor;
  14273. };
  14274. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14275. if (camera === void 0) { camera = null; }
  14276. if (!camera) {
  14277. camera = this.getScene().activeCamera;
  14278. }
  14279. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14280. };
  14281. /**
  14282. * Returns the distance from the mesh to the active camera.
  14283. * Returns a float.
  14284. */
  14285. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14286. if (camera === void 0) { camera = null; }
  14287. if (!camera) {
  14288. camera = this.getScene().activeCamera;
  14289. }
  14290. return this.absolutePosition.subtract(camera.position).length();
  14291. };
  14292. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14293. if (!this.physicsImpostor) {
  14294. return this;
  14295. }
  14296. this.physicsImpostor.applyImpulse(force, contactPoint);
  14297. return this;
  14298. };
  14299. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14300. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14301. return this;
  14302. }
  14303. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14304. mainPivot: pivot1,
  14305. connectedPivot: pivot2,
  14306. nativeParams: options
  14307. });
  14308. return this;
  14309. };
  14310. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14311. // Collisions
  14312. /**
  14313. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14314. * Default `false`.
  14315. */
  14316. get: function () {
  14317. return this._checkCollisions;
  14318. },
  14319. set: function (collisionEnabled) {
  14320. this._checkCollisions = collisionEnabled;
  14321. if (this.getScene().workerCollisions) {
  14322. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14323. }
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14329. var globalPosition = this.getAbsolutePosition();
  14330. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14331. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14332. if (!this._collider) {
  14333. this._collider = new BABYLON.Collider();
  14334. }
  14335. this._collider.radius = this.ellipsoid;
  14336. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14337. return this;
  14338. };
  14339. // Submeshes octree
  14340. /**
  14341. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14342. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14343. * Returns an Octree of submeshes.
  14344. */
  14345. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14346. if (maxCapacity === void 0) { maxCapacity = 64; }
  14347. if (maxDepth === void 0) { maxDepth = 2; }
  14348. if (!this._submeshesOctree) {
  14349. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14350. }
  14351. this.computeWorldMatrix(true);
  14352. var boundingInfo = this.getBoundingInfo();
  14353. // Update octree
  14354. if (boundingInfo) {
  14355. var bbox = boundingInfo.boundingBox;
  14356. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14357. }
  14358. return this._submeshesOctree;
  14359. };
  14360. // Collisions
  14361. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14362. this._generatePointsArray();
  14363. if (!this._positions) {
  14364. return this;
  14365. }
  14366. // Transformation
  14367. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14368. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14369. subMesh._lastColliderWorldVertices = [];
  14370. subMesh._trianglePlanes = [];
  14371. var start = subMesh.verticesStart;
  14372. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14373. for (var i = start; i < end; i++) {
  14374. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14375. }
  14376. }
  14377. // Collide
  14378. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14379. if (collider.collisionFound) {
  14380. collider.collidedMesh = this;
  14381. }
  14382. return this;
  14383. };
  14384. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14385. var subMeshes;
  14386. var len;
  14387. // Octrees
  14388. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14389. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14390. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14391. len = intersections.length;
  14392. subMeshes = intersections.data;
  14393. }
  14394. else {
  14395. subMeshes = this.subMeshes;
  14396. len = subMeshes.length;
  14397. }
  14398. for (var index = 0; index < len; index++) {
  14399. var subMesh = subMeshes[index];
  14400. // Bounding test
  14401. if (len > 1 && !subMesh._checkCollision(collider))
  14402. continue;
  14403. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14404. }
  14405. return this;
  14406. };
  14407. AbstractMesh.prototype._checkCollision = function (collider) {
  14408. // Bounding box test
  14409. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14410. return this;
  14411. // Transformation matrix
  14412. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14413. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14414. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14415. return this;
  14416. };
  14417. // Picking
  14418. AbstractMesh.prototype._generatePointsArray = function () {
  14419. return false;
  14420. };
  14421. /**
  14422. * Checks if the passed Ray intersects with the mesh.
  14423. * Returns an object PickingInfo.
  14424. */
  14425. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14426. var pickingInfo = new BABYLON.PickingInfo();
  14427. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14428. return pickingInfo;
  14429. }
  14430. if (!this._generatePointsArray()) {
  14431. return pickingInfo;
  14432. }
  14433. var intersectInfo = null;
  14434. // Octrees
  14435. var subMeshes;
  14436. var len;
  14437. if (this._submeshesOctree && this.useOctreeForPicking) {
  14438. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14439. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14440. len = intersections.length;
  14441. subMeshes = intersections.data;
  14442. }
  14443. else {
  14444. subMeshes = this.subMeshes;
  14445. len = subMeshes.length;
  14446. }
  14447. for (var index = 0; index < len; index++) {
  14448. var subMesh = subMeshes[index];
  14449. // Bounding test
  14450. if (len > 1 && !subMesh.canIntersects(ray))
  14451. continue;
  14452. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14453. if (currentIntersectInfo) {
  14454. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14455. intersectInfo = currentIntersectInfo;
  14456. intersectInfo.subMeshId = index;
  14457. if (fastCheck) {
  14458. break;
  14459. }
  14460. }
  14461. }
  14462. }
  14463. if (intersectInfo) {
  14464. // Get picked point
  14465. var world = this.getWorldMatrix();
  14466. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14467. var direction = ray.direction.clone();
  14468. direction = direction.scale(intersectInfo.distance);
  14469. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14470. var pickedPoint = worldOrigin.add(worldDirection);
  14471. // Return result
  14472. pickingInfo.hit = true;
  14473. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14474. pickingInfo.pickedPoint = pickedPoint;
  14475. pickingInfo.pickedMesh = this;
  14476. pickingInfo.bu = intersectInfo.bu || 0;
  14477. pickingInfo.bv = intersectInfo.bv || 0;
  14478. pickingInfo.faceId = intersectInfo.faceId;
  14479. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14480. return pickingInfo;
  14481. }
  14482. return pickingInfo;
  14483. };
  14484. /**
  14485. * Clones the mesh, used by the class Mesh.
  14486. * Just returns `null` for an AbstractMesh.
  14487. */
  14488. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14489. return null;
  14490. };
  14491. /**
  14492. * Disposes all the mesh submeshes.
  14493. * Returns the AbstractMesh.
  14494. */
  14495. AbstractMesh.prototype.releaseSubMeshes = function () {
  14496. if (this.subMeshes) {
  14497. while (this.subMeshes.length) {
  14498. this.subMeshes[0].dispose();
  14499. }
  14500. }
  14501. else {
  14502. this.subMeshes = new Array();
  14503. }
  14504. return this;
  14505. };
  14506. /**
  14507. * Disposes the AbstractMesh.
  14508. * Some internal references are kept for further use.
  14509. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14510. * Returns nothing.
  14511. */
  14512. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14513. var _this = this;
  14514. var index;
  14515. // Action manager
  14516. if (this.actionManager) {
  14517. this.actionManager.dispose();
  14518. this.actionManager = null;
  14519. }
  14520. // Skeleton
  14521. this.skeleton = null;
  14522. // Animations
  14523. this.getScene().stopAnimation(this);
  14524. // Physics
  14525. if (this.physicsImpostor) {
  14526. this.physicsImpostor.dispose();
  14527. }
  14528. // Intersections in progress
  14529. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14530. var other = this._intersectionsInProgress[index];
  14531. var pos = other._intersectionsInProgress.indexOf(this);
  14532. other._intersectionsInProgress.splice(pos, 1);
  14533. }
  14534. this._intersectionsInProgress = [];
  14535. // Lights
  14536. var lights = this.getScene().lights;
  14537. lights.forEach(function (light) {
  14538. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14539. if (meshIndex !== -1) {
  14540. light.includedOnlyMeshes.splice(meshIndex, 1);
  14541. }
  14542. meshIndex = light.excludedMeshes.indexOf(_this);
  14543. if (meshIndex !== -1) {
  14544. light.excludedMeshes.splice(meshIndex, 1);
  14545. }
  14546. // Shadow generators
  14547. var generator = light.getShadowGenerator();
  14548. if (generator) {
  14549. var shadowMap = generator.getShadowMap();
  14550. if (shadowMap && shadowMap.renderList) {
  14551. meshIndex = shadowMap.renderList.indexOf(_this);
  14552. if (meshIndex !== -1) {
  14553. shadowMap.renderList.splice(meshIndex, 1);
  14554. }
  14555. }
  14556. }
  14557. });
  14558. // Edges
  14559. if (this._edgesRenderer) {
  14560. this._edgesRenderer.dispose();
  14561. this._edgesRenderer = null;
  14562. }
  14563. // SubMeshes
  14564. if (this.getClassName() !== "InstancedMesh") {
  14565. this.releaseSubMeshes();
  14566. }
  14567. // Octree
  14568. var sceneOctree = this.getScene().selectionOctree;
  14569. if (sceneOctree) {
  14570. var index = sceneOctree.dynamicContent.indexOf(this);
  14571. if (index !== -1) {
  14572. sceneOctree.dynamicContent.splice(index, 1);
  14573. }
  14574. }
  14575. // Query
  14576. var engine = this.getScene().getEngine();
  14577. if (this._occlusionQuery) {
  14578. this._isOcclusionQueryInProgress = false;
  14579. engine.deleteQuery(this._occlusionQuery);
  14580. this._occlusionQuery = null;
  14581. }
  14582. // Engine
  14583. engine.wipeCaches();
  14584. // Remove from scene
  14585. this.getScene().removeMesh(this);
  14586. if (!doNotRecurse) {
  14587. // Particles
  14588. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14589. if (this.getScene().particleSystems[index].emitter === this) {
  14590. this.getScene().particleSystems[index].dispose();
  14591. index--;
  14592. }
  14593. }
  14594. // Children
  14595. var objects = this.getDescendants(true);
  14596. for (index = 0; index < objects.length; index++) {
  14597. objects[index].dispose();
  14598. }
  14599. }
  14600. else {
  14601. var childMeshes = this.getChildMeshes(true);
  14602. for (index = 0; index < childMeshes.length; index++) {
  14603. var child = childMeshes[index];
  14604. child.parent = null;
  14605. child.computeWorldMatrix(true);
  14606. }
  14607. }
  14608. // facet data
  14609. if (this._facetDataEnabled) {
  14610. this.disableFacetData();
  14611. }
  14612. this.onAfterWorldMatrixUpdateObservable.clear();
  14613. this.onCollideObservable.clear();
  14614. this.onCollisionPositionChangeObservable.clear();
  14615. this._isDisposed = true;
  14616. _super.prototype.dispose.call(this);
  14617. };
  14618. /**
  14619. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14620. * This Vector3 is expressed in the World space.
  14621. */
  14622. AbstractMesh.prototype.getDirection = function (localAxis) {
  14623. var result = BABYLON.Vector3.Zero();
  14624. this.getDirectionToRef(localAxis, result);
  14625. return result;
  14626. };
  14627. /**
  14628. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14629. * localAxis is expressed in the mesh local space.
  14630. * result is computed in the Wordl space from the mesh World matrix.
  14631. * Returns the AbstractMesh.
  14632. */
  14633. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14634. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14635. return this;
  14636. };
  14637. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14639. if (this.getScene().getRenderId() == 0) {
  14640. this.computeWorldMatrix(true);
  14641. }
  14642. var wm = this.getWorldMatrix();
  14643. if (space == BABYLON.Space.WORLD) {
  14644. var tmat = BABYLON.Tmp.Matrix[0];
  14645. wm.invertToRef(tmat);
  14646. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14647. }
  14648. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14649. this._pivotMatrix.m[12] = -point.x;
  14650. this._pivotMatrix.m[13] = -point.y;
  14651. this._pivotMatrix.m[14] = -point.z;
  14652. this._cache.pivotMatrixUpdated = true;
  14653. return this;
  14654. };
  14655. /**
  14656. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14657. */
  14658. AbstractMesh.prototype.getPivotPoint = function () {
  14659. var point = BABYLON.Vector3.Zero();
  14660. this.getPivotPointToRef(point);
  14661. return point;
  14662. };
  14663. /**
  14664. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14665. * Returns the AbstractMesh.
  14666. */
  14667. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14668. result.x = -this._pivotMatrix.m[12];
  14669. result.y = -this._pivotMatrix.m[13];
  14670. result.z = -this._pivotMatrix.m[14];
  14671. return this;
  14672. };
  14673. /**
  14674. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14675. */
  14676. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14677. var point = BABYLON.Vector3.Zero();
  14678. this.getAbsolutePivotPointToRef(point);
  14679. return point;
  14680. };
  14681. /**
  14682. * Defines the passed mesh as the parent of the current mesh.
  14683. * Returns the AbstractMesh.
  14684. */
  14685. AbstractMesh.prototype.setParent = function (mesh) {
  14686. var parent = mesh;
  14687. if (mesh == null) {
  14688. var rotation = BABYLON.Tmp.Quaternion[0];
  14689. var position = BABYLON.Tmp.Vector3[0];
  14690. var scale = BABYLON.Tmp.Vector3[1];
  14691. this.getWorldMatrix().decompose(scale, rotation, position);
  14692. if (this.rotationQuaternion) {
  14693. this.rotationQuaternion.copyFrom(rotation);
  14694. }
  14695. else {
  14696. rotation.toEulerAnglesToRef(this.rotation);
  14697. }
  14698. this.position.x = position.x;
  14699. this.position.y = position.y;
  14700. this.position.z = position.z;
  14701. }
  14702. else {
  14703. var position = BABYLON.Tmp.Vector3[0];
  14704. var m1 = BABYLON.Tmp.Matrix[0];
  14705. parent.getWorldMatrix().invertToRef(m1);
  14706. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14707. this.position.copyFrom(position);
  14708. }
  14709. this.parent = parent;
  14710. return this;
  14711. };
  14712. /**
  14713. * Adds the passed mesh as a child to the current mesh.
  14714. * Returns the AbstractMesh.
  14715. */
  14716. AbstractMesh.prototype.addChild = function (mesh) {
  14717. mesh.setParent(this);
  14718. return this;
  14719. };
  14720. /**
  14721. * Removes the passed mesh from the current mesh children list.
  14722. * Returns the AbstractMesh.
  14723. */
  14724. AbstractMesh.prototype.removeChild = function (mesh) {
  14725. mesh.setParent(null);
  14726. return this;
  14727. };
  14728. /**
  14729. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14730. * Returns the AbstractMesh.
  14731. */
  14732. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14733. result.x = this._pivotMatrix.m[12];
  14734. result.y = this._pivotMatrix.m[13];
  14735. result.z = this._pivotMatrix.m[14];
  14736. this.getPivotPointToRef(result);
  14737. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14738. return this;
  14739. };
  14740. // Facet data
  14741. /**
  14742. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14743. * Returns the AbstractMesh.
  14744. */
  14745. AbstractMesh.prototype._initFacetData = function () {
  14746. if (!this._facetNormals) {
  14747. this._facetNormals = new Array();
  14748. }
  14749. if (!this._facetPositions) {
  14750. this._facetPositions = new Array();
  14751. }
  14752. if (!this._facetPartitioning) {
  14753. this._facetPartitioning = new Array();
  14754. }
  14755. this._facetNb = this.getIndices().length / 3;
  14756. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14757. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14758. for (var f = 0; f < this._facetNb; f++) {
  14759. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14760. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14761. }
  14762. this._facetDataEnabled = true;
  14763. return this;
  14764. };
  14765. /**
  14766. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14767. * This method can be called within the render loop.
  14768. * 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.
  14769. * Returns the AbstractMesh.
  14770. */
  14771. AbstractMesh.prototype.updateFacetData = function () {
  14772. if (!this._facetDataEnabled) {
  14773. this._initFacetData();
  14774. }
  14775. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14776. var indices = this.getIndices();
  14777. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14778. var bInfo = this.getBoundingInfo();
  14779. if (!bInfo) {
  14780. return this;
  14781. }
  14782. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14783. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14784. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14785. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14786. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14787. this._subDiv.max = this._partitioningSubdivisions;
  14788. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14789. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14790. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14791. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14792. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14793. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14794. // set the parameters for ComputeNormals()
  14795. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14796. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14797. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14798. this._facetParameters.bInfo = bInfo;
  14799. this._facetParameters.bbSize = this._bbSize;
  14800. this._facetParameters.subDiv = this._subDiv;
  14801. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14802. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14803. return this;
  14804. };
  14805. /**
  14806. * Returns the facetLocalNormals array.
  14807. * The normals are expressed in the mesh local space.
  14808. */
  14809. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14810. if (!this._facetNormals) {
  14811. this.updateFacetData();
  14812. }
  14813. return this._facetNormals;
  14814. };
  14815. /**
  14816. * Returns the facetLocalPositions array.
  14817. * The facet positions are expressed in the mesh local space.
  14818. */
  14819. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14820. if (!this._facetPositions) {
  14821. this.updateFacetData();
  14822. }
  14823. return this._facetPositions;
  14824. };
  14825. /**
  14826. * Returns the facetLocalPartioning array.
  14827. */
  14828. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14829. if (!this._facetPartitioning) {
  14830. this.updateFacetData();
  14831. }
  14832. return this._facetPartitioning;
  14833. };
  14834. /**
  14835. * Returns the i-th facet position in the world system.
  14836. * This method allocates a new Vector3 per call.
  14837. */
  14838. AbstractMesh.prototype.getFacetPosition = function (i) {
  14839. var pos = BABYLON.Vector3.Zero();
  14840. this.getFacetPositionToRef(i, pos);
  14841. return pos;
  14842. };
  14843. /**
  14844. * Sets the reference Vector3 with the i-th facet position in the world system.
  14845. * Returns the AbstractMesh.
  14846. */
  14847. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14848. var localPos = (this.getFacetLocalPositions())[i];
  14849. var world = this.getWorldMatrix();
  14850. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14851. return this;
  14852. };
  14853. /**
  14854. * Returns the i-th facet normal in the world system.
  14855. * This method allocates a new Vector3 per call.
  14856. */
  14857. AbstractMesh.prototype.getFacetNormal = function (i) {
  14858. var norm = BABYLON.Vector3.Zero();
  14859. this.getFacetNormalToRef(i, norm);
  14860. return norm;
  14861. };
  14862. /**
  14863. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14864. * Returns the AbstractMesh.
  14865. */
  14866. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14867. var localNorm = (this.getFacetLocalNormals())[i];
  14868. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14869. return this;
  14870. };
  14871. /**
  14872. * 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).
  14873. */
  14874. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14875. var bInfo = this.getBoundingInfo();
  14876. if (!bInfo) {
  14877. return null;
  14878. }
  14879. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14880. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14881. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14882. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14883. return null;
  14884. }
  14885. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14886. };
  14887. /**
  14888. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14889. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14890. * 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.
  14891. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14892. * 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.
  14893. */
  14894. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14895. if (checkFace === void 0) { checkFace = false; }
  14896. if (facing === void 0) { facing = true; }
  14897. var world = this.getWorldMatrix();
  14898. var invMat = BABYLON.Tmp.Matrix[5];
  14899. world.invertToRef(invMat);
  14900. var invVect = BABYLON.Tmp.Vector3[8];
  14901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14902. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14903. if (projected) {
  14904. // tranform the local computed projected vector to world coordinates
  14905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14906. }
  14907. return closest;
  14908. };
  14909. /**
  14910. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14911. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14912. * 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.
  14913. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14914. * 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.
  14915. */
  14916. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14917. if (checkFace === void 0) { checkFace = false; }
  14918. if (facing === void 0) { facing = true; }
  14919. var closest = null;
  14920. var tmpx = 0.0;
  14921. var tmpy = 0.0;
  14922. var tmpz = 0.0;
  14923. var d = 0.0; // tmp dot facet normal * facet position
  14924. var t0 = 0.0;
  14925. var projx = 0.0;
  14926. var projy = 0.0;
  14927. var projz = 0.0;
  14928. // Get all the facets in the same partitioning block than (x, y, z)
  14929. var facetPositions = this.getFacetLocalPositions();
  14930. var facetNormals = this.getFacetLocalNormals();
  14931. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14932. if (!facetsInBlock) {
  14933. return null;
  14934. }
  14935. // Get the closest facet to (x, y, z)
  14936. var shortest = Number.MAX_VALUE; // init distance vars
  14937. var tmpDistance = shortest;
  14938. var fib; // current facet in the block
  14939. var norm; // current facet normal
  14940. var p0; // current facet barycenter position
  14941. // loop on all the facets in the current partitioning block
  14942. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14943. fib = facetsInBlock[idx];
  14944. norm = facetNormals[fib];
  14945. p0 = facetPositions[fib];
  14946. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14947. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14948. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14949. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14950. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14951. projx = x + norm.x * t0;
  14952. projy = y + norm.y * t0;
  14953. projz = z + norm.z * t0;
  14954. tmpx = projx - x;
  14955. tmpy = projy - y;
  14956. tmpz = projz - z;
  14957. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14958. if (tmpDistance < shortest) {
  14959. shortest = tmpDistance;
  14960. closest = fib;
  14961. if (projected) {
  14962. projected.x = projx;
  14963. projected.y = projy;
  14964. projected.z = projz;
  14965. }
  14966. }
  14967. }
  14968. }
  14969. return closest;
  14970. };
  14971. /**
  14972. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14973. */
  14974. AbstractMesh.prototype.getFacetDataParameters = function () {
  14975. return this._facetParameters;
  14976. };
  14977. /**
  14978. * Disables the feature FacetData and frees the related memory.
  14979. * Returns the AbstractMesh.
  14980. */
  14981. AbstractMesh.prototype.disableFacetData = function () {
  14982. if (this._facetDataEnabled) {
  14983. this._facetDataEnabled = false;
  14984. this._facetPositions = new Array();
  14985. ;
  14986. this._facetNormals = new Array();
  14987. ;
  14988. this._facetPartitioning = new Array();
  14989. ;
  14990. this._facetParameters = null;
  14991. }
  14992. return this;
  14993. };
  14994. /**
  14995. * Creates new normals data for the mesh.
  14996. * @param updatable.
  14997. */
  14998. AbstractMesh.prototype.createNormals = function (updatable) {
  14999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15000. var indices = this.getIndices();
  15001. var normals;
  15002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15003. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15004. }
  15005. else {
  15006. normals = [];
  15007. }
  15008. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15010. };
  15011. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15012. var engine = this.getEngine();
  15013. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15014. this._isOccluded = false;
  15015. return;
  15016. }
  15017. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15018. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15019. if (isOcclusionQueryAvailable) {
  15020. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15021. this._isOcclusionQueryInProgress = false;
  15022. this._occlusionInternalRetryCounter = 0;
  15023. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15024. }
  15025. else {
  15026. this._occlusionInternalRetryCounter++;
  15027. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15028. this._isOcclusionQueryInProgress = false;
  15029. this._occlusionInternalRetryCounter = 0;
  15030. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15031. // if strict continue the last state of the object.
  15032. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15033. }
  15034. else {
  15035. return;
  15036. }
  15037. }
  15038. }
  15039. var scene = this.getScene();
  15040. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15041. if (!this._occlusionQuery) {
  15042. this._occlusionQuery = engine.createQuery();
  15043. }
  15044. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15045. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15046. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15047. this._isOcclusionQueryInProgress = true;
  15048. };
  15049. // Statics
  15050. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15051. AbstractMesh._BILLBOARDMODE_X = 1;
  15052. AbstractMesh._BILLBOARDMODE_Y = 2;
  15053. AbstractMesh._BILLBOARDMODE_Z = 4;
  15054. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15055. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15056. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15057. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15058. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15059. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15060. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15061. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15062. return AbstractMesh;
  15063. }(BABYLON.Node));
  15064. BABYLON.AbstractMesh = AbstractMesh;
  15065. })(BABYLON || (BABYLON = {}));
  15066. //# sourceMappingURL=babylon.abstractMesh.js.map
  15067. var BABYLON;
  15068. (function (BABYLON) {
  15069. var Light = /** @class */ (function (_super) {
  15070. __extends(Light, _super);
  15071. /**
  15072. * Creates a Light object in the scene.
  15073. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15074. */
  15075. function Light(name, scene) {
  15076. var _this = _super.call(this, name, scene) || this;
  15077. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15078. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15079. _this.intensity = 1.0;
  15080. _this.range = Number.MAX_VALUE;
  15081. /**
  15082. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15083. * of light.
  15084. */
  15085. _this._photometricScale = 1.0;
  15086. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15087. _this._radius = 0.00001;
  15088. _this.renderPriority = 0;
  15089. /**
  15090. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15091. * the current shadow generator.
  15092. */
  15093. _this.shadowEnabled = true;
  15094. _this._excludeWithLayerMask = 0;
  15095. _this._includeOnlyWithLayerMask = 0;
  15096. _this._lightmapMode = 0;
  15097. _this._excludedMeshesIds = new Array();
  15098. _this._includedOnlyMeshesIds = new Array();
  15099. _this.getScene().addLight(_this);
  15100. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15101. _this._buildUniformLayout();
  15102. _this.includedOnlyMeshes = new Array();
  15103. _this.excludedMeshes = new Array();
  15104. _this._resyncMeshes();
  15105. return _this;
  15106. }
  15107. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15108. /**
  15109. * If every light affecting the material is in this lightmapMode,
  15110. * material.lightmapTexture adds or multiplies
  15111. * (depends on material.useLightmapAsShadowmap)
  15112. * after every other light calculations.
  15113. */
  15114. get: function () {
  15115. return Light._LIGHTMAP_DEFAULT;
  15116. },
  15117. enumerable: true,
  15118. configurable: true
  15119. });
  15120. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15121. /**
  15122. * material.lightmapTexture as only diffuse lighting from this light
  15123. * adds pnly specular lighting from this light
  15124. * adds dynamic shadows
  15125. */
  15126. get: function () {
  15127. return Light._LIGHTMAP_SPECULAR;
  15128. },
  15129. enumerable: true,
  15130. configurable: true
  15131. });
  15132. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15133. /**
  15134. * material.lightmapTexture as only lighting
  15135. * no light calculation from this light
  15136. * only adds dynamic shadows from this light
  15137. */
  15138. get: function () {
  15139. return Light._LIGHTMAP_SHADOWSONLY;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15145. /**
  15146. * Each light type uses the default quantity according to its type:
  15147. * point/spot lights use luminous intensity
  15148. * directional lights use illuminance
  15149. */
  15150. get: function () {
  15151. return Light._INTENSITYMODE_AUTOMATIC;
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15157. /**
  15158. * lumen (lm)
  15159. */
  15160. get: function () {
  15161. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15167. /**
  15168. * candela (lm/sr)
  15169. */
  15170. get: function () {
  15171. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15177. /**
  15178. * lux (lm/m^2)
  15179. */
  15180. get: function () {
  15181. return Light._INTENSITYMODE_ILLUMINANCE;
  15182. },
  15183. enumerable: true,
  15184. configurable: true
  15185. });
  15186. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15187. /**
  15188. * nit (cd/m^2)
  15189. */
  15190. get: function () {
  15191. return Light._INTENSITYMODE_LUMINANCE;
  15192. },
  15193. enumerable: true,
  15194. configurable: true
  15195. });
  15196. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15197. /**
  15198. * Light type const id of the point light.
  15199. */
  15200. get: function () {
  15201. return Light._LIGHTTYPEID_POINTLIGHT;
  15202. },
  15203. enumerable: true,
  15204. configurable: true
  15205. });
  15206. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15207. /**
  15208. * Light type const id of the directional light.
  15209. */
  15210. get: function () {
  15211. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15212. },
  15213. enumerable: true,
  15214. configurable: true
  15215. });
  15216. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15217. /**
  15218. * Light type const id of the spot light.
  15219. */
  15220. get: function () {
  15221. return Light._LIGHTTYPEID_SPOTLIGHT;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15227. /**
  15228. * Light type const id of the hemispheric light.
  15229. */
  15230. get: function () {
  15231. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15232. },
  15233. enumerable: true,
  15234. configurable: true
  15235. });
  15236. Object.defineProperty(Light.prototype, "intensityMode", {
  15237. /**
  15238. * Gets the photometric scale used to interpret the intensity.
  15239. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15240. */
  15241. get: function () {
  15242. return this._intensityMode;
  15243. },
  15244. /**
  15245. * Sets the photometric scale used to interpret the intensity.
  15246. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15247. */
  15248. set: function (value) {
  15249. this._intensityMode = value;
  15250. this._computePhotometricScale();
  15251. },
  15252. enumerable: true,
  15253. configurable: true
  15254. });
  15255. ;
  15256. ;
  15257. Object.defineProperty(Light.prototype, "radius", {
  15258. /**
  15259. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15260. */
  15261. get: function () {
  15262. return this._radius;
  15263. },
  15264. /**
  15265. * sets the light radius used by PBR Materials to simulate soft area lights.
  15266. */
  15267. set: function (value) {
  15268. this._radius = value;
  15269. this._computePhotometricScale();
  15270. },
  15271. enumerable: true,
  15272. configurable: true
  15273. });
  15274. ;
  15275. ;
  15276. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15277. get: function () {
  15278. return this._includedOnlyMeshes;
  15279. },
  15280. set: function (value) {
  15281. this._includedOnlyMeshes = value;
  15282. this._hookArrayForIncludedOnly(value);
  15283. },
  15284. enumerable: true,
  15285. configurable: true
  15286. });
  15287. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15288. get: function () {
  15289. return this._excludedMeshes;
  15290. },
  15291. set: function (value) {
  15292. this._excludedMeshes = value;
  15293. this._hookArrayForExcluded(value);
  15294. },
  15295. enumerable: true,
  15296. configurable: true
  15297. });
  15298. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15299. get: function () {
  15300. return this._excludeWithLayerMask;
  15301. },
  15302. set: function (value) {
  15303. this._excludeWithLayerMask = value;
  15304. this._resyncMeshes();
  15305. },
  15306. enumerable: true,
  15307. configurable: true
  15308. });
  15309. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15310. get: function () {
  15311. return this._includeOnlyWithLayerMask;
  15312. },
  15313. set: function (value) {
  15314. this._includeOnlyWithLayerMask = value;
  15315. this._resyncMeshes();
  15316. },
  15317. enumerable: true,
  15318. configurable: true
  15319. });
  15320. Object.defineProperty(Light.prototype, "lightmapMode", {
  15321. get: function () {
  15322. return this._lightmapMode;
  15323. },
  15324. set: function (value) {
  15325. if (this._lightmapMode === value) {
  15326. return;
  15327. }
  15328. this._lightmapMode = value;
  15329. this._markMeshesAsLightDirty();
  15330. },
  15331. enumerable: true,
  15332. configurable: true
  15333. });
  15334. Light.prototype._buildUniformLayout = function () {
  15335. // Overridden
  15336. };
  15337. /**
  15338. * Returns the string "Light".
  15339. */
  15340. Light.prototype.getClassName = function () {
  15341. return "Light";
  15342. };
  15343. /**
  15344. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15345. */
  15346. Light.prototype.toString = function (fullDetails) {
  15347. var ret = "Name: " + this.name;
  15348. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15349. if (this.animations) {
  15350. for (var i = 0; i < this.animations.length; i++) {
  15351. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15352. }
  15353. }
  15354. if (fullDetails) {
  15355. }
  15356. return ret;
  15357. };
  15358. /**
  15359. * Set the enabled state of this node.
  15360. * @param {boolean} value - the new enabled state
  15361. * @see isEnabled
  15362. */
  15363. Light.prototype.setEnabled = function (value) {
  15364. _super.prototype.setEnabled.call(this, value);
  15365. this._resyncMeshes();
  15366. };
  15367. /**
  15368. * Returns the Light associated shadow generator.
  15369. */
  15370. Light.prototype.getShadowGenerator = function () {
  15371. return this._shadowGenerator;
  15372. };
  15373. /**
  15374. * Returns a Vector3, the absolute light position in the World.
  15375. */
  15376. Light.prototype.getAbsolutePosition = function () {
  15377. return BABYLON.Vector3.Zero();
  15378. };
  15379. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15380. };
  15381. Light.prototype._getWorldMatrix = function () {
  15382. return BABYLON.Matrix.Identity();
  15383. };
  15384. /**
  15385. * Boolean : True if the light will affect the passed mesh.
  15386. */
  15387. Light.prototype.canAffectMesh = function (mesh) {
  15388. if (!mesh) {
  15389. return true;
  15390. }
  15391. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15392. return false;
  15393. }
  15394. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15395. return false;
  15396. }
  15397. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15398. return false;
  15399. }
  15400. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15401. return false;
  15402. }
  15403. return true;
  15404. };
  15405. /**
  15406. * Returns the light World matrix.
  15407. */
  15408. Light.prototype.getWorldMatrix = function () {
  15409. this._currentRenderId = this.getScene().getRenderId();
  15410. var worldMatrix = this._getWorldMatrix();
  15411. if (this.parent && this.parent.getWorldMatrix) {
  15412. if (!this._parentedWorldMatrix) {
  15413. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15414. }
  15415. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15416. this._markSyncedWithParent();
  15417. return this._parentedWorldMatrix;
  15418. }
  15419. return worldMatrix;
  15420. };
  15421. /**
  15422. * Sort function to order lights for rendering.
  15423. * @param a First Light object to compare to second.
  15424. * @param b Second Light object to compare first.
  15425. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15426. */
  15427. Light.compareLightsPriority = function (a, b) {
  15428. //shadow-casting lights have priority over non-shadow-casting lights
  15429. //the renderPrioirty is a secondary sort criterion
  15430. if (a.shadowEnabled !== b.shadowEnabled) {
  15431. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15432. }
  15433. return b.renderPriority - a.renderPriority;
  15434. };
  15435. /**
  15436. * Disposes the light.
  15437. */
  15438. Light.prototype.dispose = function () {
  15439. if (this._shadowGenerator) {
  15440. this._shadowGenerator.dispose();
  15441. this._shadowGenerator = null;
  15442. }
  15443. // Animations
  15444. this.getScene().stopAnimation(this);
  15445. // Remove from meshes
  15446. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15447. var mesh = _a[_i];
  15448. mesh._removeLightSource(this);
  15449. }
  15450. this._uniformBuffer.dispose();
  15451. // Remove from scene
  15452. this.getScene().removeLight(this);
  15453. _super.prototype.dispose.call(this);
  15454. };
  15455. /**
  15456. * Returns the light type ID (integer).
  15457. */
  15458. Light.prototype.getTypeID = function () {
  15459. return 0;
  15460. };
  15461. /**
  15462. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15463. */
  15464. Light.prototype.getScaledIntensity = function () {
  15465. return this._photometricScale * this.intensity;
  15466. };
  15467. /**
  15468. * Returns a new Light object, named "name", from the current one.
  15469. */
  15470. Light.prototype.clone = function (name) {
  15471. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15472. if (!constructor) {
  15473. return null;
  15474. }
  15475. return BABYLON.SerializationHelper.Clone(constructor, this);
  15476. };
  15477. /**
  15478. * Serializes the current light into a Serialization object.
  15479. * Returns the serialized object.
  15480. */
  15481. Light.prototype.serialize = function () {
  15482. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15483. // Type
  15484. serializationObject.type = this.getTypeID();
  15485. // Parent
  15486. if (this.parent) {
  15487. serializationObject.parentId = this.parent.id;
  15488. }
  15489. // Inclusion / exclusions
  15490. if (this.excludedMeshes.length > 0) {
  15491. serializationObject.excludedMeshesIds = [];
  15492. this.excludedMeshes.forEach(function (mesh) {
  15493. serializationObject.excludedMeshesIds.push(mesh.id);
  15494. });
  15495. }
  15496. if (this.includedOnlyMeshes.length > 0) {
  15497. serializationObject.includedOnlyMeshesIds = [];
  15498. this.includedOnlyMeshes.forEach(function (mesh) {
  15499. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15500. });
  15501. }
  15502. // Animations
  15503. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15504. serializationObject.ranges = this.serializeAnimationRanges();
  15505. return serializationObject;
  15506. };
  15507. /**
  15508. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15509. * This new light is named "name" and added to the passed scene.
  15510. */
  15511. Light.GetConstructorFromName = function (type, name, scene) {
  15512. switch (type) {
  15513. case 0:
  15514. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15515. case 1:
  15516. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15517. case 2:
  15518. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15519. case 3:
  15520. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15521. }
  15522. return null;
  15523. };
  15524. /**
  15525. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15526. */
  15527. Light.Parse = function (parsedLight, scene) {
  15528. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15529. if (!constructor) {
  15530. return null;
  15531. }
  15532. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15533. // Inclusion / exclusions
  15534. if (parsedLight.excludedMeshesIds) {
  15535. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15536. }
  15537. if (parsedLight.includedOnlyMeshesIds) {
  15538. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15539. }
  15540. // Parent
  15541. if (parsedLight.parentId) {
  15542. light._waitingParentId = parsedLight.parentId;
  15543. }
  15544. // Animations
  15545. if (parsedLight.animations) {
  15546. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15547. var parsedAnimation = parsedLight.animations[animationIndex];
  15548. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15549. }
  15550. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15551. }
  15552. if (parsedLight.autoAnimate) {
  15553. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15554. }
  15555. return light;
  15556. };
  15557. Light.prototype._hookArrayForExcluded = function (array) {
  15558. var _this = this;
  15559. var oldPush = array.push;
  15560. array.push = function () {
  15561. var items = [];
  15562. for (var _i = 0; _i < arguments.length; _i++) {
  15563. items[_i] = arguments[_i];
  15564. }
  15565. var result = oldPush.apply(array, items);
  15566. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15567. var item = items_1[_a];
  15568. item._resyncLighSource(_this);
  15569. }
  15570. return result;
  15571. };
  15572. var oldSplice = array.splice;
  15573. array.splice = function (index, deleteCount) {
  15574. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15575. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15576. var item = deleted_1[_i];
  15577. item._resyncLighSource(_this);
  15578. }
  15579. return deleted;
  15580. };
  15581. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15582. var item = array_1[_i];
  15583. item._resyncLighSource(this);
  15584. }
  15585. };
  15586. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15587. var _this = this;
  15588. var oldPush = array.push;
  15589. array.push = function () {
  15590. var items = [];
  15591. for (var _i = 0; _i < arguments.length; _i++) {
  15592. items[_i] = arguments[_i];
  15593. }
  15594. var result = oldPush.apply(array, items);
  15595. _this._resyncMeshes();
  15596. return result;
  15597. };
  15598. var oldSplice = array.splice;
  15599. array.splice = function (index, deleteCount) {
  15600. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15601. _this._resyncMeshes();
  15602. return deleted;
  15603. };
  15604. this._resyncMeshes();
  15605. };
  15606. Light.prototype._resyncMeshes = function () {
  15607. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15608. var mesh = _a[_i];
  15609. mesh._resyncLighSource(this);
  15610. }
  15611. };
  15612. Light.prototype._markMeshesAsLightDirty = function () {
  15613. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15614. var mesh = _a[_i];
  15615. if (mesh._lightSources.indexOf(this) !== -1) {
  15616. mesh._markSubMeshesAsLightDirty();
  15617. }
  15618. }
  15619. };
  15620. /**
  15621. * Recomputes the cached photometric scale if needed.
  15622. */
  15623. Light.prototype._computePhotometricScale = function () {
  15624. this._photometricScale = this._getPhotometricScale();
  15625. this.getScene().resetCachedMaterial();
  15626. };
  15627. /**
  15628. * Returns the Photometric Scale according to the light type and intensity mode.
  15629. */
  15630. Light.prototype._getPhotometricScale = function () {
  15631. var photometricScale = 0.0;
  15632. var lightTypeID = this.getTypeID();
  15633. //get photometric mode
  15634. var photometricMode = this.intensityMode;
  15635. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15636. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15637. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15638. }
  15639. else {
  15640. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15641. }
  15642. }
  15643. //compute photometric scale
  15644. switch (lightTypeID) {
  15645. case Light.LIGHTTYPEID_POINTLIGHT:
  15646. case Light.LIGHTTYPEID_SPOTLIGHT:
  15647. switch (photometricMode) {
  15648. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15649. photometricScale = 1.0 / (4.0 * Math.PI);
  15650. break;
  15651. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15652. photometricScale = 1.0;
  15653. break;
  15654. case Light.INTENSITYMODE_LUMINANCE:
  15655. photometricScale = this.radius * this.radius;
  15656. break;
  15657. }
  15658. break;
  15659. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15660. switch (photometricMode) {
  15661. case Light.INTENSITYMODE_ILLUMINANCE:
  15662. photometricScale = 1.0;
  15663. break;
  15664. case Light.INTENSITYMODE_LUMINANCE:
  15665. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15666. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15667. var apexAngleRadians = this.radius;
  15668. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15669. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15670. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15671. photometricScale = solidAngle;
  15672. break;
  15673. }
  15674. break;
  15675. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15676. // No fall off in hemisperic light.
  15677. photometricScale = 1.0;
  15678. break;
  15679. }
  15680. return photometricScale;
  15681. };
  15682. Light.prototype._reorderLightsInScene = function () {
  15683. var scene = this.getScene();
  15684. if (this._renderPriority != 0) {
  15685. scene.requireLightSorting = true;
  15686. }
  15687. this.getScene().sortLightsByPriority();
  15688. };
  15689. //lightmapMode Consts
  15690. Light._LIGHTMAP_DEFAULT = 0;
  15691. Light._LIGHTMAP_SPECULAR = 1;
  15692. Light._LIGHTMAP_SHADOWSONLY = 2;
  15693. // Intensity Mode Consts
  15694. Light._INTENSITYMODE_AUTOMATIC = 0;
  15695. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15696. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15697. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15698. Light._INTENSITYMODE_LUMINANCE = 4;
  15699. // Light types ids const.
  15700. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15701. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15702. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15703. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15704. __decorate([
  15705. BABYLON.serializeAsColor3()
  15706. ], Light.prototype, "diffuse", void 0);
  15707. __decorate([
  15708. BABYLON.serializeAsColor3()
  15709. ], Light.prototype, "specular", void 0);
  15710. __decorate([
  15711. BABYLON.serialize()
  15712. ], Light.prototype, "intensity", void 0);
  15713. __decorate([
  15714. BABYLON.serialize()
  15715. ], Light.prototype, "range", void 0);
  15716. __decorate([
  15717. BABYLON.serialize()
  15718. ], Light.prototype, "intensityMode", null);
  15719. __decorate([
  15720. BABYLON.serialize()
  15721. ], Light.prototype, "radius", null);
  15722. __decorate([
  15723. BABYLON.serialize()
  15724. ], Light.prototype, "_renderPriority", void 0);
  15725. __decorate([
  15726. BABYLON.expandToProperty("_reorderLightsInScene")
  15727. ], Light.prototype, "renderPriority", void 0);
  15728. __decorate([
  15729. BABYLON.serialize()
  15730. ], Light.prototype, "shadowEnabled", void 0);
  15731. __decorate([
  15732. BABYLON.serialize("excludeWithLayerMask")
  15733. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15734. __decorate([
  15735. BABYLON.serialize("includeOnlyWithLayerMask")
  15736. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15737. __decorate([
  15738. BABYLON.serialize("lightmapMode")
  15739. ], Light.prototype, "_lightmapMode", void 0);
  15740. return Light;
  15741. }(BABYLON.Node));
  15742. BABYLON.Light = Light;
  15743. })(BABYLON || (BABYLON = {}));
  15744. //# sourceMappingURL=babylon.light.js.map
  15745. var BABYLON;
  15746. (function (BABYLON) {
  15747. var Camera = /** @class */ (function (_super) {
  15748. __extends(Camera, _super);
  15749. function Camera(name, position, scene) {
  15750. var _this = _super.call(this, name, scene) || this;
  15751. _this.upVector = BABYLON.Vector3.Up();
  15752. _this.orthoLeft = null;
  15753. _this.orthoRight = null;
  15754. _this.orthoBottom = null;
  15755. _this.orthoTop = null;
  15756. _this.fov = 0.8;
  15757. _this.minZ = 1;
  15758. _this.maxZ = 10000.0;
  15759. _this.inertia = 0.9;
  15760. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15761. _this.isIntermediate = false;
  15762. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15763. _this.layerMask = 0x0FFFFFFF;
  15764. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15765. // Camera rig members
  15766. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15767. _this._rigCameras = new Array();
  15768. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15769. _this._skipRendering = false;
  15770. _this.customRenderTargets = new Array();
  15771. // Observables
  15772. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15773. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15774. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15775. _this.onRestoreStateObservable = new BABYLON.Observable();
  15776. // Cache
  15777. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15778. _this._projectionMatrix = new BABYLON.Matrix();
  15779. _this._doNotComputeProjectionMatrix = false;
  15780. _this._postProcesses = new Array();
  15781. _this._transformMatrix = BABYLON.Matrix.Zero();
  15782. _this._activeMeshes = new BABYLON.SmartArray(256);
  15783. _this._globalPosition = BABYLON.Vector3.Zero();
  15784. _this._refreshFrustumPlanes = true;
  15785. _this.getScene().addCamera(_this);
  15786. if (!_this.getScene().activeCamera) {
  15787. _this.getScene().activeCamera = _this;
  15788. }
  15789. _this.position = position;
  15790. return _this;
  15791. }
  15792. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15793. get: function () {
  15794. return Camera._PERSPECTIVE_CAMERA;
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15800. get: function () {
  15801. return Camera._ORTHOGRAPHIC_CAMERA;
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15807. get: function () {
  15808. return Camera._FOVMODE_VERTICAL_FIXED;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15814. get: function () {
  15815. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15821. get: function () {
  15822. return Camera._RIG_MODE_NONE;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15828. get: function () {
  15829. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15835. get: function () {
  15836. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15842. get: function () {
  15843. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15849. get: function () {
  15850. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15856. get: function () {
  15857. return Camera._RIG_MODE_VR;
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15863. get: function () {
  15864. return Camera._RIG_MODE_WEBVR;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. /**
  15870. * Store current camera state (fov, position, etc..)
  15871. */
  15872. Camera.prototype.storeState = function () {
  15873. this._stateStored = true;
  15874. this._storedFov = this.fov;
  15875. return this;
  15876. };
  15877. /**
  15878. * Restores the camera state values if it has been stored. You must call storeState() first
  15879. */
  15880. Camera.prototype._restoreStateValues = function () {
  15881. if (!this._stateStored) {
  15882. return false;
  15883. }
  15884. this.fov = this._storedFov;
  15885. return true;
  15886. };
  15887. /**
  15888. * Restored camera state. You must call storeState() first
  15889. */
  15890. Camera.prototype.restoreState = function () {
  15891. if (this._restoreStateValues()) {
  15892. this.onRestoreStateObservable.notifyObservers(this);
  15893. return true;
  15894. }
  15895. return false;
  15896. };
  15897. Camera.prototype.getClassName = function () {
  15898. return "Camera";
  15899. };
  15900. /**
  15901. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15902. */
  15903. Camera.prototype.toString = function (fullDetails) {
  15904. var ret = "Name: " + this.name;
  15905. ret += ", type: " + this.getClassName();
  15906. if (this.animations) {
  15907. for (var i = 0; i < this.animations.length; i++) {
  15908. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15909. }
  15910. }
  15911. if (fullDetails) {
  15912. }
  15913. return ret;
  15914. };
  15915. Object.defineProperty(Camera.prototype, "globalPosition", {
  15916. get: function () {
  15917. return this._globalPosition;
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Camera.prototype.getActiveMeshes = function () {
  15923. return this._activeMeshes;
  15924. };
  15925. Camera.prototype.isActiveMesh = function (mesh) {
  15926. return (this._activeMeshes.indexOf(mesh) !== -1);
  15927. };
  15928. //Cache
  15929. Camera.prototype._initCache = function () {
  15930. _super.prototype._initCache.call(this);
  15931. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15932. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15933. this._cache.mode = undefined;
  15934. this._cache.minZ = undefined;
  15935. this._cache.maxZ = undefined;
  15936. this._cache.fov = undefined;
  15937. this._cache.fovMode = undefined;
  15938. this._cache.aspectRatio = undefined;
  15939. this._cache.orthoLeft = undefined;
  15940. this._cache.orthoRight = undefined;
  15941. this._cache.orthoBottom = undefined;
  15942. this._cache.orthoTop = undefined;
  15943. this._cache.renderWidth = undefined;
  15944. this._cache.renderHeight = undefined;
  15945. };
  15946. Camera.prototype._updateCache = function (ignoreParentClass) {
  15947. if (!ignoreParentClass) {
  15948. _super.prototype._updateCache.call(this);
  15949. }
  15950. this._cache.position.copyFrom(this.position);
  15951. this._cache.upVector.copyFrom(this.upVector);
  15952. };
  15953. // Synchronized
  15954. Camera.prototype._isSynchronized = function () {
  15955. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15956. };
  15957. Camera.prototype._isSynchronizedViewMatrix = function () {
  15958. if (!_super.prototype._isSynchronized.call(this))
  15959. return false;
  15960. return this._cache.position.equals(this.position)
  15961. && this._cache.upVector.equals(this.upVector)
  15962. && this.isSynchronizedWithParent();
  15963. };
  15964. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15965. var check = this._cache.mode === this.mode
  15966. && this._cache.minZ === this.minZ
  15967. && this._cache.maxZ === this.maxZ;
  15968. if (!check) {
  15969. return false;
  15970. }
  15971. var engine = this.getEngine();
  15972. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15973. check = this._cache.fov === this.fov
  15974. && this._cache.fovMode === this.fovMode
  15975. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15976. }
  15977. else {
  15978. check = this._cache.orthoLeft === this.orthoLeft
  15979. && this._cache.orthoRight === this.orthoRight
  15980. && this._cache.orthoBottom === this.orthoBottom
  15981. && this._cache.orthoTop === this.orthoTop
  15982. && this._cache.renderWidth === engine.getRenderWidth()
  15983. && this._cache.renderHeight === engine.getRenderHeight();
  15984. }
  15985. return check;
  15986. };
  15987. // Controls
  15988. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15989. };
  15990. Camera.prototype.detachControl = function (element) {
  15991. };
  15992. Camera.prototype.update = function () {
  15993. this._checkInputs();
  15994. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15995. this._updateRigCameras();
  15996. }
  15997. };
  15998. Camera.prototype._checkInputs = function () {
  15999. this.onAfterCheckInputsObservable.notifyObservers(this);
  16000. };
  16001. Object.defineProperty(Camera.prototype, "rigCameras", {
  16002. get: function () {
  16003. return this._rigCameras;
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16009. get: function () {
  16010. return this._rigPostProcess;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16016. // invalidate framebuffer
  16017. if (this._postProcesses.length > 0) {
  16018. this._postProcesses[0].markTextureDirty();
  16019. }
  16020. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16021. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16022. var cam = this._rigCameras[i];
  16023. var rigPostProcess = cam._rigPostProcess;
  16024. // for VR rig, there does not have to be a post process
  16025. if (rigPostProcess) {
  16026. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16027. if (isPass) {
  16028. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16029. cam.isIntermediate = this._postProcesses.length === 0;
  16030. }
  16031. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16032. rigPostProcess.markTextureDirty();
  16033. }
  16034. else {
  16035. cam._postProcesses = this._postProcesses.slice(0);
  16036. }
  16037. }
  16038. };
  16039. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16040. if (insertAt === void 0) { insertAt = null; }
  16041. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16042. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16043. return 0;
  16044. }
  16045. if (insertAt == null || insertAt < 0) {
  16046. this._postProcesses.push(postProcess);
  16047. }
  16048. else {
  16049. this._postProcesses.splice(insertAt, 0, postProcess);
  16050. }
  16051. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16052. return this._postProcesses.indexOf(postProcess);
  16053. };
  16054. Camera.prototype.detachPostProcess = function (postProcess) {
  16055. var idx = this._postProcesses.indexOf(postProcess);
  16056. if (idx !== -1) {
  16057. this._postProcesses.splice(idx, 1);
  16058. }
  16059. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16060. };
  16061. Camera.prototype.getWorldMatrix = function () {
  16062. if (!this._worldMatrix) {
  16063. this._worldMatrix = BABYLON.Matrix.Identity();
  16064. }
  16065. var viewMatrix = this.getViewMatrix();
  16066. viewMatrix.invertToRef(this._worldMatrix);
  16067. return this._worldMatrix;
  16068. };
  16069. Camera.prototype._getViewMatrix = function () {
  16070. return BABYLON.Matrix.Identity();
  16071. };
  16072. Camera.prototype.getViewMatrix = function (force) {
  16073. if (!force && this._isSynchronizedViewMatrix()) {
  16074. return this._computedViewMatrix;
  16075. }
  16076. this.updateCache();
  16077. this._computedViewMatrix = this._getViewMatrix();
  16078. this._currentRenderId = this.getScene().getRenderId();
  16079. this._refreshFrustumPlanes = true;
  16080. if (!this.parent || !this.parent.getWorldMatrix) {
  16081. this._globalPosition.copyFrom(this.position);
  16082. }
  16083. else {
  16084. if (!this._worldMatrix) {
  16085. this._worldMatrix = BABYLON.Matrix.Identity();
  16086. }
  16087. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16088. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16089. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16090. this._computedViewMatrix.invert();
  16091. this._markSyncedWithParent();
  16092. }
  16093. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16094. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16095. }
  16096. this.onViewMatrixChangedObservable.notifyObservers(this);
  16097. return this._computedViewMatrix;
  16098. };
  16099. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16100. this._doNotComputeProjectionMatrix = true;
  16101. if (projection !== undefined) {
  16102. this._projectionMatrix = projection;
  16103. }
  16104. };
  16105. ;
  16106. Camera.prototype.unfreezeProjectionMatrix = function () {
  16107. this._doNotComputeProjectionMatrix = false;
  16108. };
  16109. ;
  16110. Camera.prototype.getProjectionMatrix = function (force) {
  16111. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16112. return this._projectionMatrix;
  16113. }
  16114. // Cache
  16115. this._cache.mode = this.mode;
  16116. this._cache.minZ = this.minZ;
  16117. this._cache.maxZ = this.maxZ;
  16118. // Matrix
  16119. this._refreshFrustumPlanes = true;
  16120. var engine = this.getEngine();
  16121. var scene = this.getScene();
  16122. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16123. this._cache.fov = this.fov;
  16124. this._cache.fovMode = this.fovMode;
  16125. this._cache.aspectRatio = engine.getAspectRatio(this);
  16126. if (this.minZ <= 0) {
  16127. this.minZ = 0.1;
  16128. }
  16129. if (scene.useRightHandedSystem) {
  16130. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16131. }
  16132. else {
  16133. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16134. }
  16135. }
  16136. else {
  16137. var halfWidth = engine.getRenderWidth() / 2.0;
  16138. var halfHeight = engine.getRenderHeight() / 2.0;
  16139. if (scene.useRightHandedSystem) {
  16140. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16141. }
  16142. else {
  16143. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16144. }
  16145. this._cache.orthoLeft = this.orthoLeft;
  16146. this._cache.orthoRight = this.orthoRight;
  16147. this._cache.orthoBottom = this.orthoBottom;
  16148. this._cache.orthoTop = this.orthoTop;
  16149. this._cache.renderWidth = engine.getRenderWidth();
  16150. this._cache.renderHeight = engine.getRenderHeight();
  16151. }
  16152. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16153. return this._projectionMatrix;
  16154. };
  16155. Camera.prototype.getTranformationMatrix = function () {
  16156. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16157. return this._transformMatrix;
  16158. };
  16159. Camera.prototype.updateFrustumPlanes = function () {
  16160. if (!this._refreshFrustumPlanes) {
  16161. return;
  16162. }
  16163. this.getTranformationMatrix();
  16164. if (!this._frustumPlanes) {
  16165. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16166. }
  16167. else {
  16168. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16169. }
  16170. this._refreshFrustumPlanes = false;
  16171. };
  16172. Camera.prototype.isInFrustum = function (target) {
  16173. this.updateFrustumPlanes();
  16174. return target.isInFrustum(this._frustumPlanes);
  16175. };
  16176. Camera.prototype.isCompletelyInFrustum = function (target) {
  16177. this.updateFrustumPlanes();
  16178. return target.isCompletelyInFrustum(this._frustumPlanes);
  16179. };
  16180. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16181. if (length === void 0) { length = 100; }
  16182. if (!transform) {
  16183. transform = this.getWorldMatrix();
  16184. }
  16185. if (!origin) {
  16186. origin = this.position;
  16187. }
  16188. var forward = new BABYLON.Vector3(0, 0, 1);
  16189. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16190. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16191. return new BABYLON.Ray(origin, direction, length);
  16192. };
  16193. Camera.prototype.dispose = function () {
  16194. // Observables
  16195. this.onViewMatrixChangedObservable.clear();
  16196. this.onProjectionMatrixChangedObservable.clear();
  16197. this.onAfterCheckInputsObservable.clear();
  16198. this.onRestoreStateObservable.clear();
  16199. // Inputs
  16200. if (this.inputs) {
  16201. this.inputs.clear();
  16202. }
  16203. // Animations
  16204. this.getScene().stopAnimation(this);
  16205. // Remove from scene
  16206. this.getScene().removeCamera(this);
  16207. while (this._rigCameras.length > 0) {
  16208. var camera = this._rigCameras.pop();
  16209. if (camera) {
  16210. camera.dispose();
  16211. }
  16212. }
  16213. // Postprocesses
  16214. if (this._rigPostProcess) {
  16215. this._rigPostProcess.dispose(this);
  16216. this._rigPostProcess = null;
  16217. this._postProcesses = [];
  16218. }
  16219. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16220. this._rigPostProcess = null;
  16221. this._postProcesses = [];
  16222. }
  16223. else {
  16224. var i = this._postProcesses.length;
  16225. while (--i >= 0) {
  16226. this._postProcesses[i].dispose(this);
  16227. }
  16228. }
  16229. // Render targets
  16230. var i = this.customRenderTargets.length;
  16231. while (--i >= 0) {
  16232. this.customRenderTargets[i].dispose();
  16233. }
  16234. this.customRenderTargets = [];
  16235. // Active Meshes
  16236. this._activeMeshes.dispose();
  16237. _super.prototype.dispose.call(this);
  16238. };
  16239. Object.defineProperty(Camera.prototype, "leftCamera", {
  16240. // ---- Camera rigs section ----
  16241. get: function () {
  16242. if (this._rigCameras.length < 1) {
  16243. return null;
  16244. }
  16245. return this._rigCameras[0];
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(Camera.prototype, "rightCamera", {
  16251. get: function () {
  16252. if (this._rigCameras.length < 2) {
  16253. return null;
  16254. }
  16255. return this._rigCameras[1];
  16256. },
  16257. enumerable: true,
  16258. configurable: true
  16259. });
  16260. Camera.prototype.getLeftTarget = function () {
  16261. if (this._rigCameras.length < 1) {
  16262. return null;
  16263. }
  16264. return this._rigCameras[0].getTarget();
  16265. };
  16266. Camera.prototype.getRightTarget = function () {
  16267. if (this._rigCameras.length < 2) {
  16268. return null;
  16269. }
  16270. return this._rigCameras[1].getTarget();
  16271. };
  16272. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16273. if (this.cameraRigMode === mode) {
  16274. return;
  16275. }
  16276. while (this._rigCameras.length > 0) {
  16277. var camera = this._rigCameras.pop();
  16278. if (camera) {
  16279. camera.dispose();
  16280. }
  16281. }
  16282. this.cameraRigMode = mode;
  16283. this._cameraRigParams = {};
  16284. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16285. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16286. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16287. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16288. // create the rig cameras, unless none
  16289. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16290. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16291. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16292. if (leftCamera && rightCamera) {
  16293. this._rigCameras.push(leftCamera);
  16294. this._rigCameras.push(rightCamera);
  16295. }
  16296. }
  16297. switch (this.cameraRigMode) {
  16298. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16299. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16300. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16301. break;
  16302. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16303. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16304. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16305. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16306. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16307. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16308. break;
  16309. case Camera.RIG_MODE_VR:
  16310. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16311. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16312. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16313. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16314. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16315. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16316. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16317. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16318. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16319. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16320. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16321. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16322. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16323. if (metrics.compensateDistortion) {
  16324. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16325. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16326. }
  16327. break;
  16328. case Camera.RIG_MODE_WEBVR:
  16329. if (rigParams.vrDisplay) {
  16330. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16331. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16332. //Left eye
  16333. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16334. this._rigCameras[0].setCameraRigParameter("left", true);
  16335. //leaving this for future reference
  16336. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16337. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16338. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16339. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16340. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16341. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16342. this._rigCameras[0].parent = this;
  16343. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16344. //Right eye
  16345. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16346. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16347. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16348. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16349. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16350. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16351. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16352. this._rigCameras[1].parent = this;
  16353. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16354. if (Camera.UseAlternateWebVRRendering) {
  16355. this._rigCameras[1]._skipRendering = true;
  16356. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16357. }
  16358. }
  16359. break;
  16360. }
  16361. this._cascadePostProcessesToRigCams();
  16362. this.update();
  16363. };
  16364. Camera.prototype._getVRProjectionMatrix = function () {
  16365. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16366. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16367. return this._projectionMatrix;
  16368. };
  16369. Camera.prototype._updateCameraRotationMatrix = function () {
  16370. //Here for WebVR
  16371. };
  16372. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16373. //Here for WebVR
  16374. };
  16375. /**
  16376. * This function MUST be overwritten by the different WebVR cameras available.
  16377. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16378. */
  16379. Camera.prototype._getWebVRProjectionMatrix = function () {
  16380. return BABYLON.Matrix.Identity();
  16381. };
  16382. /**
  16383. * This function MUST be overwritten by the different WebVR cameras available.
  16384. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16385. */
  16386. Camera.prototype._getWebVRViewMatrix = function () {
  16387. return BABYLON.Matrix.Identity();
  16388. };
  16389. Camera.prototype.setCameraRigParameter = function (name, value) {
  16390. if (!this._cameraRigParams) {
  16391. this._cameraRigParams = {};
  16392. }
  16393. this._cameraRigParams[name] = value;
  16394. //provisionnally:
  16395. if (name === "interaxialDistance") {
  16396. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16397. }
  16398. };
  16399. /**
  16400. * needs to be overridden by children so sub has required properties to be copied
  16401. */
  16402. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16403. return null;
  16404. };
  16405. /**
  16406. * May need to be overridden by children
  16407. */
  16408. Camera.prototype._updateRigCameras = function () {
  16409. for (var i = 0; i < this._rigCameras.length; i++) {
  16410. this._rigCameras[i].minZ = this.minZ;
  16411. this._rigCameras[i].maxZ = this.maxZ;
  16412. this._rigCameras[i].fov = this.fov;
  16413. }
  16414. // only update viewport when ANAGLYPH
  16415. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16416. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16417. }
  16418. };
  16419. Camera.prototype._setupInputs = function () {
  16420. };
  16421. Camera.prototype.serialize = function () {
  16422. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16423. // Type
  16424. serializationObject.type = this.getClassName();
  16425. // Parent
  16426. if (this.parent) {
  16427. serializationObject.parentId = this.parent.id;
  16428. }
  16429. if (this.inputs) {
  16430. this.inputs.serialize(serializationObject);
  16431. }
  16432. // Animations
  16433. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16434. serializationObject.ranges = this.serializeAnimationRanges();
  16435. return serializationObject;
  16436. };
  16437. Camera.prototype.clone = function (name) {
  16438. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16439. };
  16440. Camera.prototype.getDirection = function (localAxis) {
  16441. var result = BABYLON.Vector3.Zero();
  16442. this.getDirectionToRef(localAxis, result);
  16443. return result;
  16444. };
  16445. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16446. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16447. };
  16448. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16449. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16450. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16451. switch (type) {
  16452. case "ArcRotateCamera":
  16453. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16454. case "DeviceOrientationCamera":
  16455. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16456. case "FollowCamera":
  16457. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16458. case "ArcFollowCamera":
  16459. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16460. case "GamepadCamera":
  16461. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16462. case "TouchCamera":
  16463. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16464. case "VirtualJoysticksCamera":
  16465. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16466. case "WebVRFreeCamera":
  16467. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16468. case "WebVRGamepadCamera":
  16469. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16470. case "VRDeviceOrientationFreeCamera":
  16471. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16472. case "VRDeviceOrientationGamepadCamera":
  16473. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16474. case "AnaglyphArcRotateCamera":
  16475. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16476. case "AnaglyphFreeCamera":
  16477. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16478. case "AnaglyphGamepadCamera":
  16479. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16480. case "AnaglyphUniversalCamera":
  16481. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16482. case "StereoscopicArcRotateCamera":
  16483. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16484. case "StereoscopicFreeCamera":
  16485. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16486. case "StereoscopicGamepadCamera":
  16487. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16488. case "StereoscopicUniversalCamera":
  16489. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16490. case "FreeCamera":// Forcing Universal here
  16491. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16492. default:// Universal Camera is the default value
  16493. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16494. }
  16495. };
  16496. Camera.Parse = function (parsedCamera, scene) {
  16497. var type = parsedCamera.type;
  16498. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16499. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16500. // Parent
  16501. if (parsedCamera.parentId) {
  16502. camera._waitingParentId = parsedCamera.parentId;
  16503. }
  16504. //If camera has an input manager, let it parse inputs settings
  16505. if (camera.inputs) {
  16506. camera.inputs.parse(parsedCamera);
  16507. camera._setupInputs();
  16508. }
  16509. if (camera.setPosition) {
  16510. camera.position.copyFromFloats(0, 0, 0);
  16511. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16512. }
  16513. // Target
  16514. if (parsedCamera.target) {
  16515. if (camera.setTarget) {
  16516. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16517. }
  16518. }
  16519. // Apply 3d rig, when found
  16520. if (parsedCamera.cameraRigMode) {
  16521. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16522. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16523. }
  16524. // Animations
  16525. if (parsedCamera.animations) {
  16526. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16527. var parsedAnimation = parsedCamera.animations[animationIndex];
  16528. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16529. }
  16530. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16531. }
  16532. if (parsedCamera.autoAnimate) {
  16533. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16534. }
  16535. return camera;
  16536. };
  16537. // Statics
  16538. Camera._PERSPECTIVE_CAMERA = 0;
  16539. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16540. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16541. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16542. Camera._RIG_MODE_NONE = 0;
  16543. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16544. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16545. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16546. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16547. Camera._RIG_MODE_VR = 20;
  16548. Camera._RIG_MODE_WEBVR = 21;
  16549. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16550. Camera.UseAlternateWebVRRendering = false;
  16551. __decorate([
  16552. BABYLON.serializeAsVector3()
  16553. ], Camera.prototype, "position", void 0);
  16554. __decorate([
  16555. BABYLON.serializeAsVector3()
  16556. ], Camera.prototype, "upVector", void 0);
  16557. __decorate([
  16558. BABYLON.serialize()
  16559. ], Camera.prototype, "orthoLeft", void 0);
  16560. __decorate([
  16561. BABYLON.serialize()
  16562. ], Camera.prototype, "orthoRight", void 0);
  16563. __decorate([
  16564. BABYLON.serialize()
  16565. ], Camera.prototype, "orthoBottom", void 0);
  16566. __decorate([
  16567. BABYLON.serialize()
  16568. ], Camera.prototype, "orthoTop", void 0);
  16569. __decorate([
  16570. BABYLON.serialize()
  16571. ], Camera.prototype, "fov", void 0);
  16572. __decorate([
  16573. BABYLON.serialize()
  16574. ], Camera.prototype, "minZ", void 0);
  16575. __decorate([
  16576. BABYLON.serialize()
  16577. ], Camera.prototype, "maxZ", void 0);
  16578. __decorate([
  16579. BABYLON.serialize()
  16580. ], Camera.prototype, "inertia", void 0);
  16581. __decorate([
  16582. BABYLON.serialize()
  16583. ], Camera.prototype, "mode", void 0);
  16584. __decorate([
  16585. BABYLON.serialize()
  16586. ], Camera.prototype, "layerMask", void 0);
  16587. __decorate([
  16588. BABYLON.serialize()
  16589. ], Camera.prototype, "fovMode", void 0);
  16590. __decorate([
  16591. BABYLON.serialize()
  16592. ], Camera.prototype, "cameraRigMode", void 0);
  16593. __decorate([
  16594. BABYLON.serialize()
  16595. ], Camera.prototype, "interaxialDistance", void 0);
  16596. __decorate([
  16597. BABYLON.serialize()
  16598. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16599. return Camera;
  16600. }(BABYLON.Node));
  16601. BABYLON.Camera = Camera;
  16602. })(BABYLON || (BABYLON = {}));
  16603. //# sourceMappingURL=babylon.camera.js.map
  16604. var BABYLON;
  16605. (function (BABYLON) {
  16606. var RenderingManager = /** @class */ (function () {
  16607. function RenderingManager(scene) {
  16608. this._renderingGroups = new Array();
  16609. this._autoClearDepthStencil = {};
  16610. this._customOpaqueSortCompareFn = {};
  16611. this._customAlphaTestSortCompareFn = {};
  16612. this._customTransparentSortCompareFn = {};
  16613. this._renderinGroupInfo = null;
  16614. this._scene = scene;
  16615. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16616. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16617. }
  16618. }
  16619. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16620. if (depth === void 0) { depth = true; }
  16621. if (stencil === void 0) { stencil = true; }
  16622. if (this._depthStencilBufferAlreadyCleaned) {
  16623. return;
  16624. }
  16625. this._scene.getEngine().clear(null, false, depth, stencil);
  16626. this._depthStencilBufferAlreadyCleaned = true;
  16627. };
  16628. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16629. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16630. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16631. var info = null;
  16632. if (observable) {
  16633. if (!this._renderinGroupInfo) {
  16634. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16635. }
  16636. info = this._renderinGroupInfo;
  16637. info.scene = this._scene;
  16638. info.camera = this._scene.activeCamera;
  16639. }
  16640. // Dispatch sprites
  16641. if (renderSprites) {
  16642. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16643. var manager = this._scene.spriteManagers[index];
  16644. this.dispatchSprites(manager);
  16645. }
  16646. }
  16647. // Render
  16648. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16649. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16650. var renderingGroup = this._renderingGroups[index];
  16651. if (!renderingGroup && !observable)
  16652. continue;
  16653. this._currentIndex = index;
  16654. var renderingGroupMask = 0;
  16655. // Fire PRECLEAR stage
  16656. if (observable && info) {
  16657. renderingGroupMask = Math.pow(2, index);
  16658. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16659. info.renderingGroupId = index;
  16660. observable.notifyObservers(info, renderingGroupMask);
  16661. }
  16662. // Clear depth/stencil if needed
  16663. if (RenderingManager.AUTOCLEAR) {
  16664. var autoClear = this._autoClearDepthStencil[index];
  16665. if (autoClear && autoClear.autoClear) {
  16666. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16667. }
  16668. }
  16669. if (observable && info) {
  16670. // Fire PREOPAQUE stage
  16671. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16672. observable.notifyObservers(info, renderingGroupMask);
  16673. // Fire PRETRANSPARENT stage
  16674. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16675. observable.notifyObservers(info, renderingGroupMask);
  16676. }
  16677. if (renderingGroup)
  16678. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16679. // Fire POSTTRANSPARENT stage
  16680. if (observable && info) {
  16681. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16682. observable.notifyObservers(info, renderingGroupMask);
  16683. }
  16684. }
  16685. };
  16686. RenderingManager.prototype.reset = function () {
  16687. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16688. var renderingGroup = this._renderingGroups[index];
  16689. if (renderingGroup) {
  16690. renderingGroup.prepare();
  16691. }
  16692. }
  16693. };
  16694. RenderingManager.prototype.dispose = function () {
  16695. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16696. var renderingGroup = this._renderingGroups[index];
  16697. if (renderingGroup) {
  16698. renderingGroup.dispose();
  16699. }
  16700. }
  16701. this._renderingGroups.length = 0;
  16702. };
  16703. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16704. if (!this._renderingGroups[renderingGroupId]) {
  16705. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16706. }
  16707. };
  16708. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16709. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16710. this._prepareRenderingGroup(renderingGroupId);
  16711. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16712. };
  16713. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16714. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16715. this._prepareRenderingGroup(renderingGroupId);
  16716. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16717. };
  16718. RenderingManager.prototype.dispatch = function (subMesh) {
  16719. var mesh = subMesh.getMesh();
  16720. var renderingGroupId = mesh.renderingGroupId || 0;
  16721. this._prepareRenderingGroup(renderingGroupId);
  16722. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16723. };
  16724. /**
  16725. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16726. * This allowed control for front to back rendering or reversly depending of the special needs.
  16727. *
  16728. * @param renderingGroupId The rendering group id corresponding to its index
  16729. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16730. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16731. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16732. */
  16733. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16734. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16735. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16736. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16737. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16738. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16739. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16740. if (this._renderingGroups[renderingGroupId]) {
  16741. var group = this._renderingGroups[renderingGroupId];
  16742. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16743. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16744. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16745. }
  16746. };
  16747. /**
  16748. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16749. *
  16750. * @param renderingGroupId The rendering group id corresponding to its index
  16751. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16752. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16753. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16754. */
  16755. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16756. if (depth === void 0) { depth = true; }
  16757. if (stencil === void 0) { stencil = true; }
  16758. this._autoClearDepthStencil[renderingGroupId] = {
  16759. autoClear: autoClearDepthStencil,
  16760. depth: depth,
  16761. stencil: stencil
  16762. };
  16763. };
  16764. /**
  16765. * The max id used for rendering groups (not included)
  16766. */
  16767. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16768. /**
  16769. * The min id used for rendering groups (included)
  16770. */
  16771. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16772. /**
  16773. * Used to globally prevent autoclearing scenes.
  16774. */
  16775. RenderingManager.AUTOCLEAR = true;
  16776. return RenderingManager;
  16777. }());
  16778. BABYLON.RenderingManager = RenderingManager;
  16779. })(BABYLON || (BABYLON = {}));
  16780. //# sourceMappingURL=babylon.renderingManager.js.map
  16781. var BABYLON;
  16782. (function (BABYLON) {
  16783. var RenderingGroup = /** @class */ (function () {
  16784. /**
  16785. * Creates a new rendering group.
  16786. * @param index The rendering group index
  16787. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16788. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16789. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16790. */
  16791. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16792. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16793. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16794. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16795. this.index = index;
  16796. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16797. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16798. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16799. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16800. this._particleSystems = new BABYLON.SmartArray(256);
  16801. this._spriteManagers = new BABYLON.SmartArray(256);
  16802. this._edgesRenderers = new BABYLON.SmartArray(16);
  16803. this._scene = scene;
  16804. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16805. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16806. this.transparentSortCompareFn = transparentSortCompareFn;
  16807. }
  16808. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16809. /**
  16810. * Set the opaque sort comparison function.
  16811. * If null the sub meshes will be render in the order they were created
  16812. */
  16813. set: function (value) {
  16814. this._opaqueSortCompareFn = value;
  16815. if (value) {
  16816. this._renderOpaque = this.renderOpaqueSorted;
  16817. }
  16818. else {
  16819. this._renderOpaque = RenderingGroup.renderUnsorted;
  16820. }
  16821. },
  16822. enumerable: true,
  16823. configurable: true
  16824. });
  16825. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16826. /**
  16827. * Set the alpha test sort comparison function.
  16828. * If null the sub meshes will be render in the order they were created
  16829. */
  16830. set: function (value) {
  16831. this._alphaTestSortCompareFn = value;
  16832. if (value) {
  16833. this._renderAlphaTest = this.renderAlphaTestSorted;
  16834. }
  16835. else {
  16836. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16837. }
  16838. },
  16839. enumerable: true,
  16840. configurable: true
  16841. });
  16842. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16843. /**
  16844. * Set the transparent sort comparison function.
  16845. * If null the sub meshes will be render in the order they were created
  16846. */
  16847. set: function (value) {
  16848. if (value) {
  16849. this._transparentSortCompareFn = value;
  16850. }
  16851. else {
  16852. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16853. }
  16854. this._renderTransparent = this.renderTransparentSorted;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. /**
  16860. * Render all the sub meshes contained in the group.
  16861. * @param customRenderFunction Used to override the default render behaviour of the group.
  16862. * @returns true if rendered some submeshes.
  16863. */
  16864. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16865. if (customRenderFunction) {
  16866. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16867. return;
  16868. }
  16869. var engine = this._scene.getEngine();
  16870. // Depth only
  16871. if (this._depthOnlySubMeshes.length !== 0) {
  16872. engine.setAlphaTesting(true);
  16873. engine.setColorWrite(false);
  16874. this._renderAlphaTest(this._depthOnlySubMeshes);
  16875. engine.setAlphaTesting(false);
  16876. engine.setColorWrite(true);
  16877. }
  16878. // Opaque
  16879. if (this._opaqueSubMeshes.length !== 0) {
  16880. this._renderOpaque(this._opaqueSubMeshes);
  16881. }
  16882. // Alpha test
  16883. if (this._alphaTestSubMeshes.length !== 0) {
  16884. engine.setAlphaTesting(true);
  16885. this._renderAlphaTest(this._alphaTestSubMeshes);
  16886. engine.setAlphaTesting(false);
  16887. }
  16888. var stencilState = engine.getStencilBuffer();
  16889. engine.setStencilBuffer(false);
  16890. // Sprites
  16891. if (renderSprites) {
  16892. this._renderSprites();
  16893. }
  16894. // Particles
  16895. if (renderParticles) {
  16896. this._renderParticles(activeMeshes);
  16897. }
  16898. if (this.onBeforeTransparentRendering) {
  16899. this.onBeforeTransparentRendering();
  16900. }
  16901. // Transparent
  16902. if (this._transparentSubMeshes.length !== 0) {
  16903. this._renderTransparent(this._transparentSubMeshes);
  16904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16905. }
  16906. // Set back stencil to false in case it changes before the edge renderer.
  16907. engine.setStencilBuffer(false);
  16908. // Edges
  16909. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16910. this._edgesRenderers.data[edgesRendererIndex].render();
  16911. }
  16912. // Restore Stencil state.
  16913. engine.setStencilBuffer(stencilState);
  16914. };
  16915. /**
  16916. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16917. * @param subMeshes The submeshes to render
  16918. */
  16919. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16920. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  16921. };
  16922. /**
  16923. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16924. * @param subMeshes The submeshes to render
  16925. */
  16926. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16927. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  16928. };
  16929. /**
  16930. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16931. * @param subMeshes The submeshes to render
  16932. */
  16933. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16934. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  16935. };
  16936. /**
  16937. * Renders the submeshes in a specified order.
  16938. * @param subMeshes The submeshes to sort before render
  16939. * @param sortCompareFn The comparison function use to sort
  16940. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16941. * @param transparent Specifies to activate blending if true
  16942. */
  16943. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  16944. var subIndex = 0;
  16945. var subMesh;
  16946. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  16947. for (; subIndex < subMeshes.length; subIndex++) {
  16948. subMesh = subMeshes.data[subIndex];
  16949. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16950. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16951. }
  16952. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16953. if (sortCompareFn) {
  16954. sortedArray.sort(sortCompareFn);
  16955. }
  16956. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16957. subMesh = sortedArray[subIndex];
  16958. if (transparent) {
  16959. var material = subMesh.getMaterial();
  16960. if (material && material.needDepthPrePass) {
  16961. var engine = material.getScene().getEngine();
  16962. engine.setColorWrite(false);
  16963. engine.setAlphaTesting(true);
  16964. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16965. subMesh.render(false);
  16966. engine.setAlphaTesting(false);
  16967. engine.setColorWrite(true);
  16968. }
  16969. }
  16970. subMesh.render(transparent);
  16971. }
  16972. };
  16973. /**
  16974. * Renders the submeshes in the order they were dispatched (no sort applied).
  16975. * @param subMeshes The submeshes to render
  16976. */
  16977. RenderingGroup.renderUnsorted = function (subMeshes) {
  16978. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16979. var submesh = subMeshes.data[subIndex];
  16980. submesh.render(false);
  16981. }
  16982. };
  16983. /**
  16984. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16985. * are rendered back to front if in the same alpha index.
  16986. *
  16987. * @param a The first submesh
  16988. * @param b The second submesh
  16989. * @returns The result of the comparison
  16990. */
  16991. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16992. // Alpha index first
  16993. if (a._alphaIndex > b._alphaIndex) {
  16994. return 1;
  16995. }
  16996. if (a._alphaIndex < b._alphaIndex) {
  16997. return -1;
  16998. }
  16999. // Then distance to camera
  17000. return RenderingGroup.backToFrontSortCompare(a, b);
  17001. };
  17002. /**
  17003. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17004. * are rendered back to front.
  17005. *
  17006. * @param a The first submesh
  17007. * @param b The second submesh
  17008. * @returns The result of the comparison
  17009. */
  17010. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17011. // Then distance to camera
  17012. if (a._distanceToCamera < b._distanceToCamera) {
  17013. return 1;
  17014. }
  17015. if (a._distanceToCamera > b._distanceToCamera) {
  17016. return -1;
  17017. }
  17018. return 0;
  17019. };
  17020. /**
  17021. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17022. * are rendered front to back (prevent overdraw).
  17023. *
  17024. * @param a The first submesh
  17025. * @param b The second submesh
  17026. * @returns The result of the comparison
  17027. */
  17028. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17029. // Then distance to camera
  17030. if (a._distanceToCamera < b._distanceToCamera) {
  17031. return -1;
  17032. }
  17033. if (a._distanceToCamera > b._distanceToCamera) {
  17034. return 1;
  17035. }
  17036. return 0;
  17037. };
  17038. /**
  17039. * Resets the different lists of submeshes to prepare a new frame.
  17040. */
  17041. RenderingGroup.prototype.prepare = function () {
  17042. this._opaqueSubMeshes.reset();
  17043. this._transparentSubMeshes.reset();
  17044. this._alphaTestSubMeshes.reset();
  17045. this._depthOnlySubMeshes.reset();
  17046. this._particleSystems.reset();
  17047. this._spriteManagers.reset();
  17048. this._edgesRenderers.reset();
  17049. };
  17050. RenderingGroup.prototype.dispose = function () {
  17051. this._opaqueSubMeshes.dispose();
  17052. this._transparentSubMeshes.dispose();
  17053. this._alphaTestSubMeshes.dispose();
  17054. this._depthOnlySubMeshes.dispose();
  17055. this._particleSystems.dispose();
  17056. this._spriteManagers.dispose();
  17057. this._edgesRenderers.dispose();
  17058. };
  17059. /**
  17060. * Inserts the submesh in its correct queue depending on its material.
  17061. * @param subMesh The submesh to dispatch
  17062. */
  17063. RenderingGroup.prototype.dispatch = function (subMesh) {
  17064. var material = subMesh.getMaterial();
  17065. var mesh = subMesh.getMesh();
  17066. if (!material) {
  17067. return;
  17068. }
  17069. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17070. this._transparentSubMeshes.push(subMesh);
  17071. }
  17072. else if (material.needAlphaTesting()) {
  17073. if (material.needDepthPrePass) {
  17074. this._depthOnlySubMeshes.push(subMesh);
  17075. }
  17076. this._alphaTestSubMeshes.push(subMesh);
  17077. }
  17078. else {
  17079. if (material.needDepthPrePass) {
  17080. this._depthOnlySubMeshes.push(subMesh);
  17081. }
  17082. this._opaqueSubMeshes.push(subMesh); // Opaque
  17083. }
  17084. if (mesh._edgesRenderer) {
  17085. this._edgesRenderers.push(mesh._edgesRenderer);
  17086. }
  17087. };
  17088. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17089. this._spriteManagers.push(spriteManager);
  17090. };
  17091. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17092. this._particleSystems.push(particleSystem);
  17093. };
  17094. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17095. if (this._particleSystems.length === 0) {
  17096. return;
  17097. }
  17098. // Particles
  17099. var activeCamera = this._scene.activeCamera;
  17100. this._scene._particlesDuration.beginMonitoring();
  17101. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17102. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17103. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17104. continue;
  17105. }
  17106. var emitter = particleSystem.emitter;
  17107. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17108. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17109. }
  17110. }
  17111. this._scene._particlesDuration.endMonitoring(false);
  17112. };
  17113. RenderingGroup.prototype._renderSprites = function () {
  17114. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17115. return;
  17116. }
  17117. // Sprites
  17118. var activeCamera = this._scene.activeCamera;
  17119. this._scene._spritesDuration.beginMonitoring();
  17120. for (var id = 0; id < this._spriteManagers.length; id++) {
  17121. var spriteManager = this._spriteManagers.data[id];
  17122. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17123. spriteManager.render();
  17124. }
  17125. }
  17126. this._scene._spritesDuration.endMonitoring(false);
  17127. };
  17128. return RenderingGroup;
  17129. }());
  17130. BABYLON.RenderingGroup = RenderingGroup;
  17131. })(BABYLON || (BABYLON = {}));
  17132. //# sourceMappingURL=babylon.renderingGroup.js.map
  17133. var BABYLON;
  17134. (function (BABYLON) {
  17135. var ClickInfo = /** @class */ (function () {
  17136. function ClickInfo() {
  17137. this._singleClick = false;
  17138. this._doubleClick = false;
  17139. this._hasSwiped = false;
  17140. this._ignore = false;
  17141. }
  17142. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17143. get: function () {
  17144. return this._singleClick;
  17145. },
  17146. set: function (b) {
  17147. this._singleClick = b;
  17148. },
  17149. enumerable: true,
  17150. configurable: true
  17151. });
  17152. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17153. get: function () {
  17154. return this._doubleClick;
  17155. },
  17156. set: function (b) {
  17157. this._doubleClick = b;
  17158. },
  17159. enumerable: true,
  17160. configurable: true
  17161. });
  17162. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17163. get: function () {
  17164. return this._hasSwiped;
  17165. },
  17166. set: function (b) {
  17167. this._hasSwiped = b;
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17173. get: function () {
  17174. return this._ignore;
  17175. },
  17176. set: function (b) {
  17177. this._ignore = b;
  17178. },
  17179. enumerable: true,
  17180. configurable: true
  17181. });
  17182. return ClickInfo;
  17183. }());
  17184. /**
  17185. * This class is used by the onRenderingGroupObservable
  17186. */
  17187. var RenderingGroupInfo = /** @class */ (function () {
  17188. function RenderingGroupInfo() {
  17189. }
  17190. /**
  17191. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17192. * This stage will be fired no matter what
  17193. */
  17194. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17195. /**
  17196. * Called before opaque object are rendered.
  17197. * This stage will be fired only if there's 3D Opaque content to render
  17198. */
  17199. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17200. /**
  17201. * Called after the opaque objects are rendered and before the transparent ones
  17202. * This stage will be fired only if there's 3D transparent content to render
  17203. */
  17204. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17205. /**
  17206. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17207. * This stage will be fired no matter what
  17208. */
  17209. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17210. return RenderingGroupInfo;
  17211. }());
  17212. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17213. /**
  17214. * Represents a scene to be rendered by the engine.
  17215. * @see http://doc.babylonjs.com/page.php?p=21911
  17216. */
  17217. var Scene = /** @class */ (function () {
  17218. /**
  17219. * @constructor
  17220. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17221. */
  17222. function Scene(engine) {
  17223. // Members
  17224. this.autoClear = true;
  17225. this.autoClearDepthAndStencil = true;
  17226. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17227. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17228. this.forceWireframe = false;
  17229. this._forcePointsCloud = false;
  17230. this.forceShowBoundingBoxes = false;
  17231. this.animationsEnabled = true;
  17232. this.constantlyUpdateMeshUnderPointer = false;
  17233. this.hoverCursor = "pointer";
  17234. this.defaultCursor = "";
  17235. /**
  17236. * This is used to call preventDefault() on pointer down
  17237. * in order to block unwanted artifacts like system double clicks
  17238. */
  17239. this.preventDefaultOnPointerDown = true;
  17240. // Metadata
  17241. this.metadata = null;
  17242. /**
  17243. * An event triggered when the scene is disposed.
  17244. * @type {BABYLON.Observable}
  17245. */
  17246. this.onDisposeObservable = new BABYLON.Observable();
  17247. /**
  17248. * An event triggered before rendering the scene
  17249. * @type {BABYLON.Observable}
  17250. */
  17251. this.onBeforeRenderObservable = new BABYLON.Observable();
  17252. /**
  17253. * An event triggered after rendering the scene
  17254. * @type {BABYLON.Observable}
  17255. */
  17256. this.onAfterRenderObservable = new BABYLON.Observable();
  17257. /**
  17258. * An event triggered when the scene is ready
  17259. * @type {BABYLON.Observable}
  17260. */
  17261. this.onReadyObservable = new BABYLON.Observable();
  17262. /**
  17263. * An event triggered before rendering a camera
  17264. * @type {BABYLON.Observable}
  17265. */
  17266. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17267. /**
  17268. * An event triggered after rendering a camera
  17269. * @type {BABYLON.Observable}
  17270. */
  17271. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17272. /**
  17273. * An event triggered when active meshes evaluation is about to start
  17274. * @type {BABYLON.Observable}
  17275. */
  17276. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17277. /**
  17278. * An event triggered when active meshes evaluation is done
  17279. * @type {BABYLON.Observable}
  17280. */
  17281. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17282. /**
  17283. * An event triggered when a camera is created
  17284. * @type {BABYLON.Observable}
  17285. */
  17286. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17287. /**
  17288. * An event triggered when a camera is removed
  17289. * @type {BABYLON.Observable}
  17290. */
  17291. this.onCameraRemovedObservable = new BABYLON.Observable();
  17292. /**
  17293. * An event triggered when a light is created
  17294. * @type {BABYLON.Observable}
  17295. */
  17296. this.onNewLightAddedObservable = new BABYLON.Observable();
  17297. /**
  17298. * An event triggered when a light is removed
  17299. * @type {BABYLON.Observable}
  17300. */
  17301. this.onLightRemovedObservable = new BABYLON.Observable();
  17302. /**
  17303. * An event triggered when a geometry is created
  17304. * @type {BABYLON.Observable}
  17305. */
  17306. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17307. /**
  17308. * An event triggered when a geometry is removed
  17309. * @type {BABYLON.Observable}
  17310. */
  17311. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17312. /**
  17313. * An event triggered when a mesh is created
  17314. * @type {BABYLON.Observable}
  17315. */
  17316. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17317. /**
  17318. * An event triggered when a mesh is removed
  17319. * @type {BABYLON.Observable}
  17320. */
  17321. this.onMeshRemovedObservable = new BABYLON.Observable();
  17322. /**
  17323. * An event triggered when render targets are about to be rendered
  17324. * Can happen multiple times per frame.
  17325. * @type {BABYLON.Observable}
  17326. */
  17327. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17328. /**
  17329. * An event triggered when render targets were rendered.
  17330. * Can happen multiple times per frame.
  17331. * @type {BABYLON.Observable}
  17332. */
  17333. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17334. /**
  17335. * An event triggered before calculating deterministic simulation step
  17336. * @type {BABYLON.Observable}
  17337. */
  17338. this.onBeforeStepObservable = new BABYLON.Observable();
  17339. /**
  17340. * An event triggered after calculating deterministic simulation step
  17341. * @type {BABYLON.Observable}
  17342. */
  17343. this.onAfterStepObservable = new BABYLON.Observable();
  17344. /**
  17345. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17346. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17347. * 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)
  17348. */
  17349. this.onRenderingGroupObservable = new BABYLON.Observable();
  17350. // Animations
  17351. this.animations = [];
  17352. /**
  17353. * 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).
  17354. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17355. */
  17356. this.onPrePointerObservable = new BABYLON.Observable();
  17357. /**
  17358. * Observable event triggered each time an input event is received from the rendering canvas
  17359. */
  17360. this.onPointerObservable = new BABYLON.Observable();
  17361. this._meshPickProceed = false;
  17362. this._previousHasSwiped = false;
  17363. this._currentPickResult = null;
  17364. this._previousPickResult = null;
  17365. this._totalPointersPressed = 0;
  17366. this._doubleClickOccured = false;
  17367. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17368. this.cameraToUseForPointers = null;
  17369. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17370. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17371. this._startingPointerTime = 0;
  17372. this._previousStartingPointerTime = 0;
  17373. // Deterministic lockstep
  17374. this._timeAccumulator = 0;
  17375. this._currentStepId = 0;
  17376. this._currentInternalStep = 0;
  17377. // Keyboard
  17378. /**
  17379. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17380. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17381. */
  17382. this.onPreKeyboardObservable = new BABYLON.Observable();
  17383. /**
  17384. * Observable event triggered each time an keyboard event is received from the hosting window
  17385. */
  17386. this.onKeyboardObservable = new BABYLON.Observable();
  17387. // Coordinate system
  17388. /**
  17389. * use right-handed coordinate system on this scene.
  17390. * @type {boolean}
  17391. */
  17392. this._useRightHandedSystem = false;
  17393. // Fog
  17394. this._fogEnabled = true;
  17395. this._fogMode = Scene.FOGMODE_NONE;
  17396. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17397. this.fogDensity = 0.1;
  17398. this.fogStart = 0;
  17399. this.fogEnd = 1000.0;
  17400. // Lights
  17401. /**
  17402. * is shadow enabled on this scene.
  17403. * @type {boolean}
  17404. */
  17405. this._shadowsEnabled = true;
  17406. /**
  17407. * is light enabled on this scene.
  17408. * @type {boolean}
  17409. */
  17410. this._lightsEnabled = true;
  17411. /**
  17412. * All of the lights added to this scene.
  17413. * @see BABYLON.Light
  17414. * @type {BABYLON.Light[]}
  17415. */
  17416. this.lights = new Array();
  17417. // Cameras
  17418. /** All of the cameras added to this scene. */
  17419. this.cameras = new Array();
  17420. /** All of the active cameras added to this scene. */
  17421. this.activeCameras = new Array();
  17422. // Meshes
  17423. /**
  17424. * All of the (abstract) meshes added to this scene.
  17425. * @see BABYLON.AbstractMesh
  17426. * @type {BABYLON.AbstractMesh[]}
  17427. */
  17428. this.meshes = new Array();
  17429. // Geometries
  17430. this._geometries = new Array();
  17431. this.materials = new Array();
  17432. this.multiMaterials = new Array();
  17433. // Textures
  17434. this._texturesEnabled = true;
  17435. this.textures = new Array();
  17436. // Particles
  17437. this.particlesEnabled = true;
  17438. this.particleSystems = new Array();
  17439. // Sprites
  17440. this.spritesEnabled = true;
  17441. this.spriteManagers = new Array();
  17442. // Layers
  17443. this.layers = new Array();
  17444. this.highlightLayers = new Array();
  17445. // Skeletons
  17446. this._skeletonsEnabled = true;
  17447. this.skeletons = new Array();
  17448. // Morph targets
  17449. this.morphTargetManagers = new Array();
  17450. // Lens flares
  17451. this.lensFlaresEnabled = true;
  17452. this.lensFlareSystems = new Array();
  17453. // Collisions
  17454. this.collisionsEnabled = true;
  17455. /** Defines the gravity applied to this scene */
  17456. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17457. // Postprocesses
  17458. this.postProcesses = new Array();
  17459. this.postProcessesEnabled = true;
  17460. // Customs render targets
  17461. this.renderTargetsEnabled = true;
  17462. this.dumpNextRenderTargets = false;
  17463. this.customRenderTargets = new Array();
  17464. // Imported meshes
  17465. this.importedMeshesFiles = new Array();
  17466. // Probes
  17467. this.probesEnabled = true;
  17468. this.reflectionProbes = new Array();
  17469. this._actionManagers = new Array();
  17470. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17471. // Procedural textures
  17472. this.proceduralTexturesEnabled = true;
  17473. this._proceduralTextures = new Array();
  17474. this.soundTracks = new Array();
  17475. this._audioEnabled = true;
  17476. this._headphone = false;
  17477. // Performance counters
  17478. this._totalVertices = new BABYLON.PerfCounter();
  17479. this._activeIndices = new BABYLON.PerfCounter();
  17480. this._activeParticles = new BABYLON.PerfCounter();
  17481. this._interFrameDuration = new BABYLON.PerfCounter();
  17482. this._lastFrameDuration = new BABYLON.PerfCounter();
  17483. this._particlesDuration = new BABYLON.PerfCounter();
  17484. this._renderDuration = new BABYLON.PerfCounter();
  17485. this._spritesDuration = new BABYLON.PerfCounter();
  17486. this._activeBones = new BABYLON.PerfCounter();
  17487. this._animationTime = 0;
  17488. this.animationTimeScale = 1;
  17489. this._renderId = 0;
  17490. this._executeWhenReadyTimeoutId = -1;
  17491. this._intermediateRendering = false;
  17492. this._viewUpdateFlag = -1;
  17493. this._projectionUpdateFlag = -1;
  17494. this._alternateViewUpdateFlag = -1;
  17495. this._alternateProjectionUpdateFlag = -1;
  17496. this._toBeDisposed = new BABYLON.SmartArray(256);
  17497. this._pendingData = new Array();
  17498. this._isDisposed = false;
  17499. this._activeMeshes = new BABYLON.SmartArray(256);
  17500. this._processedMaterials = new BABYLON.SmartArray(256);
  17501. this._renderTargets = new BABYLON.SmartArray(256);
  17502. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17503. this._activeSkeletons = new BABYLON.SmartArray(32);
  17504. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17505. this._activeAnimatables = new Array();
  17506. this._transformMatrix = BABYLON.Matrix.Zero();
  17507. this._useAlternateCameraConfiguration = false;
  17508. this._alternateRendering = false;
  17509. this.requireLightSorting = false;
  17510. this._activeMeshesFrozen = false;
  17511. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17512. this._engine.scenes.push(this);
  17513. this._uid = null;
  17514. this._renderingManager = new BABYLON.RenderingManager(this);
  17515. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17516. if (BABYLON.OutlineRenderer) {
  17517. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17518. }
  17519. if (BABYLON.Tools.IsWindowObjectExist()) {
  17520. this.attachControl();
  17521. }
  17522. //simplification queue
  17523. if (BABYLON.SimplificationQueue) {
  17524. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17525. }
  17526. //collision coordinator initialization. For now legacy per default.
  17527. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17528. // Uniform Buffer
  17529. this._createUbo();
  17530. // Default Image processing definition.
  17531. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17532. }
  17533. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17534. /** The fog is deactivated */
  17535. get: function () {
  17536. return Scene._FOGMODE_NONE;
  17537. },
  17538. enumerable: true,
  17539. configurable: true
  17540. });
  17541. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17542. /** The fog density is following an exponential function */
  17543. get: function () {
  17544. return Scene._FOGMODE_EXP;
  17545. },
  17546. enumerable: true,
  17547. configurable: true
  17548. });
  17549. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17550. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17551. get: function () {
  17552. return Scene._FOGMODE_EXP2;
  17553. },
  17554. enumerable: true,
  17555. configurable: true
  17556. });
  17557. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17558. /** The fog density is following a linear function. */
  17559. get: function () {
  17560. return Scene._FOGMODE_LINEAR;
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17566. /**
  17567. * Texture used in all pbr material as the reflection texture.
  17568. * As in the majority of the scene they are the same (exception for multi room and so on),
  17569. * this is easier to reference from here than from all the materials.
  17570. */
  17571. get: function () {
  17572. return this._environmentTexture;
  17573. },
  17574. /**
  17575. * Texture used in all pbr material as the reflection texture.
  17576. * As in the majority of the scene they are the same (exception for multi room and so on),
  17577. * this is easier to set here than in all the materials.
  17578. */
  17579. set: function (value) {
  17580. if (this._environmentTexture === value) {
  17581. return;
  17582. }
  17583. this._environmentTexture = value;
  17584. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17590. /**
  17591. * Default image processing configuration used either in the rendering
  17592. * Forward main pass or through the imageProcessingPostProcess if present.
  17593. * As in the majority of the scene they are the same (exception for multi camera),
  17594. * this is easier to reference from here than from all the materials and post process.
  17595. *
  17596. * No setter as we it is a shared configuration, you can set the values instead.
  17597. */
  17598. get: function () {
  17599. return this._imageProcessingConfiguration;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17605. get: function () {
  17606. return this._forcePointsCloud;
  17607. },
  17608. set: function (value) {
  17609. if (this._forcePointsCloud === value) {
  17610. return;
  17611. }
  17612. this._forcePointsCloud = value;
  17613. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(Scene.prototype, "onDispose", {
  17619. /** A function to be executed when this scene is disposed. */
  17620. set: function (callback) {
  17621. if (this._onDisposeObserver) {
  17622. this.onDisposeObservable.remove(this._onDisposeObserver);
  17623. }
  17624. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. Object.defineProperty(Scene.prototype, "beforeRender", {
  17630. /** A function to be executed before rendering this scene */
  17631. set: function (callback) {
  17632. if (this._onBeforeRenderObserver) {
  17633. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17634. }
  17635. if (callback) {
  17636. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17637. }
  17638. },
  17639. enumerable: true,
  17640. configurable: true
  17641. });
  17642. Object.defineProperty(Scene.prototype, "afterRender", {
  17643. /** A function to be executed after rendering this scene */
  17644. set: function (callback) {
  17645. if (this._onAfterRenderObserver) {
  17646. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17647. }
  17648. if (callback) {
  17649. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17650. }
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17656. set: function (callback) {
  17657. if (this._onBeforeCameraRenderObserver) {
  17658. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17659. }
  17660. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17661. },
  17662. enumerable: true,
  17663. configurable: true
  17664. });
  17665. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17666. set: function (callback) {
  17667. if (this._onAfterCameraRenderObserver) {
  17668. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17669. }
  17670. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17676. get: function () {
  17677. if (!this._gamepadManager) {
  17678. this._gamepadManager = new BABYLON.GamepadManager();
  17679. }
  17680. return this._gamepadManager;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17686. get: function () {
  17687. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17693. get: function () {
  17694. return this._useRightHandedSystem;
  17695. },
  17696. set: function (value) {
  17697. if (this._useRightHandedSystem === value) {
  17698. return;
  17699. }
  17700. this._useRightHandedSystem = value;
  17701. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Scene.prototype.setStepId = function (newStepId) {
  17707. this._currentStepId = newStepId;
  17708. };
  17709. ;
  17710. Scene.prototype.getStepId = function () {
  17711. return this._currentStepId;
  17712. };
  17713. ;
  17714. Scene.prototype.getInternalStep = function () {
  17715. return this._currentInternalStep;
  17716. };
  17717. ;
  17718. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17719. get: function () {
  17720. return this._fogEnabled;
  17721. },
  17722. /**
  17723. * is fog enabled on this scene.
  17724. */
  17725. set: function (value) {
  17726. if (this._fogEnabled === value) {
  17727. return;
  17728. }
  17729. this._fogEnabled = value;
  17730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. Object.defineProperty(Scene.prototype, "fogMode", {
  17736. get: function () {
  17737. return this._fogMode;
  17738. },
  17739. set: function (value) {
  17740. if (this._fogMode === value) {
  17741. return;
  17742. }
  17743. this._fogMode = value;
  17744. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17750. get: function () {
  17751. return this._shadowsEnabled;
  17752. },
  17753. set: function (value) {
  17754. if (this._shadowsEnabled === value) {
  17755. return;
  17756. }
  17757. this._shadowsEnabled = value;
  17758. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17764. get: function () {
  17765. return this._lightsEnabled;
  17766. },
  17767. set: function (value) {
  17768. if (this._lightsEnabled === value) {
  17769. return;
  17770. }
  17771. this._lightsEnabled = value;
  17772. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17778. /** The default material used on meshes when no material is affected */
  17779. get: function () {
  17780. if (!this._defaultMaterial) {
  17781. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17782. }
  17783. return this._defaultMaterial;
  17784. },
  17785. /** The default material used on meshes when no material is affected */
  17786. set: function (value) {
  17787. this._defaultMaterial = value;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17793. get: function () {
  17794. return this._texturesEnabled;
  17795. },
  17796. set: function (value) {
  17797. if (this._texturesEnabled === value) {
  17798. return;
  17799. }
  17800. this._texturesEnabled = value;
  17801. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17802. },
  17803. enumerable: true,
  17804. configurable: true
  17805. });
  17806. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17807. get: function () {
  17808. return this._skeletonsEnabled;
  17809. },
  17810. set: function (value) {
  17811. if (this._skeletonsEnabled === value) {
  17812. return;
  17813. }
  17814. this._skeletonsEnabled = value;
  17815. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17821. get: function () {
  17822. if (!this._postProcessRenderPipelineManager) {
  17823. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17824. }
  17825. return this._postProcessRenderPipelineManager;
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17831. get: function () {
  17832. if (!this._mainSoundTrack) {
  17833. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17834. }
  17835. return this._mainSoundTrack;
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17841. get: function () {
  17842. return this._alternateRendering;
  17843. },
  17844. enumerable: true,
  17845. configurable: true
  17846. });
  17847. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17848. get: function () {
  17849. return this._frustumPlanes;
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. Object.defineProperty(Scene.prototype, "debugLayer", {
  17855. // Properties
  17856. get: function () {
  17857. if (!this._debugLayer) {
  17858. this._debugLayer = new BABYLON.DebugLayer(this);
  17859. }
  17860. return this._debugLayer;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17866. get: function () {
  17867. return this._workerCollisions;
  17868. },
  17869. set: function (enabled) {
  17870. if (!BABYLON.CollisionCoordinatorLegacy) {
  17871. return;
  17872. }
  17873. enabled = (enabled && !!Worker);
  17874. this._workerCollisions = enabled;
  17875. if (this.collisionCoordinator) {
  17876. this.collisionCoordinator.destroy();
  17877. }
  17878. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17879. this.collisionCoordinator.init(this);
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17885. get: function () {
  17886. return this._selectionOctree;
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17892. /**
  17893. * The mesh that is currently under the pointer.
  17894. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17895. */
  17896. get: function () {
  17897. return this._pointerOverMesh;
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(Scene.prototype, "pointerX", {
  17903. /**
  17904. * Current on-screen X position of the pointer
  17905. * @return {number} X position of the pointer
  17906. */
  17907. get: function () {
  17908. return this._pointerX;
  17909. },
  17910. enumerable: true,
  17911. configurable: true
  17912. });
  17913. Object.defineProperty(Scene.prototype, "pointerY", {
  17914. /**
  17915. * Current on-screen Y position of the pointer
  17916. * @return {number} Y position of the pointer
  17917. */
  17918. get: function () {
  17919. return this._pointerY;
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Scene.prototype.getCachedMaterial = function () {
  17925. return this._cachedMaterial;
  17926. };
  17927. Scene.prototype.getCachedEffect = function () {
  17928. return this._cachedEffect;
  17929. };
  17930. Scene.prototype.getCachedVisibility = function () {
  17931. return this._cachedVisibility;
  17932. };
  17933. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17934. if (visibility === void 0) { visibility = 1; }
  17935. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17936. };
  17937. Scene.prototype.getBoundingBoxRenderer = function () {
  17938. if (!this._boundingBoxRenderer) {
  17939. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17940. }
  17941. return this._boundingBoxRenderer;
  17942. };
  17943. Scene.prototype.getOutlineRenderer = function () {
  17944. return this._outlineRenderer;
  17945. };
  17946. Scene.prototype.getEngine = function () {
  17947. return this._engine;
  17948. };
  17949. Scene.prototype.getTotalVertices = function () {
  17950. return this._totalVertices.current;
  17951. };
  17952. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17953. get: function () {
  17954. return this._totalVertices;
  17955. },
  17956. enumerable: true,
  17957. configurable: true
  17958. });
  17959. Scene.prototype.getActiveIndices = function () {
  17960. return this._activeIndices.current;
  17961. };
  17962. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17963. get: function () {
  17964. return this._activeIndices;
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Scene.prototype.getActiveParticles = function () {
  17970. return this._activeParticles.current;
  17971. };
  17972. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17973. get: function () {
  17974. return this._activeParticles;
  17975. },
  17976. enumerable: true,
  17977. configurable: true
  17978. });
  17979. Scene.prototype.getActiveBones = function () {
  17980. return this._activeBones.current;
  17981. };
  17982. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17983. get: function () {
  17984. return this._activeBones;
  17985. },
  17986. enumerable: true,
  17987. configurable: true
  17988. });
  17989. // Stats
  17990. Scene.prototype.getInterFramePerfCounter = function () {
  17991. return this._interFrameDuration.current;
  17992. };
  17993. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17994. get: function () {
  17995. return this._interFrameDuration;
  17996. },
  17997. enumerable: true,
  17998. configurable: true
  17999. });
  18000. Scene.prototype.getLastFrameDuration = function () {
  18001. return this._lastFrameDuration.current;
  18002. };
  18003. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18004. get: function () {
  18005. return this._lastFrameDuration;
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18011. BABYLON.Tools.Log("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18012. return 0;
  18013. };
  18014. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18015. get: function () {
  18016. BABYLON.Tools.Log("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18017. return null;
  18018. },
  18019. enumerable: true,
  18020. configurable: true
  18021. });
  18022. Scene.prototype.getActiveMeshes = function () {
  18023. return this._activeMeshes;
  18024. };
  18025. Scene.prototype.getRenderTargetsDuration = function () {
  18026. BABYLON.Tools.Log("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18027. return 0;
  18028. };
  18029. Scene.prototype.getRenderDuration = function () {
  18030. return this._renderDuration.current;
  18031. };
  18032. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18033. get: function () {
  18034. return this._renderDuration;
  18035. },
  18036. enumerable: true,
  18037. configurable: true
  18038. });
  18039. Scene.prototype.getParticlesDuration = function () {
  18040. return this._particlesDuration.current;
  18041. };
  18042. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18043. get: function () {
  18044. return this._particlesDuration;
  18045. },
  18046. enumerable: true,
  18047. configurable: true
  18048. });
  18049. Scene.prototype.getSpritesDuration = function () {
  18050. return this._spritesDuration.current;
  18051. };
  18052. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18053. get: function () {
  18054. return this._spritesDuration;
  18055. },
  18056. enumerable: true,
  18057. configurable: true
  18058. });
  18059. Scene.prototype.getAnimationRatio = function () {
  18060. return this._animationRatio;
  18061. };
  18062. Scene.prototype.getRenderId = function () {
  18063. return this._renderId;
  18064. };
  18065. Scene.prototype.incrementRenderId = function () {
  18066. this._renderId++;
  18067. };
  18068. Scene.prototype._updatePointerPosition = function (evt) {
  18069. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18070. if (!canvasRect) {
  18071. return;
  18072. }
  18073. this._pointerX = evt.clientX - canvasRect.left;
  18074. this._pointerY = evt.clientY - canvasRect.top;
  18075. this._unTranslatedPointerX = this._pointerX;
  18076. this._unTranslatedPointerY = this._pointerY;
  18077. };
  18078. Scene.prototype._createUbo = function () {
  18079. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18080. this._sceneUbo.addUniform("viewProjection", 16);
  18081. this._sceneUbo.addUniform("view", 16);
  18082. };
  18083. Scene.prototype._createAlternateUbo = function () {
  18084. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18085. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18086. this._alternateSceneUbo.addUniform("view", 16);
  18087. };
  18088. // Pointers handling
  18089. /**
  18090. * Use this method to simulate a pointer move on a mesh
  18091. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18092. */
  18093. Scene.prototype.simulatePointerMove = function (pickResult) {
  18094. var evt = new PointerEvent("pointermove");
  18095. return this._processPointerMove(pickResult, evt);
  18096. };
  18097. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18098. var canvas = this._engine.getRenderingCanvas();
  18099. if (!canvas) {
  18100. return this;
  18101. }
  18102. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18103. this.setPointerOverSprite(null);
  18104. this.setPointerOverMesh(pickResult.pickedMesh);
  18105. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18106. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18107. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18108. }
  18109. else {
  18110. canvas.style.cursor = this.hoverCursor;
  18111. }
  18112. }
  18113. else {
  18114. canvas.style.cursor = this.defaultCursor;
  18115. }
  18116. }
  18117. else {
  18118. this.setPointerOverMesh(null);
  18119. // Sprites
  18120. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18121. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18122. this.setPointerOverSprite(pickResult.pickedSprite);
  18123. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18124. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18125. }
  18126. else {
  18127. canvas.style.cursor = this.hoverCursor;
  18128. }
  18129. }
  18130. else {
  18131. this.setPointerOverSprite(null);
  18132. // Restore pointer
  18133. canvas.style.cursor = this.defaultCursor;
  18134. }
  18135. }
  18136. if (pickResult) {
  18137. if (this.onPointerMove) {
  18138. this.onPointerMove(evt, pickResult);
  18139. }
  18140. if (this.onPointerObservable.hasObservers()) {
  18141. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18142. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18143. this.onPointerObservable.notifyObservers(pi, type);
  18144. }
  18145. }
  18146. return this;
  18147. };
  18148. /**
  18149. * Use this method to simulate a pointer down on a mesh
  18150. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18151. */
  18152. Scene.prototype.simulatePointerDown = function (pickResult) {
  18153. var evt = new PointerEvent("pointerdown");
  18154. return this._processPointerDown(pickResult, evt);
  18155. };
  18156. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18157. var _this = this;
  18158. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18159. this._pickedDownMesh = pickResult.pickedMesh;
  18160. var actionManager = pickResult.pickedMesh.actionManager;
  18161. if (actionManager) {
  18162. if (actionManager.hasPickTriggers) {
  18163. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18164. switch (evt.button) {
  18165. case 0:
  18166. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18167. break;
  18168. case 1:
  18169. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18170. break;
  18171. case 2:
  18172. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18173. break;
  18174. }
  18175. }
  18176. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18177. window.setTimeout(function () {
  18178. 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);
  18179. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18180. if (_this._totalPointersPressed !== 0 &&
  18181. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18182. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18183. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18184. _this._startingPointerTime = 0;
  18185. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18186. }
  18187. }
  18188. }, Scene.LongPressDelay);
  18189. }
  18190. }
  18191. }
  18192. if (pickResult) {
  18193. if (this.onPointerDown) {
  18194. this.onPointerDown(evt, pickResult);
  18195. }
  18196. if (this.onPointerObservable.hasObservers()) {
  18197. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18198. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18199. this.onPointerObservable.notifyObservers(pi, type);
  18200. }
  18201. }
  18202. return this;
  18203. };
  18204. /**
  18205. * Use this method to simulate a pointer up on a mesh
  18206. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18207. */
  18208. Scene.prototype.simulatePointerUp = function (pickResult) {
  18209. var evt = new PointerEvent("pointerup");
  18210. var clickInfo = new ClickInfo();
  18211. clickInfo.singleClick = true;
  18212. return this._processPointerUp(pickResult, evt, clickInfo);
  18213. };
  18214. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18215. if (pickResult && pickResult && pickResult.pickedMesh) {
  18216. this._pickedUpMesh = pickResult.pickedMesh;
  18217. if (this._pickedDownMesh === this._pickedUpMesh) {
  18218. if (this.onPointerPick) {
  18219. this.onPointerPick(evt, pickResult);
  18220. }
  18221. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18222. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18223. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18224. this.onPointerObservable.notifyObservers(pi, type);
  18225. }
  18226. }
  18227. if (pickResult.pickedMesh.actionManager) {
  18228. if (clickInfo.ignore) {
  18229. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18230. }
  18231. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18232. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18233. }
  18234. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18235. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18236. }
  18237. }
  18238. }
  18239. if (this._pickedDownMesh &&
  18240. this._pickedDownMesh.actionManager &&
  18241. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18242. this._pickedDownMesh !== this._pickedUpMesh) {
  18243. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18244. }
  18245. if (this.onPointerUp) {
  18246. this.onPointerUp(evt, pickResult);
  18247. }
  18248. if (this.onPointerObservable.hasObservers()) {
  18249. if (!clickInfo.ignore) {
  18250. if (!clickInfo.hasSwiped) {
  18251. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18252. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18253. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18254. this.onPointerObservable.notifyObservers(pi, type);
  18255. }
  18256. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18257. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18258. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18259. this.onPointerObservable.notifyObservers(pi, type);
  18260. }
  18261. }
  18262. }
  18263. else {
  18264. var type = BABYLON.PointerEventTypes.POINTERUP;
  18265. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18266. this.onPointerObservable.notifyObservers(pi, type);
  18267. }
  18268. }
  18269. return this;
  18270. };
  18271. /**
  18272. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18273. * @param attachUp defines if you want to attach events to pointerup
  18274. * @param attachDown defines if you want to attach events to pointerdown
  18275. * @param attachMove defines if you want to attach events to pointermove
  18276. */
  18277. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18278. var _this = this;
  18279. if (attachUp === void 0) { attachUp = true; }
  18280. if (attachDown === void 0) { attachDown = true; }
  18281. if (attachMove === void 0) { attachMove = true; }
  18282. this._initActionManager = function (act, clickInfo) {
  18283. if (!_this._meshPickProceed) {
  18284. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18285. _this._currentPickResult = pickResult;
  18286. if (pickResult) {
  18287. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18288. }
  18289. _this._meshPickProceed = true;
  18290. }
  18291. return act;
  18292. };
  18293. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18294. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18295. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18296. btn !== _this._previousButtonPressed) {
  18297. _this._doubleClickOccured = false;
  18298. clickInfo.singleClick = true;
  18299. clickInfo.ignore = false;
  18300. cb(clickInfo, _this._currentPickResult);
  18301. }
  18302. };
  18303. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18304. var clickInfo = new ClickInfo();
  18305. _this._currentPickResult = null;
  18306. var act = null;
  18307. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18308. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18309. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18310. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18311. act = _this._initActionManager(act, clickInfo);
  18312. if (act)
  18313. checkPicking = act.hasPickTriggers;
  18314. }
  18315. if (checkPicking) {
  18316. var btn = evt.button;
  18317. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18318. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18319. if (!clickInfo.hasSwiped) {
  18320. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18321. if (!checkSingleClickImmediately) {
  18322. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18323. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18324. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18325. act = _this._initActionManager(act, clickInfo);
  18326. if (act)
  18327. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18328. }
  18329. }
  18330. if (checkSingleClickImmediately) {
  18331. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18332. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18333. btn !== _this._previousButtonPressed) {
  18334. clickInfo.singleClick = true;
  18335. cb(clickInfo, _this._currentPickResult);
  18336. }
  18337. }
  18338. else {
  18339. // wait that no double click has been raised during the double click delay
  18340. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18341. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18342. }
  18343. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18344. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18345. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18346. act = _this._initActionManager(act, clickInfo);
  18347. if (act)
  18348. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18349. }
  18350. if (checkDoubleClick) {
  18351. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18352. if (btn === _this._previousButtonPressed &&
  18353. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18354. !_this._doubleClickOccured) {
  18355. // pointer has not moved for 2 clicks, it's a double click
  18356. if (!clickInfo.hasSwiped &&
  18357. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18358. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18359. _this._previousStartingPointerTime = 0;
  18360. _this._doubleClickOccured = true;
  18361. clickInfo.doubleClick = true;
  18362. clickInfo.ignore = false;
  18363. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18364. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18365. }
  18366. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18367. cb(clickInfo, _this._currentPickResult);
  18368. }
  18369. else {
  18370. _this._doubleClickOccured = false;
  18371. _this._previousStartingPointerTime = _this._startingPointerTime;
  18372. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18373. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18374. _this._previousButtonPressed = btn;
  18375. _this._previousHasSwiped = clickInfo.hasSwiped;
  18376. if (Scene.ExclusiveDoubleClickMode) {
  18377. if (_this._previousDelayedSimpleClickTimeout) {
  18378. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18379. }
  18380. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18381. cb(clickInfo, _this._previousPickResult);
  18382. }
  18383. else {
  18384. cb(clickInfo, _this._currentPickResult);
  18385. }
  18386. }
  18387. }
  18388. else {
  18389. _this._doubleClickOccured = false;
  18390. _this._previousStartingPointerTime = _this._startingPointerTime;
  18391. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18392. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18393. _this._previousButtonPressed = btn;
  18394. _this._previousHasSwiped = clickInfo.hasSwiped;
  18395. }
  18396. }
  18397. }
  18398. }
  18399. clickInfo.ignore = true;
  18400. cb(clickInfo, _this._currentPickResult);
  18401. };
  18402. this._spritePredicate = function (sprite) {
  18403. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18404. };
  18405. this._onPointerMove = function (evt) {
  18406. _this._updatePointerPosition(evt);
  18407. // PreObservable support
  18408. if (_this.onPrePointerObservable.hasObservers()) {
  18409. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18410. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18411. _this.onPrePointerObservable.notifyObservers(pi, type);
  18412. if (pi.skipOnPointerObservable) {
  18413. return;
  18414. }
  18415. }
  18416. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18417. return;
  18418. }
  18419. if (!_this.pointerMovePredicate) {
  18420. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18421. }
  18422. // Meshes
  18423. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18424. _this._processPointerMove(pickResult, evt);
  18425. };
  18426. this._onPointerDown = function (evt) {
  18427. _this._totalPointersPressed++;
  18428. _this._pickedDownMesh = null;
  18429. _this._meshPickProceed = false;
  18430. _this._updatePointerPosition(evt);
  18431. if (_this.preventDefaultOnPointerDown && canvas) {
  18432. evt.preventDefault();
  18433. canvas.focus();
  18434. }
  18435. // PreObservable support
  18436. if (_this.onPrePointerObservable.hasObservers()) {
  18437. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18438. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18439. _this.onPrePointerObservable.notifyObservers(pi, type);
  18440. if (pi.skipOnPointerObservable) {
  18441. return;
  18442. }
  18443. }
  18444. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18445. return;
  18446. }
  18447. _this._startingPointerPosition.x = _this._pointerX;
  18448. _this._startingPointerPosition.y = _this._pointerY;
  18449. _this._startingPointerTime = new Date().getTime();
  18450. if (!_this.pointerDownPredicate) {
  18451. _this.pointerDownPredicate = function (mesh) {
  18452. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18453. };
  18454. }
  18455. // Meshes
  18456. _this._pickedDownMesh = null;
  18457. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18458. _this._processPointerDown(pickResult, evt);
  18459. // Sprites
  18460. _this._pickedDownSprite = null;
  18461. if (_this.spriteManagers.length > 0) {
  18462. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18463. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18464. if (pickResult.pickedSprite.actionManager) {
  18465. _this._pickedDownSprite = pickResult.pickedSprite;
  18466. switch (evt.button) {
  18467. case 0:
  18468. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18469. break;
  18470. case 1:
  18471. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18472. break;
  18473. case 2:
  18474. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18475. break;
  18476. }
  18477. if (pickResult.pickedSprite.actionManager) {
  18478. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18479. }
  18480. }
  18481. }
  18482. }
  18483. };
  18484. this._onPointerUp = function (evt) {
  18485. if (_this._totalPointersPressed === 0) {
  18486. return; // So we need to test it the pointer down was pressed before.
  18487. }
  18488. _this._totalPointersPressed--;
  18489. _this._pickedUpMesh = null;
  18490. _this._meshPickProceed = false;
  18491. _this._updatePointerPosition(evt);
  18492. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18493. // PreObservable support
  18494. if (_this.onPrePointerObservable.hasObservers()) {
  18495. if (!clickInfo.ignore) {
  18496. if (!clickInfo.hasSwiped) {
  18497. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18498. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18499. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18500. _this.onPrePointerObservable.notifyObservers(pi, type);
  18501. if (pi.skipOnPointerObservable) {
  18502. return;
  18503. }
  18504. }
  18505. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18506. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18507. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18508. _this.onPrePointerObservable.notifyObservers(pi, type);
  18509. if (pi.skipOnPointerObservable) {
  18510. return;
  18511. }
  18512. }
  18513. }
  18514. }
  18515. else {
  18516. var type = BABYLON.PointerEventTypes.POINTERUP;
  18517. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18518. _this.onPrePointerObservable.notifyObservers(pi, type);
  18519. if (pi.skipOnPointerObservable) {
  18520. return;
  18521. }
  18522. }
  18523. }
  18524. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18525. return;
  18526. }
  18527. if (!_this.pointerUpPredicate) {
  18528. _this.pointerUpPredicate = function (mesh) {
  18529. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18530. };
  18531. }
  18532. // Meshes
  18533. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18534. _this._initActionManager(null, clickInfo);
  18535. }
  18536. if (!pickResult) {
  18537. pickResult = _this._currentPickResult;
  18538. }
  18539. _this._processPointerUp(pickResult, evt, clickInfo);
  18540. // Sprites
  18541. if (_this.spriteManagers.length > 0) {
  18542. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18543. if (spritePickResult) {
  18544. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18545. if (spritePickResult.pickedSprite.actionManager) {
  18546. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18547. if (spritePickResult.pickedSprite.actionManager) {
  18548. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18549. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18550. }
  18551. }
  18552. }
  18553. }
  18554. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18555. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18556. }
  18557. }
  18558. }
  18559. _this._previousPickResult = _this._currentPickResult;
  18560. });
  18561. };
  18562. this._onKeyDown = function (evt) {
  18563. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18564. if (_this.onPreKeyboardObservable.hasObservers()) {
  18565. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18566. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18567. if (pi.skipOnPointerObservable) {
  18568. return;
  18569. }
  18570. }
  18571. if (_this.onKeyboardObservable.hasObservers()) {
  18572. var pi = new BABYLON.KeyboardInfo(type, evt);
  18573. _this.onKeyboardObservable.notifyObservers(pi, type);
  18574. }
  18575. if (_this.actionManager) {
  18576. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18577. }
  18578. };
  18579. this._onKeyUp = function (evt) {
  18580. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18581. if (_this.onPreKeyboardObservable.hasObservers()) {
  18582. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18583. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18584. if (pi.skipOnPointerObservable) {
  18585. return;
  18586. }
  18587. }
  18588. if (_this.onKeyboardObservable.hasObservers()) {
  18589. var pi = new BABYLON.KeyboardInfo(type, evt);
  18590. _this.onKeyboardObservable.notifyObservers(pi, type);
  18591. }
  18592. if (_this.actionManager) {
  18593. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18594. }
  18595. };
  18596. var engine = this.getEngine();
  18597. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18598. if (!canvas) {
  18599. return;
  18600. }
  18601. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18602. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18603. });
  18604. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18605. if (!canvas) {
  18606. return;
  18607. }
  18608. canvas.removeEventListener("keydown", _this._onKeyDown);
  18609. canvas.removeEventListener("keyup", _this._onKeyUp);
  18610. });
  18611. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18612. var canvas = this._engine.getRenderingCanvas();
  18613. if (!canvas) {
  18614. return;
  18615. }
  18616. if (attachMove) {
  18617. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18618. // Wheel
  18619. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18620. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18621. }
  18622. if (attachDown) {
  18623. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18624. }
  18625. if (attachUp) {
  18626. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18627. }
  18628. canvas.tabIndex = 1;
  18629. };
  18630. Scene.prototype.detachControl = function () {
  18631. var engine = this.getEngine();
  18632. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18633. var canvas = engine.getRenderingCanvas();
  18634. if (!canvas) {
  18635. return;
  18636. }
  18637. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18638. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18639. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18640. if (this._onCanvasBlurObserver) {
  18641. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18642. }
  18643. if (this._onCanvasFocusObserver) {
  18644. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18645. }
  18646. // Wheel
  18647. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18648. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18649. // Keyboard
  18650. canvas.removeEventListener("keydown", this._onKeyDown);
  18651. canvas.removeEventListener("keyup", this._onKeyUp);
  18652. // Observables
  18653. this.onKeyboardObservable.clear();
  18654. this.onPreKeyboardObservable.clear();
  18655. this.onPointerObservable.clear();
  18656. this.onPrePointerObservable.clear();
  18657. };
  18658. // Ready
  18659. Scene.prototype.isReady = function () {
  18660. if (this._isDisposed) {
  18661. return false;
  18662. }
  18663. if (this._pendingData.length > 0) {
  18664. return false;
  18665. }
  18666. var index;
  18667. // Geometries
  18668. for (index = 0; index < this._geometries.length; index++) {
  18669. var geometry = this._geometries[index];
  18670. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18671. return false;
  18672. }
  18673. }
  18674. // Meshes
  18675. for (index = 0; index < this.meshes.length; index++) {
  18676. var mesh = this.meshes[index];
  18677. if (!mesh.isEnabled()) {
  18678. continue;
  18679. }
  18680. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18681. continue;
  18682. }
  18683. if (!mesh.isReady()) {
  18684. return false;
  18685. }
  18686. var mat = mesh.material;
  18687. if (mat) {
  18688. if (!mat.isReady(mesh)) {
  18689. return false;
  18690. }
  18691. }
  18692. }
  18693. return true;
  18694. };
  18695. Scene.prototype.resetCachedMaterial = function () {
  18696. this._cachedMaterial = null;
  18697. this._cachedEffect = null;
  18698. this._cachedVisibility = null;
  18699. };
  18700. Scene.prototype.registerBeforeRender = function (func) {
  18701. this.onBeforeRenderObservable.add(func);
  18702. };
  18703. Scene.prototype.unregisterBeforeRender = function (func) {
  18704. this.onBeforeRenderObservable.removeCallback(func);
  18705. };
  18706. Scene.prototype.registerAfterRender = function (func) {
  18707. this.onAfterRenderObservable.add(func);
  18708. };
  18709. Scene.prototype.unregisterAfterRender = function (func) {
  18710. this.onAfterRenderObservable.removeCallback(func);
  18711. };
  18712. Scene.prototype._addPendingData = function (data) {
  18713. this._pendingData.push(data);
  18714. };
  18715. Scene.prototype._removePendingData = function (data) {
  18716. var index = this._pendingData.indexOf(data);
  18717. if (index !== -1) {
  18718. this._pendingData.splice(index, 1);
  18719. }
  18720. };
  18721. Scene.prototype.getWaitingItemsCount = function () {
  18722. return this._pendingData.length;
  18723. };
  18724. /**
  18725. * Registers a function to be executed when the scene is ready.
  18726. * @param {Function} func - the function to be executed.
  18727. */
  18728. Scene.prototype.executeWhenReady = function (func) {
  18729. var _this = this;
  18730. this.onReadyObservable.add(func);
  18731. if (this._executeWhenReadyTimeoutId !== -1) {
  18732. return;
  18733. }
  18734. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18735. _this._checkIsReady();
  18736. }, 150);
  18737. };
  18738. Scene.prototype._checkIsReady = function () {
  18739. var _this = this;
  18740. if (this.isReady()) {
  18741. this.onReadyObservable.notifyObservers(this);
  18742. this.onReadyObservable.clear();
  18743. this._executeWhenReadyTimeoutId = -1;
  18744. return;
  18745. }
  18746. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18747. _this._checkIsReady();
  18748. }, 150);
  18749. };
  18750. // Animations
  18751. /**
  18752. * Will start the animation sequence of a given target
  18753. * @param target - the target
  18754. * @param {number} from - from which frame should animation start
  18755. * @param {number} to - till which frame should animation run.
  18756. * @param {boolean} [loop] - should the animation loop
  18757. * @param {number} [speedRatio] - the speed in which to run the animation
  18758. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18759. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18760. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18761. * See BABYLON.Animatable
  18762. */
  18763. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18764. if (speedRatio === void 0) { speedRatio = 1.0; }
  18765. if (from > to && speedRatio > 0) {
  18766. speedRatio *= -1;
  18767. }
  18768. this.stopAnimation(target);
  18769. if (!animatable) {
  18770. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18771. }
  18772. // Local animations
  18773. if (target.animations) {
  18774. animatable.appendAnimations(target, target.animations);
  18775. }
  18776. // Children animations
  18777. if (target.getAnimatables) {
  18778. var animatables = target.getAnimatables();
  18779. for (var index = 0; index < animatables.length; index++) {
  18780. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18781. }
  18782. }
  18783. animatable.reset();
  18784. return animatable;
  18785. };
  18786. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18787. if (speedRatio === undefined) {
  18788. speedRatio = 1.0;
  18789. }
  18790. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18791. return animatable;
  18792. };
  18793. Scene.prototype.getAnimatableByTarget = function (target) {
  18794. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18795. if (this._activeAnimatables[index].target === target) {
  18796. return this._activeAnimatables[index];
  18797. }
  18798. }
  18799. return null;
  18800. };
  18801. Object.defineProperty(Scene.prototype, "Animatables", {
  18802. get: function () {
  18803. return this._activeAnimatables;
  18804. },
  18805. enumerable: true,
  18806. configurable: true
  18807. });
  18808. /**
  18809. * Will stop the animation of the given target
  18810. * @param target - the target
  18811. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18812. * @see beginAnimation
  18813. */
  18814. Scene.prototype.stopAnimation = function (target, animationName) {
  18815. var animatable = this.getAnimatableByTarget(target);
  18816. if (animatable) {
  18817. animatable.stop(animationName);
  18818. }
  18819. };
  18820. Scene.prototype._animate = function () {
  18821. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18822. return;
  18823. }
  18824. // Getting time
  18825. var now = BABYLON.Tools.Now;
  18826. if (!this._animationTimeLast) {
  18827. if (this._pendingData.length > 0) {
  18828. return;
  18829. }
  18830. this._animationTimeLast = now;
  18831. }
  18832. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18833. this._animationTime += deltaTime;
  18834. this._animationTimeLast = now;
  18835. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18836. this._activeAnimatables[index]._animate(this._animationTime);
  18837. }
  18838. };
  18839. // Matrix
  18840. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18841. this._useAlternateCameraConfiguration = active;
  18842. };
  18843. Scene.prototype.getViewMatrix = function () {
  18844. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18845. };
  18846. Scene.prototype.getProjectionMatrix = function () {
  18847. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18848. };
  18849. Scene.prototype.getTransformMatrix = function () {
  18850. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18851. };
  18852. Scene.prototype.setTransformMatrix = function (view, projection) {
  18853. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18854. return;
  18855. }
  18856. this._viewUpdateFlag = view.updateFlag;
  18857. this._projectionUpdateFlag = projection.updateFlag;
  18858. this._viewMatrix = view;
  18859. this._projectionMatrix = projection;
  18860. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18861. // Update frustum
  18862. if (!this._frustumPlanes) {
  18863. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18864. }
  18865. else {
  18866. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18867. }
  18868. if (this.activeCamera && this.activeCamera._alternateCamera) {
  18869. var otherCamera = this.activeCamera._alternateCamera;
  18870. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18871. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18872. }
  18873. if (this._sceneUbo.useUbo) {
  18874. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18875. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18876. this._sceneUbo.update();
  18877. }
  18878. };
  18879. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18880. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18881. return;
  18882. }
  18883. this._alternateViewUpdateFlag = view.updateFlag;
  18884. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18885. this._alternateViewMatrix = view;
  18886. this._alternateProjectionMatrix = projection;
  18887. if (!this._alternateTransformMatrix) {
  18888. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18889. }
  18890. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18891. if (!this._alternateSceneUbo) {
  18892. this._createAlternateUbo();
  18893. }
  18894. if (this._alternateSceneUbo.useUbo) {
  18895. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18896. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18897. this._alternateSceneUbo.update();
  18898. }
  18899. };
  18900. Scene.prototype.getSceneUniformBuffer = function () {
  18901. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18902. };
  18903. // Methods
  18904. Scene.prototype.getUniqueId = function () {
  18905. var result = Scene._uniqueIdCounter;
  18906. Scene._uniqueIdCounter++;
  18907. return result;
  18908. };
  18909. Scene.prototype.addMesh = function (newMesh) {
  18910. this.meshes.push(newMesh);
  18911. //notify the collision coordinator
  18912. if (this.collisionCoordinator) {
  18913. this.collisionCoordinator.onMeshAdded(newMesh);
  18914. }
  18915. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18916. };
  18917. Scene.prototype.removeMesh = function (toRemove) {
  18918. var index = this.meshes.indexOf(toRemove);
  18919. if (index !== -1) {
  18920. // Remove from the scene if mesh found
  18921. this.meshes.splice(index, 1);
  18922. }
  18923. //notify the collision coordinator
  18924. if (this.collisionCoordinator) {
  18925. this.collisionCoordinator.onMeshRemoved(toRemove);
  18926. }
  18927. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18928. return index;
  18929. };
  18930. Scene.prototype.removeSkeleton = function (toRemove) {
  18931. var index = this.skeletons.indexOf(toRemove);
  18932. if (index !== -1) {
  18933. // Remove from the scene if found
  18934. this.skeletons.splice(index, 1);
  18935. }
  18936. return index;
  18937. };
  18938. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18939. var index = this.morphTargetManagers.indexOf(toRemove);
  18940. if (index !== -1) {
  18941. // Remove from the scene if found
  18942. this.morphTargetManagers.splice(index, 1);
  18943. }
  18944. return index;
  18945. };
  18946. Scene.prototype.removeLight = function (toRemove) {
  18947. var index = this.lights.indexOf(toRemove);
  18948. if (index !== -1) {
  18949. // Remove from the scene if mesh found
  18950. this.lights.splice(index, 1);
  18951. this.sortLightsByPriority();
  18952. }
  18953. this.onLightRemovedObservable.notifyObservers(toRemove);
  18954. return index;
  18955. };
  18956. Scene.prototype.removeCamera = function (toRemove) {
  18957. var index = this.cameras.indexOf(toRemove);
  18958. if (index !== -1) {
  18959. // Remove from the scene if mesh found
  18960. this.cameras.splice(index, 1);
  18961. }
  18962. // Remove from activeCameras
  18963. var index2 = this.activeCameras.indexOf(toRemove);
  18964. if (index2 !== -1) {
  18965. // Remove from the scene if mesh found
  18966. this.activeCameras.splice(index2, 1);
  18967. }
  18968. // Reset the activeCamera
  18969. if (this.activeCamera === toRemove) {
  18970. if (this.cameras.length > 0) {
  18971. this.activeCamera = this.cameras[0];
  18972. }
  18973. else {
  18974. this.activeCamera = null;
  18975. }
  18976. }
  18977. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18978. return index;
  18979. };
  18980. Scene.prototype.addLight = function (newLight) {
  18981. this.lights.push(newLight);
  18982. this.sortLightsByPriority();
  18983. this.onNewLightAddedObservable.notifyObservers(newLight);
  18984. };
  18985. Scene.prototype.sortLightsByPriority = function () {
  18986. if (this.requireLightSorting) {
  18987. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18988. }
  18989. };
  18990. Scene.prototype.addCamera = function (newCamera) {
  18991. this.cameras.push(newCamera);
  18992. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18993. };
  18994. /**
  18995. * Switch active camera
  18996. * @param {Camera} newCamera - new active camera
  18997. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18998. */
  18999. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19000. if (attachControl === void 0) { attachControl = true; }
  19001. var canvas = this._engine.getRenderingCanvas();
  19002. if (!canvas) {
  19003. return;
  19004. }
  19005. if (this.activeCamera) {
  19006. this.activeCamera.detachControl(canvas);
  19007. }
  19008. this.activeCamera = newCamera;
  19009. if (attachControl) {
  19010. newCamera.attachControl(canvas);
  19011. }
  19012. };
  19013. /**
  19014. * sets the active camera of the scene using its ID
  19015. * @param {string} id - the camera's ID
  19016. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19017. * @see activeCamera
  19018. */
  19019. Scene.prototype.setActiveCameraByID = function (id) {
  19020. var camera = this.getCameraByID(id);
  19021. if (camera) {
  19022. this.activeCamera = camera;
  19023. return camera;
  19024. }
  19025. return null;
  19026. };
  19027. /**
  19028. * sets the active camera of the scene using its name
  19029. * @param {string} name - the camera's name
  19030. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19031. * @see activeCamera
  19032. */
  19033. Scene.prototype.setActiveCameraByName = function (name) {
  19034. var camera = this.getCameraByName(name);
  19035. if (camera) {
  19036. this.activeCamera = camera;
  19037. return camera;
  19038. }
  19039. return null;
  19040. };
  19041. /**
  19042. * get a material using its id
  19043. * @param {string} the material's ID
  19044. * @return {BABYLON.Material|null} the material or null if none found.
  19045. */
  19046. Scene.prototype.getMaterialByID = function (id) {
  19047. for (var index = 0; index < this.materials.length; index++) {
  19048. if (this.materials[index].id === id) {
  19049. return this.materials[index];
  19050. }
  19051. }
  19052. return null;
  19053. };
  19054. /**
  19055. * get a material using its name
  19056. * @param {string} the material's name
  19057. * @return {BABYLON.Material|null} the material or null if none found.
  19058. */
  19059. Scene.prototype.getMaterialByName = function (name) {
  19060. for (var index = 0; index < this.materials.length; index++) {
  19061. if (this.materials[index].name === name) {
  19062. return this.materials[index];
  19063. }
  19064. }
  19065. return null;
  19066. };
  19067. Scene.prototype.getLensFlareSystemByName = function (name) {
  19068. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19069. if (this.lensFlareSystems[index].name === name) {
  19070. return this.lensFlareSystems[index];
  19071. }
  19072. }
  19073. return null;
  19074. };
  19075. Scene.prototype.getLensFlareSystemByID = function (id) {
  19076. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19077. if (this.lensFlareSystems[index].id === id) {
  19078. return this.lensFlareSystems[index];
  19079. }
  19080. }
  19081. return null;
  19082. };
  19083. Scene.prototype.getCameraByID = function (id) {
  19084. for (var index = 0; index < this.cameras.length; index++) {
  19085. if (this.cameras[index].id === id) {
  19086. return this.cameras[index];
  19087. }
  19088. }
  19089. return null;
  19090. };
  19091. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19092. for (var index = 0; index < this.cameras.length; index++) {
  19093. if (this.cameras[index].uniqueId === uniqueId) {
  19094. return this.cameras[index];
  19095. }
  19096. }
  19097. return null;
  19098. };
  19099. /**
  19100. * get a camera using its name
  19101. * @param {string} the camera's name
  19102. * @return {BABYLON.Camera|null} the camera or null if none found.
  19103. */
  19104. Scene.prototype.getCameraByName = function (name) {
  19105. for (var index = 0; index < this.cameras.length; index++) {
  19106. if (this.cameras[index].name === name) {
  19107. return this.cameras[index];
  19108. }
  19109. }
  19110. return null;
  19111. };
  19112. /**
  19113. * get a bone using its id
  19114. * @param {string} the bone's id
  19115. * @return {BABYLON.Bone|null} the bone or null if not found
  19116. */
  19117. Scene.prototype.getBoneByID = function (id) {
  19118. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19119. var skeleton = this.skeletons[skeletonIndex];
  19120. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19121. if (skeleton.bones[boneIndex].id === id) {
  19122. return skeleton.bones[boneIndex];
  19123. }
  19124. }
  19125. }
  19126. return null;
  19127. };
  19128. /**
  19129. * get a bone using its id
  19130. * @param {string} the bone's name
  19131. * @return {BABYLON.Bone|null} the bone or null if not found
  19132. */
  19133. Scene.prototype.getBoneByName = function (name) {
  19134. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19135. var skeleton = this.skeletons[skeletonIndex];
  19136. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19137. if (skeleton.bones[boneIndex].name === name) {
  19138. return skeleton.bones[boneIndex];
  19139. }
  19140. }
  19141. }
  19142. return null;
  19143. };
  19144. /**
  19145. * get a light node using its name
  19146. * @param {string} the light's name
  19147. * @return {BABYLON.Light|null} the light or null if none found.
  19148. */
  19149. Scene.prototype.getLightByName = function (name) {
  19150. for (var index = 0; index < this.lights.length; index++) {
  19151. if (this.lights[index].name === name) {
  19152. return this.lights[index];
  19153. }
  19154. }
  19155. return null;
  19156. };
  19157. /**
  19158. * get a light node using its ID
  19159. * @param {string} the light's id
  19160. * @return {BABYLON.Light|null} the light or null if none found.
  19161. */
  19162. Scene.prototype.getLightByID = function (id) {
  19163. for (var index = 0; index < this.lights.length; index++) {
  19164. if (this.lights[index].id === id) {
  19165. return this.lights[index];
  19166. }
  19167. }
  19168. return null;
  19169. };
  19170. /**
  19171. * get a light node using its scene-generated unique ID
  19172. * @param {number} the light's unique id
  19173. * @return {BABYLON.Light|null} the light or null if none found.
  19174. */
  19175. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19176. for (var index = 0; index < this.lights.length; index++) {
  19177. if (this.lights[index].uniqueId === uniqueId) {
  19178. return this.lights[index];
  19179. }
  19180. }
  19181. return null;
  19182. };
  19183. /**
  19184. * get a particle system by id
  19185. * @param id {number} the particle system id
  19186. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19187. */
  19188. Scene.prototype.getParticleSystemByID = function (id) {
  19189. for (var index = 0; index < this.particleSystems.length; index++) {
  19190. if (this.particleSystems[index].id === id) {
  19191. return this.particleSystems[index];
  19192. }
  19193. }
  19194. return null;
  19195. };
  19196. /**
  19197. * get a geometry using its ID
  19198. * @param {string} the geometry's id
  19199. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19200. */
  19201. Scene.prototype.getGeometryByID = function (id) {
  19202. for (var index = 0; index < this._geometries.length; index++) {
  19203. if (this._geometries[index].id === id) {
  19204. return this._geometries[index];
  19205. }
  19206. }
  19207. return null;
  19208. };
  19209. /**
  19210. * add a new geometry to this scene.
  19211. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19212. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19213. * @return {boolean} was the geometry added or not
  19214. */
  19215. Scene.prototype.pushGeometry = function (geometry, force) {
  19216. if (!force && this.getGeometryByID(geometry.id)) {
  19217. return false;
  19218. }
  19219. this._geometries.push(geometry);
  19220. //notify the collision coordinator
  19221. if (this.collisionCoordinator) {
  19222. this.collisionCoordinator.onGeometryAdded(geometry);
  19223. }
  19224. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19225. return true;
  19226. };
  19227. /**
  19228. * Removes an existing geometry
  19229. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19230. * @return {boolean} was the geometry removed or not
  19231. */
  19232. Scene.prototype.removeGeometry = function (geometry) {
  19233. var index = this._geometries.indexOf(geometry);
  19234. if (index > -1) {
  19235. this._geometries.splice(index, 1);
  19236. //notify the collision coordinator
  19237. if (this.collisionCoordinator) {
  19238. this.collisionCoordinator.onGeometryDeleted(geometry);
  19239. }
  19240. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19241. return true;
  19242. }
  19243. return false;
  19244. };
  19245. Scene.prototype.getGeometries = function () {
  19246. return this._geometries;
  19247. };
  19248. /**
  19249. * Get the first added mesh found of a given ID
  19250. * @param {string} id - the id to search for
  19251. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19252. */
  19253. Scene.prototype.getMeshByID = function (id) {
  19254. for (var index = 0; index < this.meshes.length; index++) {
  19255. if (this.meshes[index].id === id) {
  19256. return this.meshes[index];
  19257. }
  19258. }
  19259. return null;
  19260. };
  19261. Scene.prototype.getMeshesByID = function (id) {
  19262. return this.meshes.filter(function (m) {
  19263. return m.id === id;
  19264. });
  19265. };
  19266. /**
  19267. * Get a mesh with its auto-generated unique id
  19268. * @param {number} uniqueId - the unique id to search for
  19269. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19270. */
  19271. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19272. for (var index = 0; index < this.meshes.length; index++) {
  19273. if (this.meshes[index].uniqueId === uniqueId) {
  19274. return this.meshes[index];
  19275. }
  19276. }
  19277. return null;
  19278. };
  19279. /**
  19280. * Get a the last added mesh found of a given ID
  19281. * @param {string} id - the id to search for
  19282. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19283. */
  19284. Scene.prototype.getLastMeshByID = function (id) {
  19285. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19286. if (this.meshes[index].id === id) {
  19287. return this.meshes[index];
  19288. }
  19289. }
  19290. return null;
  19291. };
  19292. /**
  19293. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19294. * @param {string} id - the id to search for
  19295. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19296. */
  19297. Scene.prototype.getLastEntryByID = function (id) {
  19298. var index;
  19299. for (index = this.meshes.length - 1; index >= 0; index--) {
  19300. if (this.meshes[index].id === id) {
  19301. return this.meshes[index];
  19302. }
  19303. }
  19304. for (index = this.cameras.length - 1; index >= 0; index--) {
  19305. if (this.cameras[index].id === id) {
  19306. return this.cameras[index];
  19307. }
  19308. }
  19309. for (index = this.lights.length - 1; index >= 0; index--) {
  19310. if (this.lights[index].id === id) {
  19311. return this.lights[index];
  19312. }
  19313. }
  19314. return null;
  19315. };
  19316. Scene.prototype.getNodeByID = function (id) {
  19317. var mesh = this.getMeshByID(id);
  19318. if (mesh) {
  19319. return mesh;
  19320. }
  19321. var light = this.getLightByID(id);
  19322. if (light) {
  19323. return light;
  19324. }
  19325. var camera = this.getCameraByID(id);
  19326. if (camera) {
  19327. return camera;
  19328. }
  19329. var bone = this.getBoneByID(id);
  19330. return bone;
  19331. };
  19332. Scene.prototype.getNodeByName = function (name) {
  19333. var mesh = this.getMeshByName(name);
  19334. if (mesh) {
  19335. return mesh;
  19336. }
  19337. var light = this.getLightByName(name);
  19338. if (light) {
  19339. return light;
  19340. }
  19341. var camera = this.getCameraByName(name);
  19342. if (camera) {
  19343. return camera;
  19344. }
  19345. var bone = this.getBoneByName(name);
  19346. return bone;
  19347. };
  19348. Scene.prototype.getMeshByName = function (name) {
  19349. for (var index = 0; index < this.meshes.length; index++) {
  19350. if (this.meshes[index].name === name) {
  19351. return this.meshes[index];
  19352. }
  19353. }
  19354. return null;
  19355. };
  19356. Scene.prototype.getSoundByName = function (name) {
  19357. var index;
  19358. if (BABYLON.AudioEngine) {
  19359. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19360. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19361. return this.mainSoundTrack.soundCollection[index];
  19362. }
  19363. }
  19364. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19365. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19366. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19367. return this.soundTracks[sdIndex].soundCollection[index];
  19368. }
  19369. }
  19370. }
  19371. }
  19372. return null;
  19373. };
  19374. Scene.prototype.getLastSkeletonByID = function (id) {
  19375. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19376. if (this.skeletons[index].id === id) {
  19377. return this.skeletons[index];
  19378. }
  19379. }
  19380. return null;
  19381. };
  19382. Scene.prototype.getSkeletonById = function (id) {
  19383. for (var index = 0; index < this.skeletons.length; index++) {
  19384. if (this.skeletons[index].id === id) {
  19385. return this.skeletons[index];
  19386. }
  19387. }
  19388. return null;
  19389. };
  19390. Scene.prototype.getSkeletonByName = function (name) {
  19391. for (var index = 0; index < this.skeletons.length; index++) {
  19392. if (this.skeletons[index].name === name) {
  19393. return this.skeletons[index];
  19394. }
  19395. }
  19396. return null;
  19397. };
  19398. Scene.prototype.getMorphTargetManagerById = function (id) {
  19399. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19400. if (this.morphTargetManagers[index].uniqueId === id) {
  19401. return this.morphTargetManagers[index];
  19402. }
  19403. }
  19404. return null;
  19405. };
  19406. Scene.prototype.isActiveMesh = function (mesh) {
  19407. return (this._activeMeshes.indexOf(mesh) !== -1);
  19408. };
  19409. /**
  19410. * Return a the first highlight layer of the scene with a given name.
  19411. * @param name The name of the highlight layer to look for.
  19412. * @return The highlight layer if found otherwise null.
  19413. */
  19414. Scene.prototype.getHighlightLayerByName = function (name) {
  19415. for (var index = 0; index < this.highlightLayers.length; index++) {
  19416. if (this.highlightLayers[index].name === name) {
  19417. return this.highlightLayers[index];
  19418. }
  19419. }
  19420. return null;
  19421. };
  19422. Object.defineProperty(Scene.prototype, "uid", {
  19423. /**
  19424. * Return a unique id as a string which can serve as an identifier for the scene
  19425. */
  19426. get: function () {
  19427. if (!this._uid) {
  19428. this._uid = BABYLON.Tools.RandomId();
  19429. }
  19430. return this._uid;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. /**
  19436. * Add an externaly attached data from its key.
  19437. * This method call will fail and return false, if such key already exists.
  19438. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19439. * @param key the unique key that identifies the data
  19440. * @param data the data object to associate to the key for this Engine instance
  19441. * @return true if no such key were already present and the data was added successfully, false otherwise
  19442. */
  19443. Scene.prototype.addExternalData = function (key, data) {
  19444. if (!this._externalData) {
  19445. this._externalData = new BABYLON.StringDictionary();
  19446. }
  19447. return this._externalData.add(key, data);
  19448. };
  19449. /**
  19450. * Get an externaly attached data from its key
  19451. * @param key the unique key that identifies the data
  19452. * @return the associated data, if present (can be null), or undefined if not present
  19453. */
  19454. Scene.prototype.getExternalData = function (key) {
  19455. if (!this._externalData) {
  19456. return null;
  19457. }
  19458. return this._externalData.get(key);
  19459. };
  19460. /**
  19461. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19462. * @param key the unique key that identifies the data
  19463. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19464. * @return the associated data, can be null if the factory returned null.
  19465. */
  19466. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19467. if (!this._externalData) {
  19468. this._externalData = new BABYLON.StringDictionary();
  19469. }
  19470. return this._externalData.getOrAddWithFactory(key, factory);
  19471. };
  19472. /**
  19473. * Remove an externaly attached data from the Engine instance
  19474. * @param key the unique key that identifies the data
  19475. * @return true if the data was successfully removed, false if it doesn't exist
  19476. */
  19477. Scene.prototype.removeExternalData = function (key) {
  19478. return this._externalData.remove(key);
  19479. };
  19480. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19481. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19482. var material = subMesh.getMaterial();
  19483. if (mesh.showSubMeshesBoundingBox) {
  19484. var boundingInfo = subMesh.getBoundingInfo();
  19485. if (boundingInfo) {
  19486. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19487. }
  19488. }
  19489. if (material) {
  19490. // Render targets
  19491. if (material.getRenderTargetTextures) {
  19492. if (this._processedMaterials.indexOf(material) === -1) {
  19493. this._processedMaterials.push(material);
  19494. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19495. }
  19496. }
  19497. // Dispatch
  19498. this._activeIndices.addCount(subMesh.indexCount, false);
  19499. this._renderingManager.dispatch(subMesh);
  19500. }
  19501. }
  19502. };
  19503. Scene.prototype._isInIntermediateRendering = function () {
  19504. return this._intermediateRendering;
  19505. };
  19506. /**
  19507. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19508. */
  19509. Scene.prototype.freezeActiveMeshes = function () {
  19510. this._evaluateActiveMeshes();
  19511. this._activeMeshesFrozen = true;
  19512. return this;
  19513. };
  19514. /**
  19515. * Use this function to restart evaluating active meshes on every frame
  19516. */
  19517. Scene.prototype.unfreezeActiveMeshes = function () {
  19518. this._activeMeshesFrozen = false;
  19519. return this;
  19520. };
  19521. Scene.prototype._evaluateActiveMeshes = function () {
  19522. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19523. return;
  19524. }
  19525. if (!this.activeCamera) {
  19526. return;
  19527. }
  19528. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19529. this.activeCamera._activeMeshes.reset();
  19530. this._activeMeshes.reset();
  19531. this._renderingManager.reset();
  19532. this._processedMaterials.reset();
  19533. this._activeParticleSystems.reset();
  19534. this._activeSkeletons.reset();
  19535. this._softwareSkinnedMeshes.reset();
  19536. if (this._boundingBoxRenderer) {
  19537. this._boundingBoxRenderer.reset();
  19538. }
  19539. // Meshes
  19540. var meshes;
  19541. var len;
  19542. if (this._selectionOctree) {
  19543. var selection = this._selectionOctree.select(this._frustumPlanes);
  19544. meshes = selection.data;
  19545. len = selection.length;
  19546. }
  19547. else {
  19548. len = this.meshes.length;
  19549. meshes = this.meshes;
  19550. }
  19551. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19552. var mesh = meshes[meshIndex];
  19553. if (mesh.isBlocked) {
  19554. continue;
  19555. }
  19556. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19557. if (!mesh.isReady() || !mesh.isEnabled()) {
  19558. continue;
  19559. }
  19560. mesh.computeWorldMatrix();
  19561. // Intersections
  19562. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19563. this._meshesForIntersections.pushNoDuplicate(mesh);
  19564. }
  19565. // Switch to current LOD
  19566. var meshLOD = mesh.getLOD(this.activeCamera);
  19567. if (!meshLOD) {
  19568. continue;
  19569. }
  19570. mesh._preActivate();
  19571. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19572. this._activeMeshes.push(mesh);
  19573. this.activeCamera._activeMeshes.push(mesh);
  19574. mesh._activate(this._renderId);
  19575. if (meshLOD !== mesh) {
  19576. meshLOD._activate(this._renderId);
  19577. }
  19578. this._activeMesh(mesh, meshLOD);
  19579. }
  19580. }
  19581. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19582. // Particle systems
  19583. this._particlesDuration.beginMonitoring();
  19584. if (this.particlesEnabled) {
  19585. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19586. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19587. var particleSystem = this.particleSystems[particleIndex];
  19588. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19589. continue;
  19590. }
  19591. var emitter = particleSystem.emitter;
  19592. if (!emitter.position || emitter.isEnabled()) {
  19593. this._activeParticleSystems.push(particleSystem);
  19594. particleSystem.animate();
  19595. this._renderingManager.dispatchParticles(particleSystem);
  19596. }
  19597. }
  19598. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19599. }
  19600. this._particlesDuration.endMonitoring(false);
  19601. };
  19602. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19603. if (mesh.skeleton && this.skeletonsEnabled) {
  19604. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19605. mesh.skeleton.prepare();
  19606. }
  19607. if (!mesh.computeBonesUsingShaders) {
  19608. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19609. }
  19610. }
  19611. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19612. var boundingInfo = sourceMesh.getBoundingInfo();
  19613. if (boundingInfo) {
  19614. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19615. }
  19616. }
  19617. if (mesh && mesh.subMeshes) {
  19618. // Submeshes Octrees
  19619. var len;
  19620. var subMeshes;
  19621. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19622. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19623. len = intersections.length;
  19624. subMeshes = intersections.data;
  19625. }
  19626. else {
  19627. subMeshes = mesh.subMeshes;
  19628. len = subMeshes.length;
  19629. }
  19630. for (var subIndex = 0; subIndex < len; subIndex++) {
  19631. var subMesh = subMeshes[subIndex];
  19632. this._evaluateSubMesh(subMesh, mesh);
  19633. }
  19634. }
  19635. };
  19636. Scene.prototype.updateTransformMatrix = function (force) {
  19637. if (!this.activeCamera) {
  19638. return;
  19639. }
  19640. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19641. };
  19642. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19643. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19644. };
  19645. Scene.prototype._renderForCamera = function (camera) {
  19646. if (camera && camera._skipRendering) {
  19647. return;
  19648. }
  19649. var engine = this._engine;
  19650. this.activeCamera = camera;
  19651. if (!this.activeCamera)
  19652. throw new Error("Active camera not set");
  19653. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19654. // Viewport
  19655. engine.setViewport(this.activeCamera.viewport);
  19656. // Camera
  19657. this.resetCachedMaterial();
  19658. this._renderId++;
  19659. this.activeCamera.update();
  19660. this.updateTransformMatrix();
  19661. if (camera._alternateCamera) {
  19662. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19663. this._alternateRendering = true;
  19664. }
  19665. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19666. // Meshes
  19667. this._evaluateActiveMeshes();
  19668. // Software skinning
  19669. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19670. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19671. mesh.applySkeleton(mesh.skeleton);
  19672. }
  19673. // Render targets
  19674. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19675. var needsRestoreFrameBuffer = false;
  19676. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19677. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19678. }
  19679. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19680. this._intermediateRendering = true;
  19681. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19682. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19683. var renderTarget = this._renderTargets.data[renderIndex];
  19684. if (renderTarget._shouldRender()) {
  19685. this._renderId++;
  19686. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19687. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19688. }
  19689. }
  19690. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19691. this._intermediateRendering = false;
  19692. this._renderId++;
  19693. needsRestoreFrameBuffer = true; // Restore back buffer
  19694. }
  19695. // Render HighlightLayer Texture
  19696. var stencilState = this._engine.getStencilBuffer();
  19697. var renderhighlights = false;
  19698. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19699. this._intermediateRendering = true;
  19700. for (var i = 0; i < this.highlightLayers.length; i++) {
  19701. var highlightLayer = this.highlightLayers[i];
  19702. if (highlightLayer.shouldRender() &&
  19703. (!highlightLayer.camera ||
  19704. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19705. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19706. renderhighlights = true;
  19707. var renderTarget = highlightLayer._mainTexture;
  19708. if (renderTarget._shouldRender()) {
  19709. this._renderId++;
  19710. renderTarget.render(false, false);
  19711. needsRestoreFrameBuffer = true;
  19712. }
  19713. }
  19714. }
  19715. this._intermediateRendering = false;
  19716. this._renderId++;
  19717. }
  19718. if (needsRestoreFrameBuffer) {
  19719. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19720. }
  19721. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19722. // Prepare Frame
  19723. this.postProcessManager._prepareFrame();
  19724. this._renderDuration.beginMonitoring();
  19725. // Backgrounds
  19726. var layerIndex;
  19727. var layer;
  19728. if (this.layers.length) {
  19729. engine.setDepthBuffer(false);
  19730. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19731. layer = this.layers[layerIndex];
  19732. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19733. layer.render();
  19734. }
  19735. }
  19736. engine.setDepthBuffer(true);
  19737. }
  19738. // Render
  19739. BABYLON.Tools.StartPerformanceCounter("Main render");
  19740. // Activate HighlightLayer stencil
  19741. if (renderhighlights) {
  19742. this._engine.setStencilBuffer(true);
  19743. }
  19744. this._renderingManager.render(null, null, true, true);
  19745. // Restore HighlightLayer stencil
  19746. if (renderhighlights) {
  19747. this._engine.setStencilBuffer(stencilState);
  19748. }
  19749. BABYLON.Tools.EndPerformanceCounter("Main render");
  19750. // Bounding boxes
  19751. if (this._boundingBoxRenderer) {
  19752. this._boundingBoxRenderer.render();
  19753. }
  19754. // Lens flares
  19755. if (this.lensFlaresEnabled) {
  19756. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19757. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19758. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19759. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19760. lensFlareSystem.render();
  19761. }
  19762. }
  19763. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19764. }
  19765. // Foregrounds
  19766. if (this.layers.length) {
  19767. engine.setDepthBuffer(false);
  19768. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19769. layer = this.layers[layerIndex];
  19770. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19771. layer.render();
  19772. }
  19773. }
  19774. engine.setDepthBuffer(true);
  19775. }
  19776. // Highlight Layer
  19777. if (renderhighlights) {
  19778. engine.setDepthBuffer(false);
  19779. for (var i = 0; i < this.highlightLayers.length; i++) {
  19780. if (this.highlightLayers[i].shouldRender()) {
  19781. this.highlightLayers[i].render();
  19782. }
  19783. }
  19784. engine.setDepthBuffer(true);
  19785. }
  19786. this._renderDuration.endMonitoring(false);
  19787. // Finalize frame
  19788. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19789. // Reset some special arrays
  19790. this._renderTargets.reset();
  19791. this._alternateRendering = false;
  19792. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19793. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19794. };
  19795. Scene.prototype._processSubCameras = function (camera) {
  19796. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19797. this._renderForCamera(camera);
  19798. return;
  19799. }
  19800. // Update camera
  19801. if (this.activeCamera) {
  19802. this.activeCamera.update();
  19803. }
  19804. // rig cameras
  19805. for (var index = 0; index < camera._rigCameras.length; index++) {
  19806. this._renderForCamera(camera._rigCameras[index]);
  19807. }
  19808. this.activeCamera = camera;
  19809. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19810. };
  19811. Scene.prototype._checkIntersections = function () {
  19812. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19813. var sourceMesh = this._meshesForIntersections.data[index];
  19814. if (!sourceMesh.actionManager) {
  19815. continue;
  19816. }
  19817. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19818. var action = sourceMesh.actionManager.actions[actionIndex];
  19819. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19820. var parameters = action.getTriggerParameter();
  19821. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19822. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19823. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19824. if (areIntersecting && currentIntersectionInProgress === -1) {
  19825. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19826. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19827. sourceMesh._intersectionsInProgress.push(otherMesh);
  19828. }
  19829. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19830. sourceMesh._intersectionsInProgress.push(otherMesh);
  19831. }
  19832. }
  19833. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19834. //They intersected, and now they don't.
  19835. //is this trigger an exit trigger? execute an event.
  19836. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19837. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19838. }
  19839. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19840. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19841. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19842. }
  19843. }
  19844. }
  19845. }
  19846. }
  19847. };
  19848. Scene.prototype.render = function () {
  19849. if (this.isDisposed) {
  19850. return;
  19851. }
  19852. this._interFrameDuration.endMonitoring();
  19853. this._lastFrameDuration.beginMonitoring();
  19854. this._particlesDuration.fetchNewFrame();
  19855. this._spritesDuration.fetchNewFrame();
  19856. this._activeParticles.fetchNewFrame();
  19857. this._renderDuration.fetchNewFrame();
  19858. this._totalVertices.fetchNewFrame();
  19859. this._activeIndices.fetchNewFrame();
  19860. this._activeBones.fetchNewFrame();
  19861. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19862. this._meshesForIntersections.reset();
  19863. this.resetCachedMaterial();
  19864. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19865. // Actions
  19866. if (this.actionManager) {
  19867. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  19868. }
  19869. //Simplification Queue
  19870. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19871. this.simplificationQueue.executeNext();
  19872. }
  19873. if (this._engine.isDeterministicLockStep()) {
  19874. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19875. var defaultTimeStep = (60.0 / 1000.0);
  19876. if (this._physicsEngine) {
  19877. defaultTimeStep = this._physicsEngine.getTimeStep();
  19878. }
  19879. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19880. this._timeAccumulator += deltaTime;
  19881. // compute the amount of fixed steps we should have taken since the last step
  19882. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19883. internalSteps = Math.min(internalSteps, maxSubSteps);
  19884. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19885. this.onBeforeStepObservable.notifyObservers(this);
  19886. // Animations
  19887. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19888. this._animate();
  19889. // Physics
  19890. if (this._physicsEngine) {
  19891. BABYLON.Tools.StartPerformanceCounter("Physics");
  19892. this._physicsEngine._step(defaultTimeStep);
  19893. BABYLON.Tools.EndPerformanceCounter("Physics");
  19894. }
  19895. this._timeAccumulator -= defaultTimeStep;
  19896. this.onAfterStepObservable.notifyObservers(this);
  19897. this._currentStepId++;
  19898. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19899. this._evaluateActiveMeshes();
  19900. }
  19901. }
  19902. }
  19903. else {
  19904. // Animations
  19905. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19906. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19907. this._animate();
  19908. // Physics
  19909. if (this._physicsEngine) {
  19910. BABYLON.Tools.StartPerformanceCounter("Physics");
  19911. this._physicsEngine._step(deltaTime / 1000.0);
  19912. BABYLON.Tools.EndPerformanceCounter("Physics");
  19913. }
  19914. }
  19915. // Before render
  19916. this.onBeforeRenderObservable.notifyObservers(this);
  19917. // Customs render targets
  19918. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19919. var engine = this.getEngine();
  19920. var currentActiveCamera = this.activeCamera;
  19921. if (this.renderTargetsEnabled) {
  19922. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19923. this._intermediateRendering = true;
  19924. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19925. var renderTarget = this.customRenderTargets[customIndex];
  19926. if (renderTarget._shouldRender()) {
  19927. this._renderId++;
  19928. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19929. if (!this.activeCamera)
  19930. throw new Error("Active camera not set");
  19931. // Viewport
  19932. engine.setViewport(this.activeCamera.viewport);
  19933. // Camera
  19934. this.updateTransformMatrix();
  19935. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19936. }
  19937. }
  19938. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19939. this._intermediateRendering = false;
  19940. this._renderId++;
  19941. }
  19942. // Restore back buffer
  19943. if (this.customRenderTargets.length > 0) {
  19944. engine.restoreDefaultFramebuffer();
  19945. }
  19946. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19947. this.activeCamera = currentActiveCamera;
  19948. // Procedural textures
  19949. if (this.proceduralTexturesEnabled) {
  19950. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19951. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19952. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19953. if (proceduralTexture._shouldRender()) {
  19954. proceduralTexture.render();
  19955. }
  19956. }
  19957. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19958. }
  19959. // Clear
  19960. if (this.autoClearDepthAndStencil || this.autoClear) {
  19961. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19962. }
  19963. // Shadows
  19964. if (this.shadowsEnabled) {
  19965. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19966. var light = this.lights[lightIndex];
  19967. var shadowGenerator = light.getShadowGenerator();
  19968. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19969. var shadowMap = (shadowGenerator.getShadowMap());
  19970. if (this.textures.indexOf(shadowMap) !== -1) {
  19971. this._renderTargets.push(shadowMap);
  19972. }
  19973. }
  19974. }
  19975. }
  19976. // Depth renderer
  19977. if (this._depthRenderer) {
  19978. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19979. }
  19980. // Geometry renderer
  19981. if (this._geometryBufferRenderer) {
  19982. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19983. }
  19984. // RenderPipeline
  19985. if (this._postProcessRenderPipelineManager) {
  19986. this._postProcessRenderPipelineManager.update();
  19987. }
  19988. // Multi-cameras?
  19989. if (this.activeCameras.length > 0) {
  19990. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19991. if (cameraIndex > 0) {
  19992. this._engine.clear(null, false, true, true);
  19993. }
  19994. this._processSubCameras(this.activeCameras[cameraIndex]);
  19995. }
  19996. }
  19997. else {
  19998. if (!this.activeCamera) {
  19999. throw new Error("No camera defined");
  20000. }
  20001. this._processSubCameras(this.activeCamera);
  20002. }
  20003. // Intersection checks
  20004. this._checkIntersections();
  20005. // Update the audio listener attached to the camera
  20006. if (BABYLON.AudioEngine) {
  20007. this._updateAudioParameters();
  20008. }
  20009. // After render
  20010. if (this.afterRender) {
  20011. this.afterRender();
  20012. }
  20013. this.onAfterRenderObservable.notifyObservers(this);
  20014. // Cleaning
  20015. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20016. var data = this._toBeDisposed.data[index];
  20017. if (data) {
  20018. data.dispose();
  20019. }
  20020. this._toBeDisposed[index] = null;
  20021. }
  20022. this._toBeDisposed.reset();
  20023. if (this.dumpNextRenderTargets) {
  20024. this.dumpNextRenderTargets = false;
  20025. }
  20026. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  20027. this._interFrameDuration.beginMonitoring();
  20028. this._lastFrameDuration.endMonitoring();
  20029. this._activeBones.addCount(0, true);
  20030. this._activeIndices.addCount(0, true);
  20031. this._activeParticles.addCount(0, true);
  20032. };
  20033. Scene.prototype._updateAudioParameters = function () {
  20034. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20035. return;
  20036. }
  20037. var listeningCamera;
  20038. var audioEngine = BABYLON.Engine.audioEngine;
  20039. if (this.activeCameras.length > 0) {
  20040. listeningCamera = this.activeCameras[0];
  20041. }
  20042. else {
  20043. listeningCamera = this.activeCamera;
  20044. }
  20045. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20046. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20047. // for VR cameras
  20048. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20049. listeningCamera = listeningCamera.rigCameras[0];
  20050. }
  20051. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20052. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20053. cameraDirection.normalize();
  20054. // To avoid some errors on GearVR
  20055. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20056. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20057. }
  20058. var i;
  20059. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20060. var sound = this.mainSoundTrack.soundCollection[i];
  20061. if (sound.useCustomAttenuation) {
  20062. sound.updateDistanceFromListener();
  20063. }
  20064. }
  20065. for (i = 0; i < this.soundTracks.length; i++) {
  20066. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20067. sound = this.soundTracks[i].soundCollection[j];
  20068. if (sound.useCustomAttenuation) {
  20069. sound.updateDistanceFromListener();
  20070. }
  20071. }
  20072. }
  20073. }
  20074. };
  20075. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20076. // Audio
  20077. get: function () {
  20078. return this._audioEnabled;
  20079. },
  20080. set: function (value) {
  20081. this._audioEnabled = value;
  20082. if (BABYLON.AudioEngine) {
  20083. if (this._audioEnabled) {
  20084. this._enableAudio();
  20085. }
  20086. else {
  20087. this._disableAudio();
  20088. }
  20089. }
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Scene.prototype._disableAudio = function () {
  20095. var i;
  20096. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20097. this.mainSoundTrack.soundCollection[i].pause();
  20098. }
  20099. for (i = 0; i < this.soundTracks.length; i++) {
  20100. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20101. this.soundTracks[i].soundCollection[j].pause();
  20102. }
  20103. }
  20104. };
  20105. Scene.prototype._enableAudio = function () {
  20106. var i;
  20107. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20108. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20109. this.mainSoundTrack.soundCollection[i].play();
  20110. }
  20111. }
  20112. for (i = 0; i < this.soundTracks.length; i++) {
  20113. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20114. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20115. this.soundTracks[i].soundCollection[j].play();
  20116. }
  20117. }
  20118. }
  20119. };
  20120. Object.defineProperty(Scene.prototype, "headphone", {
  20121. get: function () {
  20122. return this._headphone;
  20123. },
  20124. set: function (value) {
  20125. this._headphone = value;
  20126. if (BABYLON.AudioEngine) {
  20127. if (this._headphone) {
  20128. this._switchAudioModeForHeadphones();
  20129. }
  20130. else {
  20131. this._switchAudioModeForNormalSpeakers();
  20132. }
  20133. }
  20134. },
  20135. enumerable: true,
  20136. configurable: true
  20137. });
  20138. Scene.prototype._switchAudioModeForHeadphones = function () {
  20139. this.mainSoundTrack.switchPanningModelToHRTF();
  20140. for (var i = 0; i < this.soundTracks.length; i++) {
  20141. this.soundTracks[i].switchPanningModelToHRTF();
  20142. }
  20143. };
  20144. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20145. this.mainSoundTrack.switchPanningModelToEqualPower();
  20146. for (var i = 0; i < this.soundTracks.length; i++) {
  20147. this.soundTracks[i].switchPanningModelToEqualPower();
  20148. }
  20149. };
  20150. Scene.prototype.enableDepthRenderer = function () {
  20151. if (this._depthRenderer) {
  20152. return this._depthRenderer;
  20153. }
  20154. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20155. return this._depthRenderer;
  20156. };
  20157. Scene.prototype.disableDepthRenderer = function () {
  20158. if (!this._depthRenderer) {
  20159. return;
  20160. }
  20161. this._depthRenderer.dispose();
  20162. this._depthRenderer = null;
  20163. };
  20164. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20165. if (ratio === void 0) { ratio = 1; }
  20166. if (this._geometryBufferRenderer) {
  20167. return this._geometryBufferRenderer;
  20168. }
  20169. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20170. if (!this._geometryBufferRenderer.isSupported) {
  20171. this._geometryBufferRenderer = null;
  20172. }
  20173. return this._geometryBufferRenderer;
  20174. };
  20175. Scene.prototype.disableGeometryBufferRenderer = function () {
  20176. if (!this._geometryBufferRenderer) {
  20177. return;
  20178. }
  20179. this._geometryBufferRenderer.dispose();
  20180. this._geometryBufferRenderer = null;
  20181. };
  20182. Scene.prototype.freezeMaterials = function () {
  20183. for (var i = 0; i < this.materials.length; i++) {
  20184. this.materials[i].freeze();
  20185. }
  20186. };
  20187. Scene.prototype.unfreezeMaterials = function () {
  20188. for (var i = 0; i < this.materials.length; i++) {
  20189. this.materials[i].unfreeze();
  20190. }
  20191. };
  20192. Scene.prototype.dispose = function () {
  20193. this.beforeRender = null;
  20194. this.afterRender = null;
  20195. this.skeletons = [];
  20196. this.morphTargetManagers = [];
  20197. this.importedMeshesFiles = new Array();
  20198. this.resetCachedMaterial();
  20199. if (this._depthRenderer) {
  20200. this._depthRenderer.dispose();
  20201. }
  20202. if (this._gamepadManager) {
  20203. this._gamepadManager.dispose();
  20204. this._gamepadManager = null;
  20205. }
  20206. // Smart arrays
  20207. if (this.activeCamera) {
  20208. this.activeCamera._activeMeshes.dispose();
  20209. this.activeCamera = null;
  20210. }
  20211. this._activeMeshes.dispose();
  20212. this._renderingManager.dispose();
  20213. this._processedMaterials.dispose();
  20214. this._activeParticleSystems.dispose();
  20215. this._activeSkeletons.dispose();
  20216. this._softwareSkinnedMeshes.dispose();
  20217. this._renderTargets.dispose();
  20218. if (this._boundingBoxRenderer) {
  20219. this._boundingBoxRenderer.dispose();
  20220. }
  20221. this._meshesForIntersections.dispose();
  20222. this._toBeDisposed.dispose();
  20223. // Debug layer
  20224. if (this._debugLayer) {
  20225. this._debugLayer.hide();
  20226. }
  20227. // Events
  20228. this.onDisposeObservable.notifyObservers(this);
  20229. this.onDisposeObservable.clear();
  20230. this.onBeforeRenderObservable.clear();
  20231. this.onAfterRenderObservable.clear();
  20232. this.OnBeforeRenderTargetsRenderObservable.clear();
  20233. this.OnAfterRenderTargetsRenderObservable.clear();
  20234. this.onAfterStepObservable.clear();
  20235. this.onBeforeStepObservable.clear();
  20236. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20237. this.onAfterActiveMeshesEvaluationObservable.clear();
  20238. this.detachControl();
  20239. // Release sounds & sounds tracks
  20240. if (BABYLON.AudioEngine) {
  20241. this.disposeSounds();
  20242. }
  20243. // VR Helper
  20244. if (this.VRHelper) {
  20245. this.VRHelper.dispose();
  20246. }
  20247. // Detach cameras
  20248. var canvas = this._engine.getRenderingCanvas();
  20249. if (canvas) {
  20250. var index;
  20251. for (index = 0; index < this.cameras.length; index++) {
  20252. this.cameras[index].detachControl(canvas);
  20253. }
  20254. }
  20255. // Release lights
  20256. while (this.lights.length) {
  20257. this.lights[0].dispose();
  20258. }
  20259. // Release meshes
  20260. while (this.meshes.length) {
  20261. this.meshes[0].dispose(true);
  20262. }
  20263. // Release cameras
  20264. while (this.cameras.length) {
  20265. this.cameras[0].dispose();
  20266. }
  20267. // Release materials
  20268. if (this.defaultMaterial) {
  20269. this.defaultMaterial.dispose();
  20270. }
  20271. while (this.multiMaterials.length) {
  20272. this.multiMaterials[0].dispose();
  20273. }
  20274. while (this.materials.length) {
  20275. this.materials[0].dispose();
  20276. }
  20277. // Release particles
  20278. while (this.particleSystems.length) {
  20279. this.particleSystems[0].dispose();
  20280. }
  20281. // Release sprites
  20282. while (this.spriteManagers.length) {
  20283. this.spriteManagers[0].dispose();
  20284. }
  20285. // Release postProcesses
  20286. while (this.postProcesses.length) {
  20287. this.postProcesses[0].dispose();
  20288. }
  20289. // Release layers
  20290. while (this.layers.length) {
  20291. this.layers[0].dispose();
  20292. }
  20293. while (this.highlightLayers.length) {
  20294. this.highlightLayers[0].dispose();
  20295. }
  20296. // Release textures
  20297. while (this.textures.length) {
  20298. this.textures[0].dispose();
  20299. }
  20300. // Release UBO
  20301. this._sceneUbo.dispose();
  20302. if (this._alternateSceneUbo) {
  20303. this._alternateSceneUbo.dispose();
  20304. }
  20305. // Post-processes
  20306. this.postProcessManager.dispose();
  20307. if (this._postProcessRenderPipelineManager) {
  20308. this._postProcessRenderPipelineManager.dispose();
  20309. }
  20310. // Physics
  20311. if (this._physicsEngine) {
  20312. this.disablePhysicsEngine();
  20313. }
  20314. // Remove from engine
  20315. index = this._engine.scenes.indexOf(this);
  20316. if (index > -1) {
  20317. this._engine.scenes.splice(index, 1);
  20318. }
  20319. this._engine.wipeCaches();
  20320. this._isDisposed = true;
  20321. };
  20322. Object.defineProperty(Scene.prototype, "isDisposed", {
  20323. get: function () {
  20324. return this._isDisposed;
  20325. },
  20326. enumerable: true,
  20327. configurable: true
  20328. });
  20329. // Release sounds & sounds tracks
  20330. Scene.prototype.disposeSounds = function () {
  20331. if (!this._mainSoundTrack) {
  20332. return;
  20333. }
  20334. this.mainSoundTrack.dispose();
  20335. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20336. this.soundTracks[scIndex].dispose();
  20337. }
  20338. };
  20339. // Octrees
  20340. Scene.prototype.getWorldExtends = function () {
  20341. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20342. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20343. for (var index = 0; index < this.meshes.length; index++) {
  20344. var mesh = this.meshes[index];
  20345. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20346. continue;
  20347. }
  20348. mesh.computeWorldMatrix(true);
  20349. var boundingInfo = mesh.getBoundingInfo();
  20350. if (boundingInfo) {
  20351. var minBox = boundingInfo.boundingBox.minimumWorld;
  20352. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20353. BABYLON.Tools.CheckExtends(minBox, min, max);
  20354. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20355. }
  20356. }
  20357. return {
  20358. min: min,
  20359. max: max
  20360. };
  20361. };
  20362. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20363. if (maxCapacity === void 0) { maxCapacity = 64; }
  20364. if (maxDepth === void 0) { maxDepth = 2; }
  20365. if (!this._selectionOctree) {
  20366. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20367. }
  20368. var worldExtends = this.getWorldExtends();
  20369. // Update octree
  20370. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20371. return this._selectionOctree;
  20372. };
  20373. // Picking
  20374. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20375. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20376. var engine = this._engine;
  20377. if (!camera) {
  20378. if (!this.activeCamera)
  20379. throw new Error("Active camera not set");
  20380. camera = this.activeCamera;
  20381. }
  20382. var cameraViewport = camera.viewport;
  20383. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20384. // Moving coordinates to local viewport world
  20385. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20386. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20387. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20388. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20389. };
  20390. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20391. if (!BABYLON.PickingInfo) {
  20392. return null;
  20393. }
  20394. var engine = this._engine;
  20395. if (!camera) {
  20396. if (!this.activeCamera)
  20397. throw new Error("Active camera not set");
  20398. camera = this.activeCamera;
  20399. }
  20400. var cameraViewport = camera.viewport;
  20401. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20402. var identity = BABYLON.Matrix.Identity();
  20403. // Moving coordinates to local viewport world
  20404. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20405. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20406. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20407. };
  20408. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20409. if (!BABYLON.PickingInfo) {
  20410. return null;
  20411. }
  20412. var pickingInfo = null;
  20413. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20414. var mesh = this.meshes[meshIndex];
  20415. if (predicate) {
  20416. if (!predicate(mesh)) {
  20417. continue;
  20418. }
  20419. }
  20420. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20421. continue;
  20422. }
  20423. var world = mesh.getWorldMatrix();
  20424. var ray = rayFunction(world);
  20425. var result = mesh.intersects(ray, fastCheck);
  20426. if (!result || !result.hit)
  20427. continue;
  20428. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20429. continue;
  20430. pickingInfo = result;
  20431. if (fastCheck) {
  20432. break;
  20433. }
  20434. }
  20435. return pickingInfo || new BABYLON.PickingInfo();
  20436. };
  20437. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20438. if (!BABYLON.PickingInfo) {
  20439. return null;
  20440. }
  20441. var pickingInfos = new Array();
  20442. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20443. var mesh = this.meshes[meshIndex];
  20444. if (predicate) {
  20445. if (!predicate(mesh)) {
  20446. continue;
  20447. }
  20448. }
  20449. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20450. continue;
  20451. }
  20452. var world = mesh.getWorldMatrix();
  20453. var ray = rayFunction(world);
  20454. var result = mesh.intersects(ray, false);
  20455. if (!result || !result.hit)
  20456. continue;
  20457. pickingInfos.push(result);
  20458. }
  20459. return pickingInfos;
  20460. };
  20461. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20462. if (!BABYLON.PickingInfo) {
  20463. return null;
  20464. }
  20465. var pickingInfo = null;
  20466. if (!camera) {
  20467. if (!this.activeCamera) {
  20468. return null;
  20469. }
  20470. camera = this.activeCamera;
  20471. }
  20472. if (this.spriteManagers.length > 0) {
  20473. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20474. var spriteManager = this.spriteManagers[spriteIndex];
  20475. if (!spriteManager.isPickable) {
  20476. continue;
  20477. }
  20478. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20479. if (!result || !result.hit)
  20480. continue;
  20481. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20482. continue;
  20483. pickingInfo = result;
  20484. if (fastCheck) {
  20485. break;
  20486. }
  20487. }
  20488. }
  20489. return pickingInfo || new BABYLON.PickingInfo();
  20490. };
  20491. /** Launch a ray to try to pick a mesh in the scene
  20492. * @param x position on screen
  20493. * @param y position on screen
  20494. * @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
  20495. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20496. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20497. */
  20498. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20499. var _this = this;
  20500. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20501. };
  20502. /** Launch a ray to try to pick a sprite in the scene
  20503. * @param x position on screen
  20504. * @param y position on screen
  20505. * @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
  20506. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20507. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20508. */
  20509. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20510. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20511. if (!ray) {
  20512. return null;
  20513. }
  20514. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20515. };
  20516. /** Use the given ray to pick a mesh in the scene
  20517. * @param ray The ray to use to pick meshes
  20518. * @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
  20519. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20520. */
  20521. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20522. var _this = this;
  20523. return this._internalPick(function (world) {
  20524. if (!_this._pickWithRayInverseMatrix) {
  20525. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20526. }
  20527. world.invertToRef(_this._pickWithRayInverseMatrix);
  20528. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20529. }, predicate, fastCheck);
  20530. };
  20531. /**
  20532. * Launch a ray to try to pick a mesh in the scene
  20533. * @param x X position on screen
  20534. * @param y Y position on screen
  20535. * @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
  20536. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20537. */
  20538. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20539. var _this = this;
  20540. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20541. };
  20542. /**
  20543. * Launch a ray to try to pick a mesh in the scene
  20544. * @param ray Ray to use
  20545. * @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
  20546. */
  20547. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20548. var _this = this;
  20549. return this._internalMultiPick(function (world) {
  20550. if (!_this._pickWithRayInverseMatrix) {
  20551. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20552. }
  20553. world.invertToRef(_this._pickWithRayInverseMatrix);
  20554. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20555. }, predicate);
  20556. };
  20557. Scene.prototype.setPointerOverMesh = function (mesh) {
  20558. if (this._pointerOverMesh === mesh) {
  20559. return;
  20560. }
  20561. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20562. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20563. }
  20564. this._pointerOverMesh = mesh;
  20565. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20566. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20567. }
  20568. };
  20569. Scene.prototype.getPointerOverMesh = function () {
  20570. return this._pointerOverMesh;
  20571. };
  20572. Scene.prototype.setPointerOverSprite = function (sprite) {
  20573. if (this._pointerOverSprite === sprite) {
  20574. return;
  20575. }
  20576. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20577. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20578. }
  20579. this._pointerOverSprite = sprite;
  20580. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20581. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20582. }
  20583. };
  20584. Scene.prototype.getPointerOverSprite = function () {
  20585. return this._pointerOverSprite;
  20586. };
  20587. // Physics
  20588. Scene.prototype.getPhysicsEngine = function () {
  20589. return this._physicsEngine;
  20590. };
  20591. /**
  20592. * Enables physics to the current scene
  20593. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20594. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20595. * @return {boolean} was the physics engine initialized
  20596. */
  20597. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20598. if (gravity === void 0) { gravity = null; }
  20599. if (this._physicsEngine) {
  20600. return true;
  20601. }
  20602. try {
  20603. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20604. return true;
  20605. }
  20606. catch (e) {
  20607. BABYLON.Tools.Error(e.message);
  20608. return false;
  20609. }
  20610. };
  20611. Scene.prototype.disablePhysicsEngine = function () {
  20612. if (!this._physicsEngine) {
  20613. return;
  20614. }
  20615. this._physicsEngine.dispose();
  20616. this._physicsEngine = null;
  20617. };
  20618. Scene.prototype.isPhysicsEnabled = function () {
  20619. return this._physicsEngine !== undefined;
  20620. };
  20621. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20622. var mesh = compound.parts[0].mesh;
  20623. if (mesh.physicsImpostor) {
  20624. mesh.physicsImpostor.dispose();
  20625. mesh.physicsImpostor = null;
  20626. }
  20627. };
  20628. // Misc.
  20629. Scene.prototype._rebuildGeometries = function () {
  20630. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20631. var geometry = _a[_i];
  20632. geometry._rebuild();
  20633. }
  20634. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20635. var mesh = _c[_b];
  20636. mesh._rebuild();
  20637. }
  20638. if (this.postProcessManager) {
  20639. this.postProcessManager._rebuild();
  20640. }
  20641. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20642. var layer = _e[_d];
  20643. layer._rebuild();
  20644. }
  20645. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20646. var highlightLayer = _g[_f];
  20647. highlightLayer._rebuild();
  20648. }
  20649. if (this._boundingBoxRenderer) {
  20650. this._boundingBoxRenderer._rebuild();
  20651. }
  20652. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20653. var system = _j[_h];
  20654. system.rebuild();
  20655. }
  20656. if (this._postProcessRenderPipelineManager) {
  20657. this._postProcessRenderPipelineManager._rebuild();
  20658. }
  20659. };
  20660. Scene.prototype._rebuildTextures = function () {
  20661. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20662. var texture = _a[_i];
  20663. texture._rebuild();
  20664. }
  20665. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20666. };
  20667. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20668. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20669. if (replace === void 0) { replace = false; }
  20670. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20671. // Dispose existing camera or light in replace mode.
  20672. if (replace) {
  20673. if (this.activeCamera) {
  20674. this.activeCamera.dispose();
  20675. this.activeCamera = null;
  20676. }
  20677. if (this.lights) {
  20678. for (var i = 0; i < this.lights.length; i++) {
  20679. this.lights[i].dispose();
  20680. }
  20681. }
  20682. }
  20683. // Light
  20684. if (this.lights.length === 0) {
  20685. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20686. }
  20687. // Camera
  20688. if (!this.activeCamera) {
  20689. var worldExtends = this.getWorldExtends();
  20690. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20691. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20692. var camera;
  20693. var radius = worldSize.length() * 1.5;
  20694. if (createArcRotateCamera) {
  20695. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20696. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20697. arcRotateCamera.wheelPrecision = 100 / radius;
  20698. camera = arcRotateCamera;
  20699. }
  20700. else {
  20701. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20702. freeCamera.setTarget(worldCenter);
  20703. camera = freeCamera;
  20704. }
  20705. camera.minZ = radius * 0.01;
  20706. camera.maxZ = radius * 100;
  20707. camera.speed = radius * 0.2;
  20708. this.activeCamera = camera;
  20709. var canvas = this.getEngine().getRenderingCanvas();
  20710. if (attachCameraControls && canvas) {
  20711. camera.attachControl(canvas);
  20712. }
  20713. }
  20714. };
  20715. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20716. if (pbr === void 0) { pbr = false; }
  20717. if (scale === void 0) { scale = 1000; }
  20718. if (blur === void 0) { blur = 0; }
  20719. if (environmentTexture) {
  20720. this.environmentTexture = environmentTexture;
  20721. }
  20722. if (!this.environmentTexture) {
  20723. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20724. return null;
  20725. }
  20726. // Skybox
  20727. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20728. if (pbr) {
  20729. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20730. hdrSkyboxMaterial.backFaceCulling = false;
  20731. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20732. if (hdrSkyboxMaterial.reflectionTexture) {
  20733. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20734. }
  20735. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20736. hdrSkyboxMaterial.disableLighting = true;
  20737. hdrSkyboxMaterial.twoSidedLighting = true;
  20738. hdrSkybox.infiniteDistance = true;
  20739. hdrSkybox.material = hdrSkyboxMaterial;
  20740. }
  20741. else {
  20742. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20743. skyboxMaterial.backFaceCulling = false;
  20744. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20745. if (skyboxMaterial.reflectionTexture) {
  20746. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20747. }
  20748. skyboxMaterial.disableLighting = true;
  20749. hdrSkybox.infiniteDistance = true;
  20750. hdrSkybox.material = skyboxMaterial;
  20751. }
  20752. return hdrSkybox;
  20753. };
  20754. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20755. if (webVROptions === void 0) { webVROptions = {}; }
  20756. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20757. };
  20758. // Tags
  20759. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20760. if (tagsQuery === undefined) {
  20761. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20762. return list;
  20763. }
  20764. var listByTags = [];
  20765. forEach = forEach || (function (item) { return; });
  20766. for (var i in list) {
  20767. var item = list[i];
  20768. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20769. listByTags.push(item);
  20770. forEach(item);
  20771. }
  20772. }
  20773. return listByTags;
  20774. };
  20775. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20776. return this._getByTags(this.meshes, tagsQuery, forEach);
  20777. };
  20778. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20779. return this._getByTags(this.cameras, tagsQuery, forEach);
  20780. };
  20781. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20782. return this._getByTags(this.lights, tagsQuery, forEach);
  20783. };
  20784. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20785. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20786. };
  20787. /**
  20788. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20789. * This allowed control for front to back rendering or reversly depending of the special needs.
  20790. *
  20791. * @param renderingGroupId The rendering group id corresponding to its index
  20792. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20793. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20794. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20795. */
  20796. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20800. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20801. };
  20802. /**
  20803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20804. *
  20805. * @param renderingGroupId The rendering group id corresponding to its index
  20806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20807. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20808. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20809. */
  20810. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20811. if (depth === void 0) { depth = true; }
  20812. if (stencil === void 0) { stencil = true; }
  20813. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20814. };
  20815. /**
  20816. * Will flag all materials as dirty to trigger new shader compilation
  20817. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20818. */
  20819. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20820. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20821. var material = _a[_i];
  20822. if (predicate && !predicate(material)) {
  20823. continue;
  20824. }
  20825. material.markAsDirty(flag);
  20826. }
  20827. };
  20828. // Statics
  20829. Scene._FOGMODE_NONE = 0;
  20830. Scene._FOGMODE_EXP = 1;
  20831. Scene._FOGMODE_EXP2 = 2;
  20832. Scene._FOGMODE_LINEAR = 3;
  20833. Scene._uniqueIdCounter = 0;
  20834. Scene.MinDeltaTime = 1.0;
  20835. Scene.MaxDeltaTime = 1000.0;
  20836. /** The distance in pixel that you have to move to prevent some events */
  20837. Scene.DragMovementThreshold = 10; // in pixels
  20838. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20839. Scene.LongPressDelay = 500; // in milliseconds
  20840. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20841. Scene.DoubleClickDelay = 300; // in milliseconds
  20842. /** If you need to check double click without raising a single click at first click, enable this flag */
  20843. Scene.ExclusiveDoubleClickMode = false;
  20844. return Scene;
  20845. }());
  20846. BABYLON.Scene = Scene;
  20847. })(BABYLON || (BABYLON = {}));
  20848. //# sourceMappingURL=babylon.scene.js.map
  20849. var BABYLON;
  20850. (function (BABYLON) {
  20851. var Buffer = /** @class */ (function () {
  20852. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20853. if (instanced === void 0) { instanced = false; }
  20854. if (engine instanceof BABYLON.Mesh) {
  20855. this._engine = engine.getScene().getEngine();
  20856. }
  20857. else {
  20858. this._engine = engine;
  20859. }
  20860. this._updatable = updatable;
  20861. this._data = data;
  20862. this._strideSize = stride;
  20863. if (!postponeInternalCreation) {
  20864. this.create();
  20865. }
  20866. this._instanced = instanced;
  20867. this._instanceDivisor = instanced ? 1 : 0;
  20868. }
  20869. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20870. // a lot of these parameters are ignored as they are overriden by the buffer
  20871. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20872. };
  20873. // Properties
  20874. Buffer.prototype.isUpdatable = function () {
  20875. return this._updatable;
  20876. };
  20877. Buffer.prototype.getData = function () {
  20878. return this._data;
  20879. };
  20880. Buffer.prototype.getBuffer = function () {
  20881. return this._buffer;
  20882. };
  20883. Buffer.prototype.getStrideSize = function () {
  20884. return this._strideSize;
  20885. };
  20886. Buffer.prototype.getIsInstanced = function () {
  20887. return this._instanced;
  20888. };
  20889. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20890. get: function () {
  20891. return this._instanceDivisor;
  20892. },
  20893. set: function (value) {
  20894. this._instanceDivisor = value;
  20895. if (value == 0) {
  20896. this._instanced = false;
  20897. }
  20898. else {
  20899. this._instanced = true;
  20900. }
  20901. },
  20902. enumerable: true,
  20903. configurable: true
  20904. });
  20905. // Methods
  20906. Buffer.prototype.create = function (data) {
  20907. if (data === void 0) { data = null; }
  20908. if (!data && this._buffer) {
  20909. return; // nothing to do
  20910. }
  20911. data = data || this._data;
  20912. if (!data) {
  20913. return;
  20914. }
  20915. if (!this._buffer) {
  20916. if (this._updatable) {
  20917. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20918. this._data = data;
  20919. }
  20920. else {
  20921. this._buffer = this._engine.createVertexBuffer(data);
  20922. }
  20923. }
  20924. else if (this._updatable) {
  20925. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20926. this._data = data;
  20927. }
  20928. };
  20929. Buffer.prototype._rebuild = function () {
  20930. this._buffer = null;
  20931. this.create(this._data);
  20932. };
  20933. Buffer.prototype.update = function (data) {
  20934. this.create(data);
  20935. };
  20936. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20937. if (!this._buffer) {
  20938. return;
  20939. }
  20940. if (this._updatable) {
  20941. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20942. this._data = null;
  20943. }
  20944. };
  20945. Buffer.prototype.dispose = function () {
  20946. if (!this._buffer) {
  20947. return;
  20948. }
  20949. if (this._engine._releaseBuffer(this._buffer)) {
  20950. this._buffer = null;
  20951. }
  20952. };
  20953. return Buffer;
  20954. }());
  20955. BABYLON.Buffer = Buffer;
  20956. })(BABYLON || (BABYLON = {}));
  20957. //# sourceMappingURL=babylon.buffer.js.map
  20958. var BABYLON;
  20959. (function (BABYLON) {
  20960. var VertexBuffer = /** @class */ (function () {
  20961. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20962. if (!stride) {
  20963. // Deduce stride from kind
  20964. switch (kind) {
  20965. case VertexBuffer.PositionKind:
  20966. stride = 3;
  20967. break;
  20968. case VertexBuffer.NormalKind:
  20969. stride = 3;
  20970. break;
  20971. case VertexBuffer.UVKind:
  20972. case VertexBuffer.UV2Kind:
  20973. case VertexBuffer.UV3Kind:
  20974. case VertexBuffer.UV4Kind:
  20975. case VertexBuffer.UV5Kind:
  20976. case VertexBuffer.UV6Kind:
  20977. stride = 2;
  20978. break;
  20979. case VertexBuffer.TangentKind:
  20980. case VertexBuffer.ColorKind:
  20981. stride = 4;
  20982. break;
  20983. case VertexBuffer.MatricesIndicesKind:
  20984. case VertexBuffer.MatricesIndicesExtraKind:
  20985. stride = 4;
  20986. break;
  20987. case VertexBuffer.MatricesWeightsKind:
  20988. case VertexBuffer.MatricesWeightsExtraKind:
  20989. default:
  20990. stride = 4;
  20991. break;
  20992. }
  20993. }
  20994. if (data instanceof BABYLON.Buffer) {
  20995. if (!stride) {
  20996. stride = data.getStrideSize();
  20997. }
  20998. this._buffer = data;
  20999. this._ownsBuffer = false;
  21000. }
  21001. else {
  21002. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21003. this._ownsBuffer = true;
  21004. }
  21005. this._stride = stride;
  21006. this._offset = offset ? offset : 0;
  21007. this._size = size ? size : stride;
  21008. this._kind = kind;
  21009. }
  21010. VertexBuffer.prototype._rebuild = function () {
  21011. if (!this._buffer) {
  21012. return;
  21013. }
  21014. this._buffer._rebuild();
  21015. };
  21016. /**
  21017. * Returns the kind of the VertexBuffer (string).
  21018. */
  21019. VertexBuffer.prototype.getKind = function () {
  21020. return this._kind;
  21021. };
  21022. // Properties
  21023. /**
  21024. * Boolean : is the VertexBuffer updatable ?
  21025. */
  21026. VertexBuffer.prototype.isUpdatable = function () {
  21027. return this._buffer.isUpdatable();
  21028. };
  21029. /**
  21030. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21031. */
  21032. VertexBuffer.prototype.getData = function () {
  21033. return this._buffer.getData();
  21034. };
  21035. /**
  21036. * Returns the WebGLBuffer associated to the VertexBuffer.
  21037. */
  21038. VertexBuffer.prototype.getBuffer = function () {
  21039. return this._buffer.getBuffer();
  21040. };
  21041. /**
  21042. * Returns the stride of the VertexBuffer (integer).
  21043. */
  21044. VertexBuffer.prototype.getStrideSize = function () {
  21045. return this._stride;
  21046. };
  21047. /**
  21048. * Returns the offset (integer).
  21049. */
  21050. VertexBuffer.prototype.getOffset = function () {
  21051. return this._offset;
  21052. };
  21053. /**
  21054. * Returns the VertexBuffer total size (integer).
  21055. */
  21056. VertexBuffer.prototype.getSize = function () {
  21057. return this._size;
  21058. };
  21059. /**
  21060. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21061. */
  21062. VertexBuffer.prototype.getIsInstanced = function () {
  21063. return this._buffer.getIsInstanced();
  21064. };
  21065. /**
  21066. * Returns the instancing divisor, zero for non-instanced (integer).
  21067. */
  21068. VertexBuffer.prototype.getInstanceDivisor = function () {
  21069. return this._buffer.instanceDivisor;
  21070. };
  21071. // Methods
  21072. /**
  21073. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21074. * Returns the created WebGLBuffer.
  21075. */
  21076. VertexBuffer.prototype.create = function (data) {
  21077. return this._buffer.create(data);
  21078. };
  21079. /**
  21080. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21081. * Returns the updated WebGLBuffer.
  21082. */
  21083. VertexBuffer.prototype.update = function (data) {
  21084. return this._buffer.update(data);
  21085. };
  21086. /**
  21087. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21088. * Returns the directly updated WebGLBuffer.
  21089. */
  21090. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21091. return this._buffer.updateDirectly(data, offset);
  21092. };
  21093. /**
  21094. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21095. */
  21096. VertexBuffer.prototype.dispose = function () {
  21097. if (this._ownsBuffer) {
  21098. this._buffer.dispose();
  21099. }
  21100. };
  21101. Object.defineProperty(VertexBuffer, "PositionKind", {
  21102. get: function () {
  21103. return VertexBuffer._PositionKind;
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. Object.defineProperty(VertexBuffer, "NormalKind", {
  21109. get: function () {
  21110. return VertexBuffer._NormalKind;
  21111. },
  21112. enumerable: true,
  21113. configurable: true
  21114. });
  21115. Object.defineProperty(VertexBuffer, "TangentKind", {
  21116. get: function () {
  21117. return VertexBuffer._TangentKind;
  21118. },
  21119. enumerable: true,
  21120. configurable: true
  21121. });
  21122. Object.defineProperty(VertexBuffer, "UVKind", {
  21123. get: function () {
  21124. return VertexBuffer._UVKind;
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21130. get: function () {
  21131. return VertexBuffer._UV2Kind;
  21132. },
  21133. enumerable: true,
  21134. configurable: true
  21135. });
  21136. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21137. get: function () {
  21138. return VertexBuffer._UV3Kind;
  21139. },
  21140. enumerable: true,
  21141. configurable: true
  21142. });
  21143. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21144. get: function () {
  21145. return VertexBuffer._UV4Kind;
  21146. },
  21147. enumerable: true,
  21148. configurable: true
  21149. });
  21150. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21151. get: function () {
  21152. return VertexBuffer._UV5Kind;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21158. get: function () {
  21159. return VertexBuffer._UV6Kind;
  21160. },
  21161. enumerable: true,
  21162. configurable: true
  21163. });
  21164. Object.defineProperty(VertexBuffer, "ColorKind", {
  21165. get: function () {
  21166. return VertexBuffer._ColorKind;
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21172. get: function () {
  21173. return VertexBuffer._MatricesIndicesKind;
  21174. },
  21175. enumerable: true,
  21176. configurable: true
  21177. });
  21178. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21179. get: function () {
  21180. return VertexBuffer._MatricesWeightsKind;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21186. get: function () {
  21187. return VertexBuffer._MatricesIndicesExtraKind;
  21188. },
  21189. enumerable: true,
  21190. configurable: true
  21191. });
  21192. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21193. get: function () {
  21194. return VertexBuffer._MatricesWeightsExtraKind;
  21195. },
  21196. enumerable: true,
  21197. configurable: true
  21198. });
  21199. // Enums
  21200. VertexBuffer._PositionKind = "position";
  21201. VertexBuffer._NormalKind = "normal";
  21202. VertexBuffer._TangentKind = "tangent";
  21203. VertexBuffer._UVKind = "uv";
  21204. VertexBuffer._UV2Kind = "uv2";
  21205. VertexBuffer._UV3Kind = "uv3";
  21206. VertexBuffer._UV4Kind = "uv4";
  21207. VertexBuffer._UV5Kind = "uv5";
  21208. VertexBuffer._UV6Kind = "uv6";
  21209. VertexBuffer._ColorKind = "color";
  21210. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21211. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21212. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21213. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21214. return VertexBuffer;
  21215. }());
  21216. BABYLON.VertexBuffer = VertexBuffer;
  21217. })(BABYLON || (BABYLON = {}));
  21218. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21219. var BABYLON;
  21220. (function (BABYLON) {
  21221. var InternalTexture = /** @class */ (function () {
  21222. function InternalTexture(engine, dataSource) {
  21223. this.onLoadedObservable = new BABYLON.Observable();
  21224. // Private
  21225. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21226. this._references = 1;
  21227. this._engine = engine;
  21228. this._dataSource = dataSource;
  21229. this._webGLTexture = engine._createTexture();
  21230. }
  21231. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21232. get: function () {
  21233. return this._dataSource;
  21234. },
  21235. enumerable: true,
  21236. configurable: true
  21237. });
  21238. InternalTexture.prototype.incrementReferences = function () {
  21239. this._references++;
  21240. };
  21241. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21242. if (depth === void 0) { depth = 1; }
  21243. this.width = width;
  21244. this.height = height;
  21245. this.depth = depth;
  21246. this.baseWidth = width;
  21247. this.baseHeight = height;
  21248. this.baseDepth = depth;
  21249. this._size = width * height * depth;
  21250. };
  21251. InternalTexture.prototype._rebuild = function () {
  21252. var _this = this;
  21253. var proxy;
  21254. this.isReady = false;
  21255. this._cachedCoordinatesMode = null;
  21256. this._cachedWrapU = null;
  21257. this._cachedWrapV = null;
  21258. this._cachedAnisotropicFilteringLevel = null;
  21259. switch (this._dataSource) {
  21260. case InternalTexture.DATASOURCE_TEMP:
  21261. return;
  21262. case InternalTexture.DATASOURCE_URL:
  21263. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21264. _this.isReady = true;
  21265. }, null, this._buffer, undefined, this.format);
  21266. proxy._swapAndDie(this);
  21267. return;
  21268. case InternalTexture.DATASOURCE_RAW:
  21269. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21270. proxy._swapAndDie(this);
  21271. this.isReady = true;
  21272. return;
  21273. case InternalTexture.DATASOURCE_RAW3D:
  21274. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21275. proxy._swapAndDie(this);
  21276. this.isReady = true;
  21277. return;
  21278. case InternalTexture.DATASOURCE_DYNAMIC:
  21279. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21280. proxy._swapAndDie(this);
  21281. // The engine will make sure to update content so no need to flag it as isReady = true
  21282. return;
  21283. case InternalTexture.DATASOURCE_RENDERTARGET:
  21284. var options = new BABYLON.RenderTargetCreationOptions();
  21285. options.generateDepthBuffer = this._generateDepthBuffer;
  21286. options.generateMipMaps = this.generateMipMaps;
  21287. options.generateStencilBuffer = this._generateStencilBuffer;
  21288. options.samplingMode = this.samplingMode;
  21289. options.type = this.type;
  21290. if (this.isCube) {
  21291. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21292. }
  21293. else {
  21294. var size = {
  21295. width: this.width,
  21296. height: this.height
  21297. };
  21298. proxy = this._engine.createRenderTargetTexture(size, options);
  21299. }
  21300. proxy._swapAndDie(this);
  21301. this.isReady = true;
  21302. return;
  21303. case InternalTexture.DATASOURCE_CUBE:
  21304. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21305. _this.isReady = true;
  21306. }, null, this.format, this._extension);
  21307. proxy._swapAndDie(this);
  21308. return;
  21309. case InternalTexture.DATASOURCE_CUBERAW:
  21310. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21311. proxy._swapAndDie(this);
  21312. this.isReady = true;
  21313. return;
  21314. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21315. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21316. if (proxy) {
  21317. proxy._swapAndDie(_this);
  21318. }
  21319. _this.isReady = true;
  21320. }, null, this.format, this._extension);
  21321. return;
  21322. }
  21323. };
  21324. InternalTexture.prototype._swapAndDie = function (target) {
  21325. target._webGLTexture = this._webGLTexture;
  21326. if (this._framebuffer) {
  21327. target._framebuffer = this._framebuffer;
  21328. }
  21329. if (this._depthStencilBuffer) {
  21330. target._depthStencilBuffer = this._depthStencilBuffer;
  21331. }
  21332. if (this._lodTextureHigh) {
  21333. if (target._lodTextureHigh) {
  21334. target._lodTextureHigh.dispose();
  21335. }
  21336. target._lodTextureHigh = this._lodTextureHigh;
  21337. }
  21338. if (this._lodTextureMid) {
  21339. if (target._lodTextureMid) {
  21340. target._lodTextureMid.dispose();
  21341. }
  21342. target._lodTextureMid = this._lodTextureMid;
  21343. }
  21344. if (this._lodTextureLow) {
  21345. if (target._lodTextureLow) {
  21346. target._lodTextureLow.dispose();
  21347. }
  21348. target._lodTextureLow = this._lodTextureLow;
  21349. }
  21350. var cache = this._engine.getLoadedTexturesCache();
  21351. var index = cache.indexOf(this);
  21352. if (index !== -1) {
  21353. cache.splice(index, 1);
  21354. }
  21355. };
  21356. InternalTexture.prototype.dispose = function () {
  21357. if (!this._webGLTexture) {
  21358. return;
  21359. }
  21360. this._references--;
  21361. if (this._references === 0) {
  21362. this._engine._releaseTexture(this);
  21363. this._webGLTexture = null;
  21364. }
  21365. };
  21366. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21367. InternalTexture.DATASOURCE_URL = 1;
  21368. InternalTexture.DATASOURCE_TEMP = 2;
  21369. InternalTexture.DATASOURCE_RAW = 3;
  21370. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21371. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21372. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21373. InternalTexture.DATASOURCE_CUBE = 7;
  21374. InternalTexture.DATASOURCE_CUBERAW = 8;
  21375. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21376. InternalTexture.DATASOURCE_RAW3D = 10;
  21377. return InternalTexture;
  21378. }());
  21379. BABYLON.InternalTexture = InternalTexture;
  21380. })(BABYLON || (BABYLON = {}));
  21381. //# sourceMappingURL=babylon.internalTexture.js.map
  21382. var BABYLON;
  21383. (function (BABYLON) {
  21384. var BaseTexture = /** @class */ (function () {
  21385. function BaseTexture(scene) {
  21386. this._hasAlpha = false;
  21387. this.getAlphaFromRGB = false;
  21388. this.level = 1;
  21389. this.coordinatesIndex = 0;
  21390. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21391. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21392. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21393. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21394. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21395. this.isCube = false;
  21396. this.is3D = false;
  21397. this.gammaSpace = true;
  21398. this.invertZ = false;
  21399. this.lodLevelInAlpha = false;
  21400. this.lodGenerationOffset = 0.0;
  21401. this.lodGenerationScale = 0.8;
  21402. this.isRenderTarget = false;
  21403. this.animations = new Array();
  21404. /**
  21405. * An event triggered when the texture is disposed.
  21406. * @type {BABYLON.Observable}
  21407. */
  21408. this.onDisposeObservable = new BABYLON.Observable();
  21409. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21410. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21411. if (this._scene) {
  21412. this._scene.textures.push(this);
  21413. }
  21414. this._uid = null;
  21415. }
  21416. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21417. get: function () {
  21418. return this._hasAlpha;
  21419. },
  21420. set: function (value) {
  21421. if (this._hasAlpha === value) {
  21422. return;
  21423. }
  21424. this._hasAlpha = value;
  21425. if (this._scene) {
  21426. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21427. }
  21428. },
  21429. enumerable: true,
  21430. configurable: true
  21431. });
  21432. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21433. get: function () {
  21434. return this._coordinatesMode;
  21435. },
  21436. set: function (value) {
  21437. if (this._coordinatesMode === value) {
  21438. return;
  21439. }
  21440. this._coordinatesMode = value;
  21441. if (this._scene) {
  21442. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21443. }
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. Object.defineProperty(BaseTexture.prototype, "uid", {
  21449. get: function () {
  21450. if (!this._uid) {
  21451. this._uid = BABYLON.Tools.RandomId();
  21452. }
  21453. return this._uid;
  21454. },
  21455. enumerable: true,
  21456. configurable: true
  21457. });
  21458. BaseTexture.prototype.toString = function () {
  21459. return this.name;
  21460. };
  21461. BaseTexture.prototype.getClassName = function () {
  21462. return "BaseTexture";
  21463. };
  21464. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21465. set: function (callback) {
  21466. if (this._onDisposeObserver) {
  21467. this.onDisposeObservable.remove(this._onDisposeObserver);
  21468. }
  21469. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21475. get: function () {
  21476. return true;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. BaseTexture.prototype.getScene = function () {
  21482. return this._scene;
  21483. };
  21484. BaseTexture.prototype.getTextureMatrix = function () {
  21485. return BABYLON.Matrix.IdentityReadOnly;
  21486. };
  21487. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21488. return BABYLON.Matrix.IdentityReadOnly;
  21489. };
  21490. BaseTexture.prototype.getInternalTexture = function () {
  21491. return this._texture;
  21492. };
  21493. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21494. return !this.isBlocking || this.isReady();
  21495. };
  21496. BaseTexture.prototype.isReady = function () {
  21497. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21498. this.delayLoad();
  21499. return false;
  21500. }
  21501. if (this._texture) {
  21502. return this._texture.isReady;
  21503. }
  21504. return false;
  21505. };
  21506. BaseTexture.prototype.getSize = function () {
  21507. if (this._texture && this._texture.width) {
  21508. return new BABYLON.Size(this._texture.width, this._texture.height);
  21509. }
  21510. if (this._texture && this._texture._size) {
  21511. return new BABYLON.Size(this._texture._size, this._texture._size);
  21512. }
  21513. return BABYLON.Size.Zero();
  21514. };
  21515. BaseTexture.prototype.getBaseSize = function () {
  21516. if (!this.isReady() || !this._texture)
  21517. return BABYLON.Size.Zero();
  21518. if (this._texture._size) {
  21519. return new BABYLON.Size(this._texture._size, this._texture._size);
  21520. }
  21521. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21522. };
  21523. BaseTexture.prototype.scale = function (ratio) {
  21524. };
  21525. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21526. get: function () {
  21527. return false;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21533. if (!this._scene) {
  21534. return null;
  21535. }
  21536. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21537. for (var index = 0; index < texturesCache.length; index++) {
  21538. var texturesCacheEntry = texturesCache[index];
  21539. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21540. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21541. texturesCacheEntry.incrementReferences();
  21542. return texturesCacheEntry;
  21543. }
  21544. }
  21545. }
  21546. return null;
  21547. };
  21548. BaseTexture.prototype._rebuild = function () {
  21549. };
  21550. BaseTexture.prototype.delayLoad = function () {
  21551. };
  21552. BaseTexture.prototype.clone = function () {
  21553. return null;
  21554. };
  21555. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21556. get: function () {
  21557. if (!this._texture) {
  21558. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21559. }
  21560. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21566. get: function () {
  21567. if (!this._texture) {
  21568. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21569. }
  21570. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. BaseTexture.prototype.readPixels = function (faceIndex) {
  21576. if (faceIndex === void 0) { faceIndex = 0; }
  21577. if (!this._texture) {
  21578. return null;
  21579. }
  21580. var size = this.getSize();
  21581. var scene = this.getScene();
  21582. if (!scene) {
  21583. return null;
  21584. }
  21585. var engine = scene.getEngine();
  21586. if (this._texture.isCube) {
  21587. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21588. }
  21589. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21590. };
  21591. BaseTexture.prototype.releaseInternalTexture = function () {
  21592. if (this._texture) {
  21593. this._texture.dispose();
  21594. this._texture = null;
  21595. }
  21596. };
  21597. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21598. get: function () {
  21599. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21600. return null;
  21601. }
  21602. if (!this._texture._sphericalPolynomial) {
  21603. this._texture._sphericalPolynomial =
  21604. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21605. }
  21606. return this._texture._sphericalPolynomial;
  21607. },
  21608. set: function (value) {
  21609. if (this._texture) {
  21610. this._texture._sphericalPolynomial = value;
  21611. }
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21617. get: function () {
  21618. if (this._texture) {
  21619. return this._texture._lodTextureHigh;
  21620. }
  21621. return null;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21627. get: function () {
  21628. if (this._texture) {
  21629. return this._texture._lodTextureMid;
  21630. }
  21631. return null;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21637. get: function () {
  21638. if (this._texture) {
  21639. return this._texture._lodTextureLow;
  21640. }
  21641. return null;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. BaseTexture.prototype.dispose = function () {
  21647. if (!this._scene) {
  21648. return;
  21649. }
  21650. // Animations
  21651. this._scene.stopAnimation(this);
  21652. // Remove from scene
  21653. this._scene._removePendingData(this);
  21654. var index = this._scene.textures.indexOf(this);
  21655. if (index >= 0) {
  21656. this._scene.textures.splice(index, 1);
  21657. }
  21658. if (this._texture === undefined) {
  21659. return;
  21660. }
  21661. // Release
  21662. this.releaseInternalTexture();
  21663. // Callback
  21664. this.onDisposeObservable.notifyObservers(this);
  21665. this.onDisposeObservable.clear();
  21666. };
  21667. BaseTexture.prototype.serialize = function () {
  21668. if (!this.name) {
  21669. return null;
  21670. }
  21671. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21672. // Animations
  21673. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21674. return serializationObject;
  21675. };
  21676. BaseTexture.WhenAllReady = function (textures, callback) {
  21677. var numRemaining = textures.length;
  21678. if (numRemaining === 0) {
  21679. callback();
  21680. return;
  21681. }
  21682. var _loop_1 = function () {
  21683. texture = textures[i];
  21684. if (texture.isReady()) {
  21685. if (--numRemaining === 0) {
  21686. callback();
  21687. }
  21688. }
  21689. else {
  21690. onLoadObservable = texture.onLoadObservable;
  21691. var onLoadCallback_1 = function () {
  21692. onLoadObservable.removeCallback(onLoadCallback_1);
  21693. if (--numRemaining === 0) {
  21694. callback();
  21695. }
  21696. };
  21697. onLoadObservable.add(onLoadCallback_1);
  21698. }
  21699. };
  21700. var texture, onLoadObservable;
  21701. for (var i = 0; i < textures.length; i++) {
  21702. _loop_1();
  21703. }
  21704. };
  21705. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21706. __decorate([
  21707. BABYLON.serialize()
  21708. ], BaseTexture.prototype, "name", void 0);
  21709. __decorate([
  21710. BABYLON.serialize("hasAlpha")
  21711. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21712. __decorate([
  21713. BABYLON.serialize()
  21714. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21715. __decorate([
  21716. BABYLON.serialize()
  21717. ], BaseTexture.prototype, "level", void 0);
  21718. __decorate([
  21719. BABYLON.serialize()
  21720. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21721. __decorate([
  21722. BABYLON.serialize("coordinatesMode")
  21723. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21724. __decorate([
  21725. BABYLON.serialize()
  21726. ], BaseTexture.prototype, "wrapU", void 0);
  21727. __decorate([
  21728. BABYLON.serialize()
  21729. ], BaseTexture.prototype, "wrapV", void 0);
  21730. __decorate([
  21731. BABYLON.serialize()
  21732. ], BaseTexture.prototype, "wrapR", void 0);
  21733. __decorate([
  21734. BABYLON.serialize()
  21735. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21736. __decorate([
  21737. BABYLON.serialize()
  21738. ], BaseTexture.prototype, "isCube", void 0);
  21739. __decorate([
  21740. BABYLON.serialize()
  21741. ], BaseTexture.prototype, "is3D", void 0);
  21742. __decorate([
  21743. BABYLON.serialize()
  21744. ], BaseTexture.prototype, "gammaSpace", void 0);
  21745. __decorate([
  21746. BABYLON.serialize()
  21747. ], BaseTexture.prototype, "invertZ", void 0);
  21748. __decorate([
  21749. BABYLON.serialize()
  21750. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21751. __decorate([
  21752. BABYLON.serialize()
  21753. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21754. __decorate([
  21755. BABYLON.serialize()
  21756. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21757. __decorate([
  21758. BABYLON.serialize()
  21759. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21760. return BaseTexture;
  21761. }());
  21762. BABYLON.BaseTexture = BaseTexture;
  21763. })(BABYLON || (BABYLON = {}));
  21764. //# sourceMappingURL=babylon.baseTexture.js.map
  21765. var BABYLON;
  21766. (function (BABYLON) {
  21767. var Texture = /** @class */ (function (_super) {
  21768. __extends(Texture, _super);
  21769. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21770. if (noMipmap === void 0) { noMipmap = false; }
  21771. if (invertY === void 0) { invertY = true; }
  21772. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21773. if (onLoad === void 0) { onLoad = null; }
  21774. if (onError === void 0) { onError = null; }
  21775. if (buffer === void 0) { buffer = null; }
  21776. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21777. var _this = _super.call(this, scene) || this;
  21778. _this.uOffset = 0;
  21779. _this.vOffset = 0;
  21780. _this.uScale = 1.0;
  21781. _this.vScale = 1.0;
  21782. _this.uAng = 0;
  21783. _this.vAng = 0;
  21784. _this.wAng = 0;
  21785. _this._isBlocking = true;
  21786. _this.name = url || "";
  21787. _this.url = url;
  21788. _this._noMipmap = noMipmap;
  21789. _this._invertY = invertY;
  21790. _this._samplingMode = samplingMode;
  21791. _this._buffer = buffer;
  21792. _this._deleteBuffer = deleteBuffer;
  21793. if (format) {
  21794. _this._format = format;
  21795. }
  21796. scene = _this.getScene();
  21797. if (!scene) {
  21798. return _this;
  21799. }
  21800. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21801. var load = function () {
  21802. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21803. _this.onLoadObservable.notifyObservers(_this);
  21804. }
  21805. if (onLoad) {
  21806. onLoad();
  21807. }
  21808. if (!_this.isBlocking && scene) {
  21809. scene.resetCachedMaterial();
  21810. }
  21811. };
  21812. if (!_this.url) {
  21813. _this._delayedOnLoad = load;
  21814. _this._delayedOnError = onError;
  21815. return _this;
  21816. }
  21817. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21818. if (!_this._texture) {
  21819. if (!scene.useDelayedTextureLoading) {
  21820. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21821. if (deleteBuffer) {
  21822. delete _this._buffer;
  21823. }
  21824. }
  21825. else {
  21826. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21827. _this._delayedOnLoad = load;
  21828. _this._delayedOnError = onError;
  21829. }
  21830. }
  21831. else {
  21832. if (_this._texture.isReady) {
  21833. BABYLON.Tools.SetImmediate(function () { return load(); });
  21834. }
  21835. else {
  21836. _this._texture.onLoadedObservable.add(load);
  21837. }
  21838. }
  21839. return _this;
  21840. }
  21841. Object.defineProperty(Texture.prototype, "noMipmap", {
  21842. get: function () {
  21843. return this._noMipmap;
  21844. },
  21845. enumerable: true,
  21846. configurable: true
  21847. });
  21848. Object.defineProperty(Texture.prototype, "isBlocking", {
  21849. get: function () {
  21850. return this._isBlocking;
  21851. },
  21852. set: function (value) {
  21853. this._isBlocking = value;
  21854. },
  21855. enumerable: true,
  21856. configurable: true
  21857. });
  21858. Object.defineProperty(Texture.prototype, "samplingMode", {
  21859. get: function () {
  21860. return this._samplingMode;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Texture.prototype.updateURL = function (url) {
  21866. this.url = url;
  21867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21868. this.delayLoad();
  21869. };
  21870. Texture.prototype.delayLoad = function () {
  21871. var _this = this;
  21872. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21873. return;
  21874. }
  21875. var scene = this.getScene();
  21876. if (!scene) {
  21877. return;
  21878. }
  21879. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21880. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21881. if (!this._texture) {
  21882. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21883. if (this._deleteBuffer) {
  21884. delete this._buffer;
  21885. }
  21886. }
  21887. else {
  21888. if (this._texture.isReady) {
  21889. BABYLON.Tools.SetImmediate(function () {
  21890. if (!_this._delayedOnLoad) {
  21891. return;
  21892. }
  21893. _this._delayedOnLoad();
  21894. });
  21895. }
  21896. else {
  21897. if (this._delayedOnLoad) {
  21898. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21899. }
  21900. }
  21901. }
  21902. };
  21903. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21904. if (!this._texture) {
  21905. return;
  21906. }
  21907. var scene = this.getScene();
  21908. if (!scene) {
  21909. return;
  21910. }
  21911. this._samplingMode = samplingMode;
  21912. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21913. };
  21914. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21915. x *= this.uScale;
  21916. y *= this.vScale;
  21917. x -= 0.5 * this.uScale;
  21918. y -= 0.5 * this.vScale;
  21919. z -= 0.5;
  21920. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21921. t.x += 0.5 * this.uScale + this.uOffset;
  21922. t.y += 0.5 * this.vScale + this.vOffset;
  21923. t.z += 0.5;
  21924. };
  21925. Texture.prototype.getTextureMatrix = function () {
  21926. var _this = this;
  21927. if (this.uOffset === this._cachedUOffset &&
  21928. this.vOffset === this._cachedVOffset &&
  21929. this.uScale === this._cachedUScale &&
  21930. this.vScale === this._cachedVScale &&
  21931. this.uAng === this._cachedUAng &&
  21932. this.vAng === this._cachedVAng &&
  21933. this.wAng === this._cachedWAng) {
  21934. return this._cachedTextureMatrix;
  21935. }
  21936. this._cachedUOffset = this.uOffset;
  21937. this._cachedVOffset = this.vOffset;
  21938. this._cachedUScale = this.uScale;
  21939. this._cachedVScale = this.vScale;
  21940. this._cachedUAng = this.uAng;
  21941. this._cachedVAng = this.vAng;
  21942. this._cachedWAng = this.wAng;
  21943. if (!this._cachedTextureMatrix) {
  21944. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21945. this._rowGenerationMatrix = new BABYLON.Matrix();
  21946. this._t0 = BABYLON.Vector3.Zero();
  21947. this._t1 = BABYLON.Vector3.Zero();
  21948. this._t2 = BABYLON.Vector3.Zero();
  21949. }
  21950. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21951. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21952. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21953. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21954. this._t1.subtractInPlace(this._t0);
  21955. this._t2.subtractInPlace(this._t0);
  21956. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21957. this._cachedTextureMatrix.m[0] = this._t1.x;
  21958. this._cachedTextureMatrix.m[1] = this._t1.y;
  21959. this._cachedTextureMatrix.m[2] = this._t1.z;
  21960. this._cachedTextureMatrix.m[4] = this._t2.x;
  21961. this._cachedTextureMatrix.m[5] = this._t2.y;
  21962. this._cachedTextureMatrix.m[6] = this._t2.z;
  21963. this._cachedTextureMatrix.m[8] = this._t0.x;
  21964. this._cachedTextureMatrix.m[9] = this._t0.y;
  21965. this._cachedTextureMatrix.m[10] = this._t0.z;
  21966. var scene = this.getScene();
  21967. if (!scene) {
  21968. return this._cachedTextureMatrix;
  21969. }
  21970. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21971. return mat.hasTexture(_this);
  21972. });
  21973. return this._cachedTextureMatrix;
  21974. };
  21975. Texture.prototype.getReflectionTextureMatrix = function () {
  21976. var _this = this;
  21977. var scene = this.getScene();
  21978. if (!scene) {
  21979. return this._cachedTextureMatrix;
  21980. }
  21981. if (this.uOffset === this._cachedUOffset &&
  21982. this.vOffset === this._cachedVOffset &&
  21983. this.uScale === this._cachedUScale &&
  21984. this.vScale === this._cachedVScale &&
  21985. this.coordinatesMode === this._cachedCoordinatesMode) {
  21986. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21987. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21988. return this._cachedTextureMatrix;
  21989. }
  21990. }
  21991. else {
  21992. return this._cachedTextureMatrix;
  21993. }
  21994. }
  21995. if (!this._cachedTextureMatrix) {
  21996. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21997. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21998. }
  21999. this._cachedUOffset = this.uOffset;
  22000. this._cachedVOffset = this.vOffset;
  22001. this._cachedUScale = this.uScale;
  22002. this._cachedVScale = this.vScale;
  22003. this._cachedCoordinatesMode = this.coordinatesMode;
  22004. switch (this.coordinatesMode) {
  22005. case Texture.PLANAR_MODE:
  22006. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22007. this._cachedTextureMatrix[0] = this.uScale;
  22008. this._cachedTextureMatrix[5] = this.vScale;
  22009. this._cachedTextureMatrix[12] = this.uOffset;
  22010. this._cachedTextureMatrix[13] = this.vOffset;
  22011. break;
  22012. case Texture.PROJECTION_MODE:
  22013. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22014. this._projectionModeMatrix.m[0] = 0.5;
  22015. this._projectionModeMatrix.m[5] = -0.5;
  22016. this._projectionModeMatrix.m[10] = 0.0;
  22017. this._projectionModeMatrix.m[12] = 0.5;
  22018. this._projectionModeMatrix.m[13] = 0.5;
  22019. this._projectionModeMatrix.m[14] = 1.0;
  22020. this._projectionModeMatrix.m[15] = 1.0;
  22021. var projectionMatrix = scene.getProjectionMatrix();
  22022. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22023. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22024. break;
  22025. default:
  22026. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22027. break;
  22028. }
  22029. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22030. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22031. });
  22032. return this._cachedTextureMatrix;
  22033. };
  22034. Texture.prototype.clone = function () {
  22035. var _this = this;
  22036. return BABYLON.SerializationHelper.Clone(function () {
  22037. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22038. }, this);
  22039. };
  22040. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22041. get: function () {
  22042. if (!this._onLoadObservable) {
  22043. this._onLoadObservable = new BABYLON.Observable();
  22044. }
  22045. return this._onLoadObservable;
  22046. },
  22047. enumerable: true,
  22048. configurable: true
  22049. });
  22050. Texture.prototype.serialize = function () {
  22051. var serializationObject = _super.prototype.serialize.call(this);
  22052. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22053. serializationObject.base64String = this._buffer;
  22054. serializationObject.name = serializationObject.name.replace("data:", "");
  22055. }
  22056. return serializationObject;
  22057. };
  22058. Texture.prototype.getClassName = function () {
  22059. return "Texture";
  22060. };
  22061. Texture.prototype.dispose = function () {
  22062. _super.prototype.dispose.call(this);
  22063. if (this.onLoadObservable) {
  22064. this.onLoadObservable.clear();
  22065. this._onLoadObservable = null;
  22066. }
  22067. this._delayedOnLoad = null;
  22068. this._delayedOnError = null;
  22069. };
  22070. // Statics
  22071. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22072. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22073. if (onLoad === void 0) { onLoad = null; }
  22074. if (onError === void 0) { onError = null; }
  22075. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22076. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22077. };
  22078. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22079. if (parsedTexture.customType) {
  22080. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22081. // Update Sampling Mode
  22082. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22083. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22084. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22085. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22086. }
  22087. }
  22088. return parsedCustomTexture;
  22089. }
  22090. if (parsedTexture.isCube) {
  22091. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22092. }
  22093. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22094. return null;
  22095. }
  22096. var texture = BABYLON.SerializationHelper.Parse(function () {
  22097. if (parsedTexture.mirrorPlane) {
  22098. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22099. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22100. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22101. return mirrorTexture;
  22102. }
  22103. else if (parsedTexture.isRenderTarget) {
  22104. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22105. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22106. return renderTargetTexture;
  22107. }
  22108. else {
  22109. var texture;
  22110. if (parsedTexture.base64String) {
  22111. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22112. }
  22113. else {
  22114. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22115. }
  22116. return texture;
  22117. }
  22118. }, parsedTexture, scene);
  22119. // Update Sampling Mode
  22120. if (parsedTexture.samplingMode) {
  22121. var sampling = parsedTexture.samplingMode;
  22122. if (texture._samplingMode !== sampling) {
  22123. texture.updateSamplingMode(sampling);
  22124. }
  22125. }
  22126. // Animations
  22127. if (parsedTexture.animations) {
  22128. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22129. var parsedAnimation = parsedTexture.animations[animationIndex];
  22130. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22131. }
  22132. }
  22133. return texture;
  22134. };
  22135. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22136. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22137. if (noMipmap === void 0) { noMipmap = false; }
  22138. if (invertY === void 0) { invertY = true; }
  22139. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22140. if (onLoad === void 0) { onLoad = null; }
  22141. if (onError === void 0) { onError = null; }
  22142. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22143. if (name.substr(0, 5) !== "data:") {
  22144. name = "data:" + name;
  22145. }
  22146. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22147. };
  22148. // Constants
  22149. Texture.NEAREST_SAMPLINGMODE = 1;
  22150. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22151. Texture.BILINEAR_SAMPLINGMODE = 2;
  22152. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22153. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22154. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22155. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22156. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22157. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22158. Texture.NEAREST_LINEAR = 7;
  22159. Texture.NEAREST_NEAREST = 8;
  22160. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22161. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22162. Texture.LINEAR_LINEAR = 11;
  22163. Texture.LINEAR_NEAREST = 12;
  22164. Texture.EXPLICIT_MODE = 0;
  22165. Texture.SPHERICAL_MODE = 1;
  22166. Texture.PLANAR_MODE = 2;
  22167. Texture.CUBIC_MODE = 3;
  22168. Texture.PROJECTION_MODE = 4;
  22169. Texture.SKYBOX_MODE = 5;
  22170. Texture.INVCUBIC_MODE = 6;
  22171. Texture.EQUIRECTANGULAR_MODE = 7;
  22172. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22173. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22174. Texture.CLAMP_ADDRESSMODE = 0;
  22175. Texture.WRAP_ADDRESSMODE = 1;
  22176. Texture.MIRROR_ADDRESSMODE = 2;
  22177. __decorate([
  22178. BABYLON.serialize()
  22179. ], Texture.prototype, "url", void 0);
  22180. __decorate([
  22181. BABYLON.serialize()
  22182. ], Texture.prototype, "uOffset", void 0);
  22183. __decorate([
  22184. BABYLON.serialize()
  22185. ], Texture.prototype, "vOffset", void 0);
  22186. __decorate([
  22187. BABYLON.serialize()
  22188. ], Texture.prototype, "uScale", void 0);
  22189. __decorate([
  22190. BABYLON.serialize()
  22191. ], Texture.prototype, "vScale", void 0);
  22192. __decorate([
  22193. BABYLON.serialize()
  22194. ], Texture.prototype, "uAng", void 0);
  22195. __decorate([
  22196. BABYLON.serialize()
  22197. ], Texture.prototype, "vAng", void 0);
  22198. __decorate([
  22199. BABYLON.serialize()
  22200. ], Texture.prototype, "wAng", void 0);
  22201. __decorate([
  22202. BABYLON.serialize()
  22203. ], Texture.prototype, "isBlocking", null);
  22204. return Texture;
  22205. }(BABYLON.BaseTexture));
  22206. BABYLON.Texture = Texture;
  22207. })(BABYLON || (BABYLON = {}));
  22208. //# sourceMappingURL=babylon.texture.js.map
  22209. var BABYLON;
  22210. (function (BABYLON) {
  22211. var _InstancesBatch = /** @class */ (function () {
  22212. function _InstancesBatch() {
  22213. this.mustReturn = false;
  22214. this.visibleInstances = new Array();
  22215. this.renderSelf = new Array();
  22216. }
  22217. return _InstancesBatch;
  22218. }());
  22219. BABYLON._InstancesBatch = _InstancesBatch;
  22220. var Mesh = /** @class */ (function (_super) {
  22221. __extends(Mesh, _super);
  22222. /**
  22223. * @constructor
  22224. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22225. * @param {Scene} scene The scene to add this mesh to.
  22226. * @param {Node} parent The parent of this mesh, if it has one
  22227. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22228. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22229. * When false, achieved by calling a clone(), also passing False.
  22230. * This will make creation of children, recursive.
  22231. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22232. */
  22233. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22234. if (scene === void 0) { scene = null; }
  22235. if (parent === void 0) { parent = null; }
  22236. if (source === void 0) { source = null; }
  22237. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22238. var _this = _super.call(this, name, scene) || this;
  22239. // Events
  22240. /**
  22241. * An event triggered before rendering the mesh
  22242. * @type {BABYLON.Observable}
  22243. */
  22244. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22245. /**
  22246. * An event triggered after rendering the mesh
  22247. * @type {BABYLON.Observable}
  22248. */
  22249. _this.onAfterRenderObservable = new BABYLON.Observable();
  22250. /**
  22251. * An event triggered before drawing the mesh
  22252. * @type {BABYLON.Observable}
  22253. */
  22254. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22255. // Members
  22256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22257. _this.instances = new Array();
  22258. _this._LODLevels = new Array();
  22259. _this._visibleInstances = {};
  22260. _this._renderIdForInstances = new Array();
  22261. _this._batchCache = new _InstancesBatch();
  22262. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22263. // Use by builder only to know what orientation were the mesh build in.
  22264. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22265. _this.overrideMaterialSideOrientation = null;
  22266. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22267. // Will be used to save a source mesh reference, If any
  22268. _this._source = null;
  22269. scene = _this.getScene();
  22270. if (source) {
  22271. // Source mesh
  22272. _this._source = source;
  22273. // Geometry
  22274. if (source._geometry) {
  22275. source._geometry.applyToMesh(_this);
  22276. }
  22277. // Deep copy
  22278. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22279. // Tags
  22280. if (BABYLON.Tags.HasTags(source)) {
  22281. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22282. }
  22283. _this.metadata = source.metadata;
  22284. // Parent
  22285. _this.parent = source.parent;
  22286. // Pivot
  22287. _this.setPivotMatrix(source.getPivotMatrix());
  22288. _this.id = name + "." + source.id;
  22289. // Material
  22290. _this.material = source.material;
  22291. var index;
  22292. if (!doNotCloneChildren) {
  22293. // Children
  22294. for (index = 0; index < scene.meshes.length; index++) {
  22295. var mesh = scene.meshes[index];
  22296. if (mesh.parent === source) {
  22297. // doNotCloneChildren is always going to be False
  22298. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22299. }
  22300. }
  22301. }
  22302. // Physics clone
  22303. var physicsEngine = _this.getScene().getPhysicsEngine();
  22304. if (clonePhysicsImpostor && physicsEngine) {
  22305. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22306. if (impostor) {
  22307. _this.physicsImpostor = impostor.clone(_this);
  22308. }
  22309. }
  22310. // Particles
  22311. for (index = 0; index < scene.particleSystems.length; index++) {
  22312. var system = scene.particleSystems[index];
  22313. if (system.emitter === source) {
  22314. system.clone(system.name, _this);
  22315. }
  22316. }
  22317. _this.computeWorldMatrix(true);
  22318. }
  22319. // Parent
  22320. if (parent !== null) {
  22321. _this.parent = parent;
  22322. }
  22323. return _this;
  22324. }
  22325. Object.defineProperty(Mesh, "FRONTSIDE", {
  22326. /**
  22327. * Mesh side orientation : usually the external or front surface
  22328. */
  22329. get: function () {
  22330. return Mesh._FRONTSIDE;
  22331. },
  22332. enumerable: true,
  22333. configurable: true
  22334. });
  22335. Object.defineProperty(Mesh, "BACKSIDE", {
  22336. /**
  22337. * Mesh side orientation : usually the internal or back surface
  22338. */
  22339. get: function () {
  22340. return Mesh._BACKSIDE;
  22341. },
  22342. enumerable: true,
  22343. configurable: true
  22344. });
  22345. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22346. /**
  22347. * Mesh side orientation : both internal and external or front and back surfaces
  22348. */
  22349. get: function () {
  22350. return Mesh._DOUBLESIDE;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22356. /**
  22357. * Mesh side orientation : by default, `FRONTSIDE`
  22358. */
  22359. get: function () {
  22360. return Mesh._DEFAULTSIDE;
  22361. },
  22362. enumerable: true,
  22363. configurable: true
  22364. });
  22365. Object.defineProperty(Mesh, "NO_CAP", {
  22366. /**
  22367. * Mesh cap setting : no cap
  22368. */
  22369. get: function () {
  22370. return Mesh._NO_CAP;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Mesh, "CAP_START", {
  22376. /**
  22377. * Mesh cap setting : one cap at the beginning of the mesh
  22378. */
  22379. get: function () {
  22380. return Mesh._CAP_START;
  22381. },
  22382. enumerable: true,
  22383. configurable: true
  22384. });
  22385. Object.defineProperty(Mesh, "CAP_END", {
  22386. /**
  22387. * Mesh cap setting : one cap at the end of the mesh
  22388. */
  22389. get: function () {
  22390. return Mesh._CAP_END;
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. Object.defineProperty(Mesh, "CAP_ALL", {
  22396. /**
  22397. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22398. */
  22399. get: function () {
  22400. return Mesh._CAP_ALL;
  22401. },
  22402. enumerable: true,
  22403. configurable: true
  22404. });
  22405. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22406. set: function (callback) {
  22407. if (this._onBeforeDrawObserver) {
  22408. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22409. }
  22410. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22416. get: function () {
  22417. return this._morphTargetManager;
  22418. },
  22419. set: function (value) {
  22420. if (this._morphTargetManager === value) {
  22421. return;
  22422. }
  22423. this._morphTargetManager = value;
  22424. this._syncGeometryWithMorphTargetManager();
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Object.defineProperty(Mesh.prototype, "source", {
  22430. get: function () {
  22431. return this._source;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. // Methods
  22437. /**
  22438. * Returns the string "Mesh".
  22439. */
  22440. Mesh.prototype.getClassName = function () {
  22441. return "Mesh";
  22442. };
  22443. /**
  22444. * Returns a string.
  22445. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22446. */
  22447. Mesh.prototype.toString = function (fullDetails) {
  22448. var ret = _super.prototype.toString.call(this, fullDetails);
  22449. ret += ", n vertices: " + this.getTotalVertices();
  22450. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22451. if (this.animations) {
  22452. for (var i = 0; i < this.animations.length; i++) {
  22453. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22454. }
  22455. }
  22456. if (fullDetails) {
  22457. if (this._geometry) {
  22458. var ib = this.getIndices();
  22459. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22460. if (vb && ib) {
  22461. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22462. }
  22463. }
  22464. else {
  22465. ret += ", flat shading: UNKNOWN";
  22466. }
  22467. }
  22468. return ret;
  22469. };
  22470. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22471. /**
  22472. * True if the mesh has some Levels Of Details (LOD).
  22473. * Returns a boolean.
  22474. */
  22475. get: function () {
  22476. return this._LODLevels.length > 0;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Mesh.prototype._sortLODLevels = function () {
  22482. this._LODLevels.sort(function (a, b) {
  22483. if (a.distance < b.distance) {
  22484. return 1;
  22485. }
  22486. if (a.distance > b.distance) {
  22487. return -1;
  22488. }
  22489. return 0;
  22490. });
  22491. };
  22492. /**
  22493. * Add a mesh as LOD level triggered at the given distance.
  22494. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22495. * @param {number} distance The distance from the center of the object to show this level
  22496. * @param {Mesh} mesh The mesh to be added as LOD level
  22497. * @return {Mesh} This mesh (for chaining)
  22498. */
  22499. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22500. if (mesh && mesh._masterMesh) {
  22501. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22502. return this;
  22503. }
  22504. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22505. this._LODLevels.push(level);
  22506. if (mesh) {
  22507. mesh._masterMesh = this;
  22508. }
  22509. this._sortLODLevels();
  22510. return this;
  22511. };
  22512. /**
  22513. * Returns the LOD level mesh at the passed distance or null if not found.
  22514. * It is related to the method `addLODLevel(distance, mesh)`.
  22515. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22516. * Returns an object Mesh or `null`.
  22517. */
  22518. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22519. for (var index = 0; index < this._LODLevels.length; index++) {
  22520. var level = this._LODLevels[index];
  22521. if (level.distance === distance) {
  22522. return level.mesh;
  22523. }
  22524. }
  22525. return null;
  22526. };
  22527. /**
  22528. * Remove a mesh from the LOD array
  22529. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22530. * @param {Mesh} mesh The mesh to be removed.
  22531. * @return {Mesh} This mesh (for chaining)
  22532. */
  22533. Mesh.prototype.removeLODLevel = function (mesh) {
  22534. for (var index = 0; index < this._LODLevels.length; index++) {
  22535. if (this._LODLevels[index].mesh === mesh) {
  22536. this._LODLevels.splice(index, 1);
  22537. if (mesh) {
  22538. mesh._masterMesh = null;
  22539. }
  22540. }
  22541. }
  22542. this._sortLODLevels();
  22543. return this;
  22544. };
  22545. /**
  22546. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22547. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22548. */
  22549. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22550. if (!this._LODLevels || this._LODLevels.length === 0) {
  22551. return this;
  22552. }
  22553. var bSphere;
  22554. if (boundingSphere) {
  22555. bSphere = boundingSphere;
  22556. }
  22557. else {
  22558. var boundingInfo = this.getBoundingInfo();
  22559. if (!boundingInfo) {
  22560. return this;
  22561. }
  22562. bSphere = boundingInfo.boundingSphere;
  22563. }
  22564. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22565. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22566. if (this.onLODLevelSelection) {
  22567. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22568. }
  22569. return this;
  22570. }
  22571. for (var index = 0; index < this._LODLevels.length; index++) {
  22572. var level = this._LODLevels[index];
  22573. if (level.distance < distanceToCamera) {
  22574. if (level.mesh) {
  22575. level.mesh._preActivate();
  22576. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22577. }
  22578. if (this.onLODLevelSelection) {
  22579. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22580. }
  22581. return level.mesh;
  22582. }
  22583. }
  22584. if (this.onLODLevelSelection) {
  22585. this.onLODLevelSelection(distanceToCamera, this, this);
  22586. }
  22587. return this;
  22588. };
  22589. Object.defineProperty(Mesh.prototype, "geometry", {
  22590. /**
  22591. * Returns the mesh internal Geometry object.
  22592. */
  22593. get: function () {
  22594. return this._geometry;
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. /**
  22600. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22601. */
  22602. Mesh.prototype.getTotalVertices = function () {
  22603. if (!this._geometry) {
  22604. return 0;
  22605. }
  22606. return this._geometry.getTotalVertices();
  22607. };
  22608. /**
  22609. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22610. * 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.
  22611. * You can force the copy with forceCopy === true
  22612. * Returns null if the mesh has no geometry or no vertex buffer.
  22613. * Possible `kind` values :
  22614. * - BABYLON.VertexBuffer.PositionKind
  22615. * - BABYLON.VertexBuffer.UVKind
  22616. * - BABYLON.VertexBuffer.UV2Kind
  22617. * - BABYLON.VertexBuffer.UV3Kind
  22618. * - BABYLON.VertexBuffer.UV4Kind
  22619. * - BABYLON.VertexBuffer.UV5Kind
  22620. * - BABYLON.VertexBuffer.UV6Kind
  22621. * - BABYLON.VertexBuffer.ColorKind
  22622. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22623. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22624. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22625. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22626. */
  22627. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22628. if (!this._geometry) {
  22629. return null;
  22630. }
  22631. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22632. };
  22633. /**
  22634. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22635. * Returns `null` if the mesh has no geometry.
  22636. * Possible `kind` values :
  22637. * - BABYLON.VertexBuffer.PositionKind
  22638. * - BABYLON.VertexBuffer.UVKind
  22639. * - BABYLON.VertexBuffer.UV2Kind
  22640. * - BABYLON.VertexBuffer.UV3Kind
  22641. * - BABYLON.VertexBuffer.UV4Kind
  22642. * - BABYLON.VertexBuffer.UV5Kind
  22643. * - BABYLON.VertexBuffer.UV6Kind
  22644. * - BABYLON.VertexBuffer.ColorKind
  22645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22649. */
  22650. Mesh.prototype.getVertexBuffer = function (kind) {
  22651. if (!this._geometry) {
  22652. return null;
  22653. }
  22654. return this._geometry.getVertexBuffer(kind);
  22655. };
  22656. /**
  22657. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22658. * Possible `kind` values :
  22659. * - BABYLON.VertexBuffer.PositionKind
  22660. * - BABYLON.VertexBuffer.UVKind
  22661. * - BABYLON.VertexBuffer.UV2Kind
  22662. * - BABYLON.VertexBuffer.UV3Kind
  22663. * - BABYLON.VertexBuffer.UV4Kind
  22664. * - BABYLON.VertexBuffer.UV5Kind
  22665. * - BABYLON.VertexBuffer.UV6Kind
  22666. * - BABYLON.VertexBuffer.ColorKind
  22667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22671. */
  22672. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22673. if (!this._geometry) {
  22674. if (this._delayInfo) {
  22675. return this._delayInfo.indexOf(kind) !== -1;
  22676. }
  22677. return false;
  22678. }
  22679. return this._geometry.isVerticesDataPresent(kind);
  22680. };
  22681. /**
  22682. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22683. * Possible `kind` values :
  22684. * - BABYLON.VertexBuffer.PositionKind
  22685. * - BABYLON.VertexBuffer.UVKind
  22686. * - BABYLON.VertexBuffer.UV2Kind
  22687. * - BABYLON.VertexBuffer.UV3Kind
  22688. * - BABYLON.VertexBuffer.UV4Kind
  22689. * - BABYLON.VertexBuffer.UV5Kind
  22690. * - BABYLON.VertexBuffer.UV6Kind
  22691. * - BABYLON.VertexBuffer.ColorKind
  22692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22696. */
  22697. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22698. if (!this._geometry) {
  22699. if (this._delayInfo) {
  22700. return this._delayInfo.indexOf(kind) !== -1;
  22701. }
  22702. return false;
  22703. }
  22704. return this._geometry.isVertexBufferUpdatable(kind);
  22705. };
  22706. /**
  22707. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22708. * Possible `kind` values :
  22709. * - BABYLON.VertexBuffer.PositionKind
  22710. * - BABYLON.VertexBuffer.UVKind
  22711. * - BABYLON.VertexBuffer.UV2Kind
  22712. * - BABYLON.VertexBuffer.UV3Kind
  22713. * - BABYLON.VertexBuffer.UV4Kind
  22714. * - BABYLON.VertexBuffer.UV5Kind
  22715. * - BABYLON.VertexBuffer.UV6Kind
  22716. * - BABYLON.VertexBuffer.ColorKind
  22717. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22718. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22719. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22720. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22721. */
  22722. Mesh.prototype.getVerticesDataKinds = function () {
  22723. if (!this._geometry) {
  22724. var result = new Array();
  22725. if (this._delayInfo) {
  22726. this._delayInfo.forEach(function (kind, index, array) {
  22727. result.push(kind);
  22728. });
  22729. }
  22730. return result;
  22731. }
  22732. return this._geometry.getVerticesDataKinds();
  22733. };
  22734. /**
  22735. * Returns a positive integer : the total number of indices in this mesh geometry.
  22736. * Returns zero if the mesh has no geometry.
  22737. */
  22738. Mesh.prototype.getTotalIndices = function () {
  22739. if (!this._geometry) {
  22740. return 0;
  22741. }
  22742. return this._geometry.getTotalIndices();
  22743. };
  22744. /**
  22745. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22746. * 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.
  22747. * Returns an empty array if the mesh has no geometry.
  22748. */
  22749. Mesh.prototype.getIndices = function (copyWhenShared) {
  22750. if (!this._geometry) {
  22751. return [];
  22752. }
  22753. return this._geometry.getIndices(copyWhenShared);
  22754. };
  22755. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22756. get: function () {
  22757. return this._masterMesh !== null && this._masterMesh !== undefined;
  22758. },
  22759. enumerable: true,
  22760. configurable: true
  22761. });
  22762. /**
  22763. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22764. */
  22765. Mesh.prototype.isReady = function () {
  22766. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22767. return false;
  22768. }
  22769. return _super.prototype.isReady.call(this);
  22770. };
  22771. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22772. /**
  22773. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22774. * This property is pertinent only for updatable parametric shapes.
  22775. */
  22776. get: function () {
  22777. return this._areNormalsFrozen;
  22778. },
  22779. enumerable: true,
  22780. configurable: true
  22781. });
  22782. /**
  22783. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22784. * It has no effect at all on other shapes.
  22785. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22786. * Returns the Mesh.
  22787. */
  22788. Mesh.prototype.freezeNormals = function () {
  22789. this._areNormalsFrozen = true;
  22790. return this;
  22791. };
  22792. /**
  22793. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22794. * It has no effect at all on other shapes.
  22795. * It reactivates the mesh normals computation if it was previously frozen.
  22796. * Returns the Mesh.
  22797. */
  22798. Mesh.prototype.unfreezeNormals = function () {
  22799. this._areNormalsFrozen = false;
  22800. return this;
  22801. };
  22802. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22803. /**
  22804. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22805. */
  22806. set: function (count) {
  22807. this._overridenInstanceCount = count;
  22808. },
  22809. enumerable: true,
  22810. configurable: true
  22811. });
  22812. // Methods
  22813. Mesh.prototype._preActivate = function () {
  22814. var sceneRenderId = this.getScene().getRenderId();
  22815. if (this._preActivateId === sceneRenderId) {
  22816. return this;
  22817. }
  22818. this._preActivateId = sceneRenderId;
  22819. this._visibleInstances = null;
  22820. return this;
  22821. };
  22822. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22823. if (this._visibleInstances) {
  22824. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22825. }
  22826. return this;
  22827. };
  22828. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22829. if (!this._visibleInstances) {
  22830. this._visibleInstances = {};
  22831. this._visibleInstances.defaultRenderId = renderId;
  22832. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22833. }
  22834. if (!this._visibleInstances[renderId]) {
  22835. this._visibleInstances[renderId] = new Array();
  22836. }
  22837. this._visibleInstances[renderId].push(instance);
  22838. return this;
  22839. };
  22840. /**
  22841. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22842. * This means the mesh underlying bounding box and sphere are recomputed.
  22843. * Returns the Mesh.
  22844. */
  22845. Mesh.prototype.refreshBoundingInfo = function () {
  22846. if (this._boundingInfo && this._boundingInfo.isLocked) {
  22847. return this;
  22848. }
  22849. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22850. if (data) {
  22851. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22852. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22853. }
  22854. if (this.subMeshes) {
  22855. for (var index = 0; index < this.subMeshes.length; index++) {
  22856. this.subMeshes[index].refreshBoundingInfo();
  22857. }
  22858. }
  22859. this._updateBoundingInfo();
  22860. return this;
  22861. };
  22862. Mesh.prototype._createGlobalSubMesh = function (force) {
  22863. var totalVertices = this.getTotalVertices();
  22864. if (!totalVertices || !this.getIndices()) {
  22865. return null;
  22866. }
  22867. // Check if we need to recreate the submeshes
  22868. if (this.subMeshes && this.subMeshes.length > 0) {
  22869. var ib = this.getIndices();
  22870. if (!ib) {
  22871. return null;
  22872. }
  22873. var totalIndices = ib.length;
  22874. var needToRecreate = false;
  22875. if (force) {
  22876. needToRecreate = true;
  22877. }
  22878. else {
  22879. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22880. var submesh = _a[_i];
  22881. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22882. needToRecreate = true;
  22883. break;
  22884. }
  22885. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22886. needToRecreate = true;
  22887. break;
  22888. }
  22889. }
  22890. }
  22891. if (!needToRecreate) {
  22892. return this.subMeshes[0];
  22893. }
  22894. }
  22895. this.releaseSubMeshes();
  22896. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22897. };
  22898. Mesh.prototype.subdivide = function (count) {
  22899. if (count < 1) {
  22900. return;
  22901. }
  22902. var totalIndices = this.getTotalIndices();
  22903. var subdivisionSize = (totalIndices / count) | 0;
  22904. var offset = 0;
  22905. // Ensure that subdivisionSize is a multiple of 3
  22906. while (subdivisionSize % 3 !== 0) {
  22907. subdivisionSize++;
  22908. }
  22909. this.releaseSubMeshes();
  22910. for (var index = 0; index < count; index++) {
  22911. if (offset >= totalIndices) {
  22912. break;
  22913. }
  22914. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22915. offset += subdivisionSize;
  22916. }
  22917. this.synchronizeInstances();
  22918. };
  22919. /**
  22920. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22921. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22922. * The `data` are either a numeric array either a Float32Array.
  22923. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22924. * 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).
  22925. * Note that a new underlying VertexBuffer object is created each call.
  22926. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22927. *
  22928. * Possible `kind` values :
  22929. * - BABYLON.VertexBuffer.PositionKind
  22930. * - BABYLON.VertexBuffer.UVKind
  22931. * - BABYLON.VertexBuffer.UV2Kind
  22932. * - BABYLON.VertexBuffer.UV3Kind
  22933. * - BABYLON.VertexBuffer.UV4Kind
  22934. * - BABYLON.VertexBuffer.UV5Kind
  22935. * - BABYLON.VertexBuffer.UV6Kind
  22936. * - BABYLON.VertexBuffer.ColorKind
  22937. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22938. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22939. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22940. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22941. *
  22942. * Returns the Mesh.
  22943. */
  22944. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22945. if (updatable === void 0) { updatable = false; }
  22946. if (!this._geometry) {
  22947. var vertexData = new BABYLON.VertexData();
  22948. vertexData.set(data, kind);
  22949. var scene = this.getScene();
  22950. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22951. }
  22952. else {
  22953. this._geometry.setVerticesData(kind, data, updatable, stride);
  22954. }
  22955. return this;
  22956. };
  22957. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22958. if (updatable === void 0) { updatable = true; }
  22959. var vb = this.getVertexBuffer(kind);
  22960. if (!vb || vb.isUpdatable() === updatable) {
  22961. return;
  22962. }
  22963. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22964. };
  22965. /**
  22966. * Sets the mesh VertexBuffer.
  22967. * Returns the Mesh.
  22968. */
  22969. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22970. if (!this._geometry) {
  22971. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  22972. }
  22973. this._geometry.setVerticesBuffer(buffer);
  22974. return this;
  22975. };
  22976. /**
  22977. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22978. * If the mesh has no geometry, it is simply returned as it is.
  22979. * The `data` are either a numeric array either a Float32Array.
  22980. * No new underlying VertexBuffer object is created.
  22981. * 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.
  22982. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22983. *
  22984. * Possible `kind` values :
  22985. * - BABYLON.VertexBuffer.PositionKind
  22986. * - BABYLON.VertexBuffer.UVKind
  22987. * - BABYLON.VertexBuffer.UV2Kind
  22988. * - BABYLON.VertexBuffer.UV3Kind
  22989. * - BABYLON.VertexBuffer.UV4Kind
  22990. * - BABYLON.VertexBuffer.UV5Kind
  22991. * - BABYLON.VertexBuffer.UV6Kind
  22992. * - BABYLON.VertexBuffer.ColorKind
  22993. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22994. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22995. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22996. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22997. *
  22998. * Returns the Mesh.
  22999. */
  23000. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23001. if (!this._geometry) {
  23002. return this;
  23003. }
  23004. if (!makeItUnique) {
  23005. this._geometry.updateVerticesData(kind, data, updateExtends);
  23006. }
  23007. else {
  23008. this.makeGeometryUnique();
  23009. this.updateVerticesData(kind, data, updateExtends, false);
  23010. }
  23011. return this;
  23012. };
  23013. /**
  23014. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23015. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23016. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23017. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23018. * Returns the Mesh.
  23019. */
  23020. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23021. if (computeNormals === void 0) { computeNormals = true; }
  23022. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23023. if (!positions) {
  23024. return this;
  23025. }
  23026. positionFunction(positions);
  23027. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23028. if (computeNormals) {
  23029. var indices = this.getIndices();
  23030. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23031. if (!normals) {
  23032. return this;
  23033. }
  23034. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23035. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23036. }
  23037. return this;
  23038. };
  23039. /**
  23040. * Creates a un-shared specific occurence of the geometry for the mesh.
  23041. * Returns the Mesh.
  23042. */
  23043. Mesh.prototype.makeGeometryUnique = function () {
  23044. if (!this._geometry) {
  23045. return this;
  23046. }
  23047. var oldGeometry = this._geometry;
  23048. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23049. oldGeometry.releaseForMesh(this, true);
  23050. geometry.applyToMesh(this);
  23051. return this;
  23052. };
  23053. /**
  23054. * Sets the mesh indices.
  23055. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23056. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23057. * This method creates a new index buffer each call.
  23058. * Returns the Mesh.
  23059. */
  23060. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23061. if (totalVertices === void 0) { totalVertices = null; }
  23062. if (updatable === void 0) { updatable = false; }
  23063. if (!this._geometry) {
  23064. var vertexData = new BABYLON.VertexData();
  23065. vertexData.indices = indices;
  23066. var scene = this.getScene();
  23067. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23068. }
  23069. else {
  23070. this._geometry.setIndices(indices, totalVertices, updatable);
  23071. }
  23072. return this;
  23073. };
  23074. /**
  23075. * Update the current index buffer
  23076. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23077. * Returns the Mesh.
  23078. */
  23079. Mesh.prototype.updateIndices = function (indices, offset) {
  23080. if (!this._geometry) {
  23081. return this;
  23082. }
  23083. this._geometry.updateIndices(indices, offset);
  23084. return this;
  23085. };
  23086. /**
  23087. * Invert the geometry to move from a right handed system to a left handed one.
  23088. * Returns the Mesh.
  23089. */
  23090. Mesh.prototype.toLeftHanded = function () {
  23091. if (!this._geometry) {
  23092. return this;
  23093. }
  23094. this._geometry.toLeftHanded();
  23095. return this;
  23096. };
  23097. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23098. if (!this._geometry) {
  23099. return this;
  23100. }
  23101. var engine = this.getScene().getEngine();
  23102. // Wireframe
  23103. var indexToBind;
  23104. if (this._unIndexed) {
  23105. indexToBind = null;
  23106. }
  23107. else {
  23108. switch (fillMode) {
  23109. case BABYLON.Material.PointFillMode:
  23110. indexToBind = null;
  23111. break;
  23112. case BABYLON.Material.WireFrameFillMode:
  23113. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23114. break;
  23115. default:
  23116. case BABYLON.Material.TriangleFillMode:
  23117. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23118. break;
  23119. }
  23120. }
  23121. // VBOs
  23122. this._geometry._bind(effect, indexToBind);
  23123. return this;
  23124. };
  23125. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23126. if (alternate === void 0) { alternate = false; }
  23127. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23128. return this;
  23129. }
  23130. this.onBeforeDrawObservable.notifyObservers(this);
  23131. var scene = this.getScene();
  23132. var engine = scene.getEngine();
  23133. // Draw order
  23134. switch (fillMode) {
  23135. case BABYLON.Material.PointFillMode:
  23136. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23137. break;
  23138. case BABYLON.Material.WireFrameFillMode:
  23139. if (this._unIndexed) {
  23140. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23141. }
  23142. else {
  23143. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23144. }
  23145. break;
  23146. default:
  23147. if (this._unIndexed) {
  23148. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23149. }
  23150. else {
  23151. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23152. }
  23153. }
  23154. if (scene._isAlternateRenderingEnabled && !alternate) {
  23155. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23156. if (!effect || !scene.activeCamera) {
  23157. return this;
  23158. }
  23159. scene._switchToAlternateCameraConfiguration(true);
  23160. this._effectiveMaterial.bindView(effect);
  23161. this._effectiveMaterial.bindViewProjection(effect);
  23162. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23163. this._draw(subMesh, fillMode, instancesCount, true);
  23164. engine.setViewport(scene.activeCamera.viewport);
  23165. scene._switchToAlternateCameraConfiguration(false);
  23166. this._effectiveMaterial.bindView(effect);
  23167. this._effectiveMaterial.bindViewProjection(effect);
  23168. }
  23169. return this;
  23170. };
  23171. /**
  23172. * Registers for this mesh a javascript function called just before the rendering process.
  23173. * This function is passed the current mesh.
  23174. * Return the Mesh.
  23175. */
  23176. Mesh.prototype.registerBeforeRender = function (func) {
  23177. this.onBeforeRenderObservable.add(func);
  23178. return this;
  23179. };
  23180. /**
  23181. * Disposes a previously registered javascript function called before the rendering.
  23182. * This function is passed the current mesh.
  23183. * Returns the Mesh.
  23184. */
  23185. Mesh.prototype.unregisterBeforeRender = function (func) {
  23186. this.onBeforeRenderObservable.removeCallback(func);
  23187. return this;
  23188. };
  23189. /**
  23190. * Registers for this mesh a javascript function called just after the rendering is complete.
  23191. * This function is passed the current mesh.
  23192. * Returns the Mesh.
  23193. */
  23194. Mesh.prototype.registerAfterRender = function (func) {
  23195. this.onAfterRenderObservable.add(func);
  23196. return this;
  23197. };
  23198. /**
  23199. * Disposes a previously registered javascript function called after the rendering.
  23200. * This function is passed the current mesh.
  23201. * Return the Mesh.
  23202. */
  23203. Mesh.prototype.unregisterAfterRender = function (func) {
  23204. this.onAfterRenderObservable.removeCallback(func);
  23205. return this;
  23206. };
  23207. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23208. var scene = this.getScene();
  23209. this._batchCache.mustReturn = false;
  23210. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23211. this._batchCache.visibleInstances[subMeshId] = null;
  23212. if (this._visibleInstances) {
  23213. var currentRenderId = scene.getRenderId();
  23214. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23215. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23216. var selfRenderId = this._renderId;
  23217. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23218. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23219. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23220. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23221. }
  23222. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23223. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23224. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23225. this._batchCache.mustReturn = true;
  23226. return this._batchCache;
  23227. }
  23228. if (currentRenderId !== selfRenderId) {
  23229. this._batchCache.renderSelf[subMeshId] = false;
  23230. }
  23231. }
  23232. this._renderIdForInstances[subMeshId] = currentRenderId;
  23233. }
  23234. return this._batchCache;
  23235. };
  23236. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23237. var visibleInstances = batch.visibleInstances[subMesh._id];
  23238. if (!visibleInstances) {
  23239. return this;
  23240. }
  23241. var matricesCount = visibleInstances.length + 1;
  23242. var bufferSize = matricesCount * 16 * 4;
  23243. var currentInstancesBufferSize = this._instancesBufferSize;
  23244. var instancesBuffer = this._instancesBuffer;
  23245. while (this._instancesBufferSize < bufferSize) {
  23246. this._instancesBufferSize *= 2;
  23247. }
  23248. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23249. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23250. }
  23251. var offset = 0;
  23252. var instancesCount = 0;
  23253. var world = this.getWorldMatrix();
  23254. if (batch.renderSelf[subMesh._id]) {
  23255. world.copyToArray(this._instancesData, offset);
  23256. offset += 16;
  23257. instancesCount++;
  23258. }
  23259. if (visibleInstances) {
  23260. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23261. var instance = visibleInstances[instanceIndex];
  23262. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23263. offset += 16;
  23264. instancesCount++;
  23265. }
  23266. }
  23267. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23268. if (instancesBuffer) {
  23269. instancesBuffer.dispose();
  23270. }
  23271. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23272. this._instancesBuffer = instancesBuffer;
  23273. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23274. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23275. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23276. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23277. }
  23278. else {
  23279. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23280. }
  23281. this._bind(subMesh, effect, fillMode);
  23282. this._draw(subMesh, fillMode, instancesCount);
  23283. engine.unbindInstanceAttributes();
  23284. return this;
  23285. };
  23286. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23287. var scene = this.getScene();
  23288. var engine = scene.getEngine();
  23289. if (hardwareInstancedRendering) {
  23290. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23291. }
  23292. else {
  23293. if (batch.renderSelf[subMesh._id]) {
  23294. // Draw
  23295. if (onBeforeDraw) {
  23296. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23297. }
  23298. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23299. }
  23300. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23301. if (visibleInstancesForSubMesh) {
  23302. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23303. var instance = visibleInstancesForSubMesh[instanceIndex];
  23304. // World
  23305. var world = instance.getWorldMatrix();
  23306. if (onBeforeDraw) {
  23307. onBeforeDraw(true, world, effectiveMaterial);
  23308. }
  23309. // Draw
  23310. this._draw(subMesh, fillMode);
  23311. }
  23312. }
  23313. }
  23314. return this;
  23315. };
  23316. /**
  23317. * Triggers the draw call for the mesh.
  23318. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23319. * Returns the Mesh.
  23320. */
  23321. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23322. this.checkOcclusionQuery();
  23323. if (this._isOccluded) {
  23324. return this;
  23325. }
  23326. var scene = this.getScene();
  23327. // Managing instances
  23328. var batch = this._getInstancesRenderList(subMesh._id);
  23329. if (batch.mustReturn) {
  23330. return this;
  23331. }
  23332. // Checking geometry state
  23333. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23334. return this;
  23335. }
  23336. this.onBeforeRenderObservable.notifyObservers(this);
  23337. var engine = scene.getEngine();
  23338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23339. // Material
  23340. var material = subMesh.getMaterial();
  23341. if (!material) {
  23342. return this;
  23343. }
  23344. this._effectiveMaterial = material;
  23345. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23346. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23347. return this;
  23348. }
  23349. }
  23350. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23351. return this;
  23352. }
  23353. // Alpha mode
  23354. if (enableAlphaMode) {
  23355. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23356. }
  23357. // Outline - step 1
  23358. var savedDepthWrite = engine.getDepthWrite();
  23359. if (this.renderOutline) {
  23360. engine.setDepthWrite(false);
  23361. scene.getOutlineRenderer().render(subMesh, batch);
  23362. engine.setDepthWrite(savedDepthWrite);
  23363. }
  23364. var effect;
  23365. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23366. effect = subMesh.effect;
  23367. }
  23368. else {
  23369. effect = this._effectiveMaterial.getEffect();
  23370. }
  23371. if (!effect) {
  23372. return this;
  23373. }
  23374. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23375. if (this._effectiveMaterial.forceDepthWrite) {
  23376. engine.setDepthWrite(true);
  23377. }
  23378. // Bind
  23379. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23380. if (!hardwareInstancedRendering) {
  23381. this._bind(subMesh, effect, fillMode);
  23382. }
  23383. var world = this.getWorldMatrix();
  23384. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23385. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23386. }
  23387. else {
  23388. this._effectiveMaterial.bind(world, this);
  23389. }
  23390. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23391. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23392. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23393. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23394. }
  23395. // Draw
  23396. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23397. // Unbind
  23398. this._effectiveMaterial.unbind();
  23399. // Outline - step 2
  23400. if (this.renderOutline && savedDepthWrite) {
  23401. engine.setDepthWrite(true);
  23402. engine.setColorWrite(false);
  23403. scene.getOutlineRenderer().render(subMesh, batch);
  23404. engine.setColorWrite(true);
  23405. }
  23406. // Overlay
  23407. if (this.renderOverlay) {
  23408. var currentMode = engine.getAlphaMode();
  23409. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23410. scene.getOutlineRenderer().render(subMesh, batch, true);
  23411. engine.setAlphaMode(currentMode);
  23412. }
  23413. this.onAfterRenderObservable.notifyObservers(this);
  23414. return this;
  23415. };
  23416. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23417. if (isInstance) {
  23418. effectiveMaterial.bindOnlyWorldMatrix(world);
  23419. }
  23420. return this;
  23421. };
  23422. /**
  23423. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23424. */
  23425. Mesh.prototype.getEmittedParticleSystems = function () {
  23426. var results = new Array();
  23427. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23428. var particleSystem = this.getScene().particleSystems[index];
  23429. if (particleSystem.emitter === this) {
  23430. results.push(particleSystem);
  23431. }
  23432. }
  23433. return results;
  23434. };
  23435. /**
  23436. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23437. */
  23438. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23439. var results = new Array();
  23440. var descendants = this.getDescendants();
  23441. descendants.push(this);
  23442. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23443. var particleSystem = this.getScene().particleSystems[index];
  23444. var emitter = particleSystem.emitter;
  23445. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23446. results.push(particleSystem);
  23447. }
  23448. }
  23449. return results;
  23450. };
  23451. Mesh.prototype._checkDelayState = function () {
  23452. var scene = this.getScene();
  23453. if (this._geometry) {
  23454. this._geometry.load(scene);
  23455. }
  23456. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23457. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23458. this._queueLoad(this, scene);
  23459. }
  23460. return this;
  23461. };
  23462. Mesh.prototype._queueLoad = function (mesh, scene) {
  23463. var _this = this;
  23464. scene._addPendingData(mesh);
  23465. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23466. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23467. if (data instanceof ArrayBuffer) {
  23468. _this._delayLoadingFunction(data, _this);
  23469. }
  23470. else {
  23471. _this._delayLoadingFunction(JSON.parse(data), _this);
  23472. }
  23473. _this.instances.forEach(function (instance) {
  23474. instance._syncSubMeshes();
  23475. });
  23476. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23477. scene._removePendingData(_this);
  23478. }, function () { }, scene.database, getBinaryData);
  23479. return this;
  23480. };
  23481. /**
  23482. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23483. */
  23484. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23485. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23486. return false;
  23487. }
  23488. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23489. return false;
  23490. }
  23491. this._checkDelayState();
  23492. return true;
  23493. };
  23494. /**
  23495. * Sets the mesh material by the material or multiMaterial `id` property.
  23496. * The material `id` is a string identifying the material or the multiMaterial.
  23497. * This method returns the Mesh.
  23498. */
  23499. Mesh.prototype.setMaterialByID = function (id) {
  23500. var materials = this.getScene().materials;
  23501. var index;
  23502. for (index = materials.length - 1; index > -1; index--) {
  23503. if (materials[index].id === id) {
  23504. this.material = materials[index];
  23505. return this;
  23506. }
  23507. }
  23508. // Multi
  23509. var multiMaterials = this.getScene().multiMaterials;
  23510. for (index = multiMaterials.length - 1; index > -1; index--) {
  23511. if (multiMaterials[index].id === id) {
  23512. this.material = multiMaterials[index];
  23513. return this;
  23514. }
  23515. }
  23516. return this;
  23517. };
  23518. /**
  23519. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23520. */
  23521. Mesh.prototype.getAnimatables = function () {
  23522. var results = new Array();
  23523. if (this.material) {
  23524. results.push(this.material);
  23525. }
  23526. if (this.skeleton) {
  23527. results.push(this.skeleton);
  23528. }
  23529. return results;
  23530. };
  23531. /**
  23532. * Modifies the mesh geometry according to the passed transformation matrix.
  23533. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23534. * The mesh normals are modified accordingly the same transformation.
  23535. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23536. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23537. * Returns the Mesh.
  23538. */
  23539. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23540. // Position
  23541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23542. return this;
  23543. }
  23544. var submeshes = this.subMeshes.splice(0);
  23545. this._resetPointsArrayCache();
  23546. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23547. var temp = new Array();
  23548. var index;
  23549. for (index = 0; index < data.length; index += 3) {
  23550. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23551. }
  23552. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23553. // Normals
  23554. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23555. return this;
  23556. }
  23557. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23558. temp = [];
  23559. for (index = 0; index < data.length; index += 3) {
  23560. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23561. }
  23562. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23563. // flip faces?
  23564. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23565. this.flipFaces();
  23566. }
  23567. // Restore submeshes
  23568. this.releaseSubMeshes();
  23569. this.subMeshes = submeshes;
  23570. return this;
  23571. };
  23572. /**
  23573. * Modifies the mesh geometry according to its own current World Matrix.
  23574. * The mesh World Matrix is then reset.
  23575. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23576. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23577. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23578. * Returns the Mesh.
  23579. */
  23580. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23581. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23582. this.scaling.copyFromFloats(1, 1, 1);
  23583. this.position.copyFromFloats(0, 0, 0);
  23584. this.rotation.copyFromFloats(0, 0, 0);
  23585. //only if quaternion is already set
  23586. if (this.rotationQuaternion) {
  23587. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23588. }
  23589. this._worldMatrix = BABYLON.Matrix.Identity();
  23590. return this;
  23591. };
  23592. Object.defineProperty(Mesh.prototype, "_positions", {
  23593. // Cache
  23594. get: function () {
  23595. if (this._geometry) {
  23596. return this._geometry._positions;
  23597. }
  23598. return null;
  23599. },
  23600. enumerable: true,
  23601. configurable: true
  23602. });
  23603. Mesh.prototype._resetPointsArrayCache = function () {
  23604. if (this._geometry) {
  23605. this._geometry._resetPointsArrayCache();
  23606. }
  23607. return this;
  23608. };
  23609. Mesh.prototype._generatePointsArray = function () {
  23610. if (this._geometry) {
  23611. return this._geometry._generatePointsArray();
  23612. }
  23613. return false;
  23614. };
  23615. /**
  23616. * Returns a new Mesh object generated from the current mesh properties.
  23617. * This method must not get confused with createInstance().
  23618. * The parameter `name` is a string, the name given to the new mesh.
  23619. * The optional parameter `newParent` can be any Node object (default `null`).
  23620. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23621. * 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.
  23622. */
  23623. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23624. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23625. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23626. };
  23627. /**
  23628. * Disposes the mesh.
  23629. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23630. */
  23631. Mesh.prototype.dispose = function (doNotRecurse) {
  23632. var _this = this;
  23633. this.morphTargetManager = null;
  23634. if (this._geometry) {
  23635. this._geometry.releaseForMesh(this, true);
  23636. }
  23637. // Sources
  23638. var meshes = this.getScene().meshes;
  23639. meshes.forEach(function (mesh) {
  23640. if (mesh._source && mesh._source === _this) {
  23641. mesh._source = null;
  23642. }
  23643. });
  23644. this._source = null;
  23645. // Instances
  23646. if (this._instancesBuffer) {
  23647. this._instancesBuffer.dispose();
  23648. this._instancesBuffer = null;
  23649. }
  23650. while (this.instances.length) {
  23651. this.instances[0].dispose();
  23652. }
  23653. // Highlight layers.
  23654. var highlightLayers = this.getScene().highlightLayers;
  23655. for (var i = 0; i < highlightLayers.length; i++) {
  23656. var highlightLayer = highlightLayers[i];
  23657. if (highlightLayer) {
  23658. highlightLayer.removeMesh(this);
  23659. highlightLayer.removeExcludedMesh(this);
  23660. }
  23661. }
  23662. _super.prototype.dispose.call(this, doNotRecurse);
  23663. };
  23664. /**
  23665. * Modifies the mesh geometry according to a displacement map.
  23666. * 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.
  23667. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23668. * This method returns nothing.
  23669. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23670. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23671. * 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.
  23672. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23673. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23674. *
  23675. * Returns the Mesh.
  23676. */
  23677. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23678. var _this = this;
  23679. var scene = this.getScene();
  23680. var onload = function (img) {
  23681. // Getting height map data
  23682. var canvas = document.createElement("canvas");
  23683. var context = canvas.getContext("2d");
  23684. var heightMapWidth = img.width;
  23685. var heightMapHeight = img.height;
  23686. canvas.width = heightMapWidth;
  23687. canvas.height = heightMapHeight;
  23688. context.drawImage(img, 0, 0);
  23689. // Create VertexData from map data
  23690. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23691. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23692. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23693. //execute success callback, if set
  23694. if (onSuccess) {
  23695. onSuccess(_this);
  23696. }
  23697. };
  23698. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23699. return this;
  23700. };
  23701. /**
  23702. * Modifies the mesh geometry according to a displacementMap buffer.
  23703. * 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.
  23704. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23705. * This method returns nothing.
  23706. * 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.
  23707. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23708. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23709. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23710. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23711. *
  23712. * Returns the Mesh.
  23713. */
  23714. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23716. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23717. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23718. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23719. return this;
  23720. }
  23721. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23722. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23723. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23724. var position = BABYLON.Vector3.Zero();
  23725. var normal = BABYLON.Vector3.Zero();
  23726. var uv = BABYLON.Vector2.Zero();
  23727. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23728. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23729. for (var index = 0; index < positions.length; index += 3) {
  23730. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23731. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23732. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23733. // Compute height
  23734. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23735. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23736. var pos = (u + v * heightMapWidth) * 4;
  23737. var r = buffer[pos] / 255.0;
  23738. var g = buffer[pos + 1] / 255.0;
  23739. var b = buffer[pos + 2] / 255.0;
  23740. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23741. normal.normalize();
  23742. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23743. position = position.add(normal);
  23744. position.toArray(positions, index);
  23745. }
  23746. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23747. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23748. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23749. return this;
  23750. };
  23751. /**
  23752. * Modify the mesh to get a flat shading rendering.
  23753. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23754. * This method returns the Mesh.
  23755. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23756. */
  23757. Mesh.prototype.convertToFlatShadedMesh = function () {
  23758. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23759. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23760. var kinds = this.getVerticesDataKinds();
  23761. var vbs = {};
  23762. var data = {};
  23763. var newdata = {};
  23764. var updatableNormals = false;
  23765. var kindIndex;
  23766. var kind;
  23767. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23768. kind = kinds[kindIndex];
  23769. var vertexBuffer = this.getVertexBuffer(kind);
  23770. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23771. updatableNormals = vertexBuffer.isUpdatable();
  23772. kinds.splice(kindIndex, 1);
  23773. kindIndex--;
  23774. continue;
  23775. }
  23776. vbs[kind] = vertexBuffer;
  23777. data[kind] = vbs[kind].getData();
  23778. newdata[kind] = [];
  23779. }
  23780. // Save previous submeshes
  23781. var previousSubmeshes = this.subMeshes.slice(0);
  23782. var indices = this.getIndices();
  23783. var totalIndices = this.getTotalIndices();
  23784. // Generating unique vertices per face
  23785. var index;
  23786. for (index = 0; index < totalIndices; index++) {
  23787. var vertexIndex = indices[index];
  23788. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23789. kind = kinds[kindIndex];
  23790. var stride = vbs[kind].getStrideSize();
  23791. for (var offset = 0; offset < stride; offset++) {
  23792. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23793. }
  23794. }
  23795. }
  23796. // Updating faces & normal
  23797. var normals = [];
  23798. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23799. for (index = 0; index < totalIndices; index += 3) {
  23800. indices[index] = index;
  23801. indices[index + 1] = index + 1;
  23802. indices[index + 2] = index + 2;
  23803. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23804. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23805. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23806. var p1p2 = p1.subtract(p2);
  23807. var p3p2 = p3.subtract(p2);
  23808. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23809. // Store same normals for every vertex
  23810. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23811. normals.push(normal.x);
  23812. normals.push(normal.y);
  23813. normals.push(normal.z);
  23814. }
  23815. }
  23816. this.setIndices(indices);
  23817. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23818. // Updating vertex buffers
  23819. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23820. kind = kinds[kindIndex];
  23821. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23822. }
  23823. // Updating submeshes
  23824. this.releaseSubMeshes();
  23825. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23826. var previousOne = previousSubmeshes[submeshIndex];
  23827. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23828. }
  23829. this.synchronizeInstances();
  23830. return this;
  23831. };
  23832. /**
  23833. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23834. * In other words, more vertices, no more indices and a single bigger VBO.
  23835. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23836. * Returns the Mesh.
  23837. */
  23838. Mesh.prototype.convertToUnIndexedMesh = function () {
  23839. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23840. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23841. var kinds = this.getVerticesDataKinds();
  23842. var vbs = {};
  23843. var data = {};
  23844. var newdata = {};
  23845. var kindIndex;
  23846. var kind;
  23847. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23848. kind = kinds[kindIndex];
  23849. var vertexBuffer = this.getVertexBuffer(kind);
  23850. vbs[kind] = vertexBuffer;
  23851. data[kind] = vbs[kind].getData();
  23852. newdata[kind] = [];
  23853. }
  23854. // Save previous submeshes
  23855. var previousSubmeshes = this.subMeshes.slice(0);
  23856. var indices = this.getIndices();
  23857. var totalIndices = this.getTotalIndices();
  23858. // Generating unique vertices per face
  23859. var index;
  23860. for (index = 0; index < totalIndices; index++) {
  23861. var vertexIndex = indices[index];
  23862. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23863. kind = kinds[kindIndex];
  23864. var stride = vbs[kind].getStrideSize();
  23865. for (var offset = 0; offset < stride; offset++) {
  23866. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23867. }
  23868. }
  23869. }
  23870. // Updating indices
  23871. for (index = 0; index < totalIndices; index += 3) {
  23872. indices[index] = index;
  23873. indices[index + 1] = index + 1;
  23874. indices[index + 2] = index + 2;
  23875. }
  23876. this.setIndices(indices);
  23877. // Updating vertex buffers
  23878. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23879. kind = kinds[kindIndex];
  23880. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23881. }
  23882. // Updating submeshes
  23883. this.releaseSubMeshes();
  23884. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23885. var previousOne = previousSubmeshes[submeshIndex];
  23886. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23887. }
  23888. this._unIndexed = true;
  23889. this.synchronizeInstances();
  23890. return this;
  23891. };
  23892. /**
  23893. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23894. * This method returns the Mesh.
  23895. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23896. */
  23897. Mesh.prototype.flipFaces = function (flipNormals) {
  23898. if (flipNormals === void 0) { flipNormals = false; }
  23899. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23900. var i;
  23901. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  23902. for (i = 0; i < vertex_data.normals.length; i++) {
  23903. vertex_data.normals[i] *= -1;
  23904. }
  23905. }
  23906. if (vertex_data.indices) {
  23907. var temp;
  23908. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23909. // reassign indices
  23910. temp = vertex_data.indices[i + 1];
  23911. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23912. vertex_data.indices[i + 2] = temp;
  23913. }
  23914. }
  23915. vertex_data.applyToMesh(this);
  23916. return this;
  23917. };
  23918. // Instances
  23919. /**
  23920. * Creates a new InstancedMesh object from the mesh model.
  23921. * An instance shares the same properties and the same material than its model.
  23922. * Only these properties of each instance can then be set individually :
  23923. * - position
  23924. * - rotation
  23925. * - rotationQuaternion
  23926. * - setPivotMatrix
  23927. * - scaling
  23928. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23929. * Warning : this method is not supported for Line mesh and LineSystem
  23930. */
  23931. Mesh.prototype.createInstance = function (name) {
  23932. return new BABYLON.InstancedMesh(name, this);
  23933. };
  23934. /**
  23935. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23936. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23937. * This method returns the Mesh.
  23938. */
  23939. Mesh.prototype.synchronizeInstances = function () {
  23940. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23941. var instance = this.instances[instanceIndex];
  23942. instance._syncSubMeshes();
  23943. }
  23944. return this;
  23945. };
  23946. /**
  23947. * Simplify the mesh according to the given array of settings.
  23948. * Function will return immediately and will simplify async. It returns the Mesh.
  23949. * @param settings a collection of simplification settings.
  23950. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23951. * @param type the type of simplification to run.
  23952. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23953. */
  23954. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23955. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23956. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23957. this.getScene().simplificationQueue.addTask({
  23958. settings: settings,
  23959. parallelProcessing: parallelProcessing,
  23960. mesh: this,
  23961. simplificationType: simplificationType,
  23962. successCallback: successCallback
  23963. });
  23964. return this;
  23965. };
  23966. /**
  23967. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23968. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23969. * This should be used together with the simplification to avoid disappearing triangles.
  23970. * Returns the Mesh.
  23971. * @param successCallback an optional success callback to be called after the optimization finished.
  23972. */
  23973. Mesh.prototype.optimizeIndices = function (successCallback) {
  23974. var _this = this;
  23975. var indices = this.getIndices();
  23976. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23977. if (!positions || !indices) {
  23978. return this;
  23979. }
  23980. var vectorPositions = new Array();
  23981. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23982. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23983. }
  23984. var dupes = new Array();
  23985. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23986. var realPos = vectorPositions.length - 1 - iteration;
  23987. var testedPosition = vectorPositions[realPos];
  23988. for (var j = 0; j < realPos; ++j) {
  23989. var againstPosition = vectorPositions[j];
  23990. if (testedPosition.equals(againstPosition)) {
  23991. dupes[realPos] = j;
  23992. break;
  23993. }
  23994. }
  23995. }, function () {
  23996. for (var i = 0; i < indices.length; ++i) {
  23997. indices[i] = dupes[indices[i]] || indices[i];
  23998. }
  23999. //indices are now reordered
  24000. var originalSubMeshes = _this.subMeshes.slice(0);
  24001. _this.setIndices(indices);
  24002. _this.subMeshes = originalSubMeshes;
  24003. if (successCallback) {
  24004. successCallback(_this);
  24005. }
  24006. });
  24007. return this;
  24008. };
  24009. Mesh.prototype.serialize = function (serializationObject) {
  24010. serializationObject.name = this.name;
  24011. serializationObject.id = this.id;
  24012. serializationObject.type = this.getClassName();
  24013. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24014. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24015. }
  24016. serializationObject.position = this.position.asArray();
  24017. if (this.rotationQuaternion) {
  24018. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24019. }
  24020. else if (this.rotation) {
  24021. serializationObject.rotation = this.rotation.asArray();
  24022. }
  24023. serializationObject.scaling = this.scaling.asArray();
  24024. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24025. serializationObject.isEnabled = this.isEnabled();
  24026. serializationObject.isVisible = this.isVisible;
  24027. serializationObject.infiniteDistance = this.infiniteDistance;
  24028. serializationObject.pickable = this.isPickable;
  24029. serializationObject.receiveShadows = this.receiveShadows;
  24030. serializationObject.billboardMode = this.billboardMode;
  24031. serializationObject.visibility = this.visibility;
  24032. serializationObject.checkCollisions = this.checkCollisions;
  24033. serializationObject.isBlocker = this.isBlocker;
  24034. // Parent
  24035. if (this.parent) {
  24036. serializationObject.parentId = this.parent.id;
  24037. }
  24038. // Geometry
  24039. var geometry = this._geometry;
  24040. if (geometry) {
  24041. var geometryId = geometry.id;
  24042. serializationObject.geometryId = geometryId;
  24043. // SubMeshes
  24044. serializationObject.subMeshes = [];
  24045. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24046. var subMesh = this.subMeshes[subIndex];
  24047. serializationObject.subMeshes.push({
  24048. materialIndex: subMesh.materialIndex,
  24049. verticesStart: subMesh.verticesStart,
  24050. verticesCount: subMesh.verticesCount,
  24051. indexStart: subMesh.indexStart,
  24052. indexCount: subMesh.indexCount
  24053. });
  24054. }
  24055. }
  24056. // Material
  24057. if (this.material) {
  24058. serializationObject.materialId = this.material.id;
  24059. }
  24060. else {
  24061. this.material = null;
  24062. }
  24063. // Morph targets
  24064. if (this.morphTargetManager) {
  24065. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24066. }
  24067. // Skeleton
  24068. if (this.skeleton) {
  24069. serializationObject.skeletonId = this.skeleton.id;
  24070. }
  24071. // Physics
  24072. //TODO implement correct serialization for physics impostors.
  24073. var impostor = this.getPhysicsImpostor();
  24074. if (impostor) {
  24075. serializationObject.physicsMass = impostor.getParam("mass");
  24076. serializationObject.physicsFriction = impostor.getParam("friction");
  24077. serializationObject.physicsRestitution = impostor.getParam("mass");
  24078. serializationObject.physicsImpostor = impostor.type;
  24079. }
  24080. // Metadata
  24081. if (this.metadata) {
  24082. serializationObject.metadata = this.metadata;
  24083. }
  24084. // Instances
  24085. serializationObject.instances = [];
  24086. for (var index = 0; index < this.instances.length; index++) {
  24087. var instance = this.instances[index];
  24088. var serializationInstance = {
  24089. name: instance.name,
  24090. position: instance.position.asArray(),
  24091. scaling: instance.scaling.asArray()
  24092. };
  24093. if (instance.rotationQuaternion) {
  24094. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24095. }
  24096. else if (instance.rotation) {
  24097. serializationInstance.rotation = instance.rotation.asArray();
  24098. }
  24099. serializationObject.instances.push(serializationInstance);
  24100. // Animations
  24101. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24102. serializationInstance.ranges = instance.serializeAnimationRanges();
  24103. }
  24104. //
  24105. // Animations
  24106. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24107. serializationObject.ranges = this.serializeAnimationRanges();
  24108. // Layer mask
  24109. serializationObject.layerMask = this.layerMask;
  24110. // Alpha
  24111. serializationObject.alphaIndex = this.alphaIndex;
  24112. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24113. // Overlay
  24114. serializationObject.overlayAlpha = this.overlayAlpha;
  24115. serializationObject.overlayColor = this.overlayColor.asArray();
  24116. serializationObject.renderOverlay = this.renderOverlay;
  24117. // Fog
  24118. serializationObject.applyFog = this.applyFog;
  24119. // Action Manager
  24120. if (this.actionManager) {
  24121. serializationObject.actions = this.actionManager.serialize(this.name);
  24122. }
  24123. };
  24124. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24125. if (!this.geometry) {
  24126. return;
  24127. }
  24128. this._markSubMeshesAsAttributesDirty();
  24129. var morphTargetManager = this._morphTargetManager;
  24130. if (morphTargetManager && morphTargetManager.vertexCount) {
  24131. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24132. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24133. this.morphTargetManager = null;
  24134. return;
  24135. }
  24136. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24137. var morphTarget = morphTargetManager.getActiveTarget(index);
  24138. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  24139. if (morphTarget.hasNormals) {
  24140. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  24141. }
  24142. if (morphTarget.hasTangents) {
  24143. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  24144. }
  24145. }
  24146. }
  24147. else {
  24148. var index = 0;
  24149. // Positions
  24150. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24151. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24152. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24153. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24154. }
  24155. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24156. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24157. }
  24158. index++;
  24159. }
  24160. }
  24161. };
  24162. // Statics
  24163. /**
  24164. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24165. * The parameter `parsedMesh` is the mesh to be copied.
  24166. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24167. */
  24168. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24169. var mesh;
  24170. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24171. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24172. }
  24173. else {
  24174. mesh = new Mesh(parsedMesh.name, scene);
  24175. }
  24176. mesh.id = parsedMesh.id;
  24177. if (BABYLON.Tags) {
  24178. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24179. }
  24180. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24181. if (parsedMesh.metadata !== undefined) {
  24182. mesh.metadata = parsedMesh.metadata;
  24183. }
  24184. if (parsedMesh.rotationQuaternion) {
  24185. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24186. }
  24187. else if (parsedMesh.rotation) {
  24188. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24189. }
  24190. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24191. if (parsedMesh.localMatrix) {
  24192. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24193. }
  24194. else if (parsedMesh.pivotMatrix) {
  24195. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24196. }
  24197. mesh.setEnabled(parsedMesh.isEnabled);
  24198. mesh.isVisible = parsedMesh.isVisible;
  24199. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24200. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24201. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24202. if (parsedMesh.applyFog !== undefined) {
  24203. mesh.applyFog = parsedMesh.applyFog;
  24204. }
  24205. if (parsedMesh.pickable !== undefined) {
  24206. mesh.isPickable = parsedMesh.pickable;
  24207. }
  24208. if (parsedMesh.alphaIndex !== undefined) {
  24209. mesh.alphaIndex = parsedMesh.alphaIndex;
  24210. }
  24211. mesh.receiveShadows = parsedMesh.receiveShadows;
  24212. mesh.billboardMode = parsedMesh.billboardMode;
  24213. if (parsedMesh.visibility !== undefined) {
  24214. mesh.visibility = parsedMesh.visibility;
  24215. }
  24216. mesh.checkCollisions = parsedMesh.checkCollisions;
  24217. if (parsedMesh.isBlocker !== undefined) {
  24218. mesh.isBlocker = parsedMesh.isBlocker;
  24219. }
  24220. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24221. // freezeWorldMatrix
  24222. if (parsedMesh.freezeWorldMatrix) {
  24223. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24224. }
  24225. // Parent
  24226. if (parsedMesh.parentId) {
  24227. mesh._waitingParentId = parsedMesh.parentId;
  24228. }
  24229. // Actions
  24230. if (parsedMesh.actions !== undefined) {
  24231. mesh._waitingActions = parsedMesh.actions;
  24232. }
  24233. // Overlay
  24234. if (parsedMesh.overlayAlpha !== undefined) {
  24235. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24236. }
  24237. if (parsedMesh.overlayColor !== undefined) {
  24238. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24239. }
  24240. if (parsedMesh.renderOverlay !== undefined) {
  24241. mesh.renderOverlay = parsedMesh.renderOverlay;
  24242. }
  24243. // Geometry
  24244. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24245. if (parsedMesh.delayLoadingFile) {
  24246. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24247. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24248. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24249. if (parsedMesh._binaryInfo) {
  24250. mesh._binaryInfo = parsedMesh._binaryInfo;
  24251. }
  24252. mesh._delayInfo = [];
  24253. if (parsedMesh.hasUVs) {
  24254. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24255. }
  24256. if (parsedMesh.hasUVs2) {
  24257. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24258. }
  24259. if (parsedMesh.hasUVs3) {
  24260. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24261. }
  24262. if (parsedMesh.hasUVs4) {
  24263. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24264. }
  24265. if (parsedMesh.hasUVs5) {
  24266. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24267. }
  24268. if (parsedMesh.hasUVs6) {
  24269. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24270. }
  24271. if (parsedMesh.hasColors) {
  24272. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24273. }
  24274. if (parsedMesh.hasMatricesIndices) {
  24275. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24276. }
  24277. if (parsedMesh.hasMatricesWeights) {
  24278. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24279. }
  24280. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24281. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24282. mesh._checkDelayState();
  24283. }
  24284. }
  24285. else {
  24286. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24287. }
  24288. // Material
  24289. if (parsedMesh.materialId) {
  24290. mesh.setMaterialByID(parsedMesh.materialId);
  24291. }
  24292. else {
  24293. mesh.material = null;
  24294. }
  24295. // Morph targets
  24296. if (parsedMesh.morphTargetManagerId > -1) {
  24297. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24298. }
  24299. // Skeleton
  24300. if (parsedMesh.skeletonId > -1) {
  24301. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24302. if (parsedMesh.numBoneInfluencers) {
  24303. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24304. }
  24305. }
  24306. // Animations
  24307. if (parsedMesh.animations) {
  24308. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24309. var parsedAnimation = parsedMesh.animations[animationIndex];
  24310. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24311. }
  24312. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24313. }
  24314. if (parsedMesh.autoAnimate) {
  24315. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24316. }
  24317. // Layer Mask
  24318. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24319. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24320. }
  24321. else {
  24322. mesh.layerMask = 0x0FFFFFFF;
  24323. }
  24324. // Physics
  24325. if (parsedMesh.physicsImpostor) {
  24326. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24327. mass: parsedMesh.physicsMass,
  24328. friction: parsedMesh.physicsFriction,
  24329. restitution: parsedMesh.physicsRestitution
  24330. }, scene);
  24331. }
  24332. // Instances
  24333. if (parsedMesh.instances) {
  24334. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24335. var parsedInstance = parsedMesh.instances[index];
  24336. var instance = mesh.createInstance(parsedInstance.name);
  24337. if (BABYLON.Tags) {
  24338. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24339. }
  24340. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24341. if (parsedInstance.parentId) {
  24342. instance._waitingParentId = parsedInstance.parentId;
  24343. }
  24344. if (parsedInstance.rotationQuaternion) {
  24345. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24346. }
  24347. else if (parsedInstance.rotation) {
  24348. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24349. }
  24350. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24351. instance.checkCollisions = mesh.checkCollisions;
  24352. if (parsedMesh.animations) {
  24353. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24354. parsedAnimation = parsedMesh.animations[animationIndex];
  24355. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24356. }
  24357. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24358. }
  24359. }
  24360. }
  24361. return mesh;
  24362. };
  24363. /**
  24364. * Creates a ribbon mesh.
  24365. * Please consider using the same method from the MeshBuilder class instead.
  24366. * 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.
  24367. *
  24368. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24369. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24370. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24371. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24372. * 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.
  24373. * 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.
  24374. * 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
  24375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24376. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24378. */
  24379. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24380. if (closeArray === void 0) { closeArray = false; }
  24381. if (updatable === void 0) { updatable = false; }
  24382. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24383. pathArray: pathArray,
  24384. closeArray: closeArray,
  24385. closePath: closePath,
  24386. offset: offset,
  24387. updatable: updatable,
  24388. sideOrientation: sideOrientation,
  24389. instance: instance
  24390. }, scene);
  24391. };
  24392. /**
  24393. * Creates a plane polygonal mesh. By default, this is a disc.
  24394. * Please consider using the same method from the MeshBuilder class instead.
  24395. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24396. * 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.
  24397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24400. */
  24401. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24402. if (scene === void 0) { scene = null; }
  24403. var options = {
  24404. radius: radius,
  24405. tessellation: tessellation,
  24406. sideOrientation: sideOrientation,
  24407. updatable: updatable
  24408. };
  24409. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24410. };
  24411. /**
  24412. * Creates a box mesh.
  24413. * Please consider using the same method from the MeshBuilder class instead.
  24414. * The parameter `size` sets the size (float) of each box side (default 1).
  24415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24418. */
  24419. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24420. if (scene === void 0) { scene = null; }
  24421. var options = {
  24422. size: size,
  24423. sideOrientation: sideOrientation,
  24424. updatable: updatable
  24425. };
  24426. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24427. };
  24428. /**
  24429. * Creates a sphere mesh.
  24430. * Please consider using the same method from the MeshBuilder class instead.
  24431. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24432. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24436. */
  24437. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24438. var options = {
  24439. segments: segments,
  24440. diameterX: diameter,
  24441. diameterY: diameter,
  24442. diameterZ: diameter,
  24443. sideOrientation: sideOrientation,
  24444. updatable: updatable
  24445. };
  24446. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24447. };
  24448. /**
  24449. * Creates a cylinder or a cone mesh.
  24450. * Please consider using the same method from the MeshBuilder class instead.
  24451. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24452. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24453. * 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.
  24454. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24455. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24459. */
  24460. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24461. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24462. if (scene !== undefined) {
  24463. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24464. updatable = scene;
  24465. }
  24466. scene = subdivisions;
  24467. subdivisions = 1;
  24468. }
  24469. var options = {
  24470. height: height,
  24471. diameterTop: diameterTop,
  24472. diameterBottom: diameterBottom,
  24473. tessellation: tessellation,
  24474. subdivisions: subdivisions,
  24475. sideOrientation: sideOrientation,
  24476. updatable: updatable
  24477. };
  24478. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24479. };
  24480. // Torus (Code from SharpDX.org)
  24481. /**
  24482. * Creates a torus mesh.
  24483. * Please consider using the same method from the MeshBuilder class instead.
  24484. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24485. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24486. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24490. */
  24491. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24492. var options = {
  24493. diameter: diameter,
  24494. thickness: thickness,
  24495. tessellation: tessellation,
  24496. sideOrientation: sideOrientation,
  24497. updatable: updatable
  24498. };
  24499. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24500. };
  24501. /**
  24502. * Creates a torus knot mesh.
  24503. * Please consider using the same method from the MeshBuilder class instead.
  24504. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24505. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24506. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24507. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24511. */
  24512. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24513. var options = {
  24514. radius: radius,
  24515. tube: tube,
  24516. radialSegments: radialSegments,
  24517. tubularSegments: tubularSegments,
  24518. p: p,
  24519. q: q,
  24520. sideOrientation: sideOrientation,
  24521. updatable: updatable
  24522. };
  24523. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24524. };
  24525. /**
  24526. * Creates a line mesh.
  24527. * Please consider using the same method from the MeshBuilder class instead.
  24528. * 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.
  24529. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24530. * The parameter `points` is an array successive Vector3.
  24531. * 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
  24532. * When updating an instance, remember that only point positions can change, not the number of points.
  24533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24534. */
  24535. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24536. if (scene === void 0) { scene = null; }
  24537. if (updatable === void 0) { updatable = false; }
  24538. if (instance === void 0) { instance = null; }
  24539. var options = {
  24540. points: points,
  24541. updatable: updatable,
  24542. instance: instance
  24543. };
  24544. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24545. };
  24546. /**
  24547. * Creates a dashed line mesh.
  24548. * Please consider using the same method from the MeshBuilder class instead.
  24549. * 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.
  24550. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24551. * The parameter `points` is an array successive Vector3.
  24552. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24553. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24554. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24555. * 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
  24556. * When updating an instance, remember that only point positions can change, not the number of points.
  24557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24558. */
  24559. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24560. if (scene === void 0) { scene = null; }
  24561. var options = {
  24562. points: points,
  24563. dashSize: dashSize,
  24564. gapSize: gapSize,
  24565. dashNb: dashNb,
  24566. updatable: updatable,
  24567. instance: instance
  24568. };
  24569. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24570. };
  24571. /**
  24572. * Creates a polygon mesh.
  24573. * Please consider using the same method from the MeshBuilder class instead.
  24574. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24575. * 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.
  24576. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24578. * Remember you can only change the shape positions, not their number when updating a polygon.
  24579. */
  24580. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24581. var options = {
  24582. shape: shape,
  24583. holes: holes,
  24584. updatable: updatable,
  24585. sideOrientation: sideOrientation
  24586. };
  24587. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24588. };
  24589. /**
  24590. * Creates an extruded polygon mesh, with depth in the Y direction.
  24591. * Please consider using the same method from the MeshBuilder class instead.
  24592. */
  24593. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24594. var options = {
  24595. shape: shape,
  24596. holes: holes,
  24597. depth: depth,
  24598. updatable: updatable,
  24599. sideOrientation: sideOrientation
  24600. };
  24601. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24602. };
  24603. /**
  24604. * Creates an extruded shape mesh.
  24605. * 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.
  24606. * Please consider using the same method from the MeshBuilder class instead.
  24607. *
  24608. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24609. * 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
  24610. * extruded along the Z axis.
  24611. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24612. * 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.
  24613. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24614. * 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
  24615. * 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
  24616. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24618. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24620. */
  24621. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24622. if (scene === void 0) { scene = null; }
  24623. var options = {
  24624. shape: shape,
  24625. path: path,
  24626. scale: scale,
  24627. rotation: rotation,
  24628. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24629. sideOrientation: sideOrientation,
  24630. instance: instance,
  24631. updatable: updatable
  24632. };
  24633. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24634. };
  24635. /**
  24636. * Creates an custom extruded shape mesh.
  24637. * 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.
  24638. * Please consider using the same method from the MeshBuilder class instead.
  24639. *
  24640. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24641. * 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
  24642. * extruded along the Z axis.
  24643. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24644. * 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
  24645. * and the distance of this point from the begining of the path :
  24646. * ```javascript
  24647. * var rotationFunction = function(i, distance) {
  24648. * // do things
  24649. * return rotationValue; }
  24650. * ```
  24651. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24652. * 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
  24653. * and the distance of this point from the begining of the path :
  24654. * ```javascript
  24655. * var scaleFunction = function(i, distance) {
  24656. * // do things
  24657. * return scaleValue;}
  24658. * ```
  24659. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24660. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24661. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24662. * 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
  24663. * 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
  24664. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24668. */
  24669. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24670. var options = {
  24671. shape: shape,
  24672. path: path,
  24673. scaleFunction: scaleFunction,
  24674. rotationFunction: rotationFunction,
  24675. ribbonCloseArray: ribbonCloseArray,
  24676. ribbonClosePath: ribbonClosePath,
  24677. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24678. sideOrientation: sideOrientation,
  24679. instance: instance,
  24680. updatable: updatable
  24681. };
  24682. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24683. };
  24684. /**
  24685. * Creates lathe mesh.
  24686. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24687. * Please consider using the same method from the MeshBuilder class instead.
  24688. * 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
  24689. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24690. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24691. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24695. */
  24696. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24697. var options = {
  24698. shape: shape,
  24699. radius: radius,
  24700. tessellation: tessellation,
  24701. sideOrientation: sideOrientation,
  24702. updatable: updatable
  24703. };
  24704. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24705. };
  24706. /**
  24707. * Creates a plane mesh.
  24708. * Please consider using the same method from the MeshBuilder class instead.
  24709. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24710. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24713. */
  24714. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24715. var options = {
  24716. size: size,
  24717. width: size,
  24718. height: size,
  24719. sideOrientation: sideOrientation,
  24720. updatable: updatable
  24721. };
  24722. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24723. };
  24724. /**
  24725. * Creates a ground mesh.
  24726. * Please consider using the same method from the MeshBuilder class instead.
  24727. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24728. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24730. */
  24731. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24732. var options = {
  24733. width: width,
  24734. height: height,
  24735. subdivisions: subdivisions,
  24736. updatable: updatable
  24737. };
  24738. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24739. };
  24740. /**
  24741. * Creates a tiled ground mesh.
  24742. * Please consider using the same method from the MeshBuilder class instead.
  24743. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24744. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24745. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24746. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24747. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24748. * numbers of subdivisions on the ground width and height of each tile.
  24749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24750. */
  24751. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24752. var options = {
  24753. xmin: xmin,
  24754. zmin: zmin,
  24755. xmax: xmax,
  24756. zmax: zmax,
  24757. subdivisions: subdivisions,
  24758. precision: precision,
  24759. updatable: updatable
  24760. };
  24761. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24762. };
  24763. /**
  24764. * Creates a ground mesh from a height map.
  24765. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24766. * Please consider using the same method from the MeshBuilder class instead.
  24767. * The parameter `url` sets the URL of the height map image resource.
  24768. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24769. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24770. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24771. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24772. * 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).
  24773. * This function is passed the newly built mesh :
  24774. * ```javascript
  24775. * function(mesh) { // do things
  24776. * return; }
  24777. * ```
  24778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24779. */
  24780. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24781. var options = {
  24782. width: width,
  24783. height: height,
  24784. subdivisions: subdivisions,
  24785. minHeight: minHeight,
  24786. maxHeight: maxHeight,
  24787. updatable: updatable,
  24788. onReady: onReady
  24789. };
  24790. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24791. };
  24792. /**
  24793. * Creates a tube mesh.
  24794. * 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.
  24795. * Please consider using the same method from the MeshBuilder class instead.
  24796. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24797. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24798. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24799. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24800. * 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.
  24801. * It must return a radius value (positive float) :
  24802. * ```javascript
  24803. * var radiusFunction = function(i, distance) {
  24804. * // do things
  24805. * return radius; }
  24806. * ```
  24807. * 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
  24808. * 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
  24809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24812. */
  24813. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24814. var options = {
  24815. path: path,
  24816. radius: radius,
  24817. tessellation: tessellation,
  24818. radiusFunction: radiusFunction,
  24819. arc: 1,
  24820. cap: cap,
  24821. updatable: updatable,
  24822. sideOrientation: sideOrientation,
  24823. instance: instance
  24824. };
  24825. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24826. };
  24827. /**
  24828. * Creates a polyhedron mesh.
  24829. * Please consider using the same method from the MeshBuilder class instead.
  24830. * 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
  24831. * to choose the wanted type.
  24832. * The parameter `size` (positive float, default 1) sets the polygon size.
  24833. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24834. * 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`.
  24835. * 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
  24836. * 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)`).
  24837. * 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
  24838. * 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.
  24839. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24840. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24842. */
  24843. Mesh.CreatePolyhedron = function (name, options, scene) {
  24844. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24845. };
  24846. /**
  24847. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24848. * Please consider using the same method from the MeshBuilder class instead.
  24849. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24850. * 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`).
  24851. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24852. * 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.
  24853. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24854. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24855. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24856. */
  24857. Mesh.CreateIcoSphere = function (name, options, scene) {
  24858. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24859. };
  24860. /**
  24861. * Creates a decal mesh.
  24862. * Please consider using the same method from the MeshBuilder class instead.
  24863. * 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.
  24864. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24865. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24866. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24867. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24868. */
  24869. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24870. var options = {
  24871. position: position,
  24872. normal: normal,
  24873. size: size,
  24874. angle: angle
  24875. };
  24876. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24877. };
  24878. // Skeletons
  24879. /**
  24880. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24881. */
  24882. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24883. if (!this._sourcePositions) {
  24884. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24885. if (!source) {
  24886. return this._sourcePositions;
  24887. }
  24888. this._sourcePositions = new Float32Array(source);
  24889. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  24890. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24891. }
  24892. }
  24893. return this._sourcePositions;
  24894. };
  24895. /**
  24896. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24897. */
  24898. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24899. if (!this._sourceNormals) {
  24900. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24901. if (!source) {
  24902. return this._sourceNormals;
  24903. }
  24904. this._sourceNormals = new Float32Array(source);
  24905. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  24906. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24907. }
  24908. }
  24909. return this._sourceNormals;
  24910. };
  24911. /**
  24912. * Updates the vertex buffer by applying transformation from the bones.
  24913. * Returns the Mesh.
  24914. *
  24915. * @param {skeleton} skeleton to apply
  24916. */
  24917. Mesh.prototype.applySkeleton = function (skeleton) {
  24918. if (!this.geometry) {
  24919. return this;
  24920. }
  24921. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24922. return this;
  24923. }
  24924. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24926. return this;
  24927. }
  24928. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24929. return this;
  24930. }
  24931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24932. return this;
  24933. }
  24934. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24935. return this;
  24936. }
  24937. if (!this._sourcePositions) {
  24938. var submeshes = this.subMeshes.slice();
  24939. this.setPositionsForCPUSkinning();
  24940. this.subMeshes = submeshes;
  24941. }
  24942. if (!this._sourceNormals) {
  24943. this.setNormalsForCPUSkinning();
  24944. }
  24945. // positionsData checks for not being Float32Array will only pass at most once
  24946. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24947. if (!positionsData) {
  24948. return this;
  24949. }
  24950. if (!(positionsData instanceof Float32Array)) {
  24951. positionsData = new Float32Array(positionsData);
  24952. }
  24953. // normalsData checks for not being Float32Array will only pass at most once
  24954. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24955. if (!normalsData) {
  24956. return this;
  24957. }
  24958. if (!(normalsData instanceof Float32Array)) {
  24959. normalsData = new Float32Array(normalsData);
  24960. }
  24961. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24962. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24963. if (!matricesWeightsData || !matricesIndicesData) {
  24964. return this;
  24965. }
  24966. var needExtras = this.numBoneInfluencers > 4;
  24967. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24968. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24969. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  24970. return this;
  24971. }
  24972. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24973. var tempVector3 = BABYLON.Vector3.Zero();
  24974. var finalMatrix = new BABYLON.Matrix();
  24975. var tempMatrix = new BABYLON.Matrix();
  24976. var matWeightIdx = 0;
  24977. var inf;
  24978. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24979. var weight;
  24980. for (inf = 0; inf < 4; inf++) {
  24981. weight = matricesWeightsData[matWeightIdx + inf];
  24982. if (weight > 0) {
  24983. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24984. finalMatrix.addToSelf(tempMatrix);
  24985. }
  24986. else
  24987. break;
  24988. }
  24989. if (needExtras) {
  24990. for (inf = 0; inf < 4; inf++) {
  24991. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24992. if (weight > 0) {
  24993. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24994. finalMatrix.addToSelf(tempMatrix);
  24995. }
  24996. else
  24997. break;
  24998. }
  24999. }
  25000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25001. tempVector3.toArray(positionsData, index);
  25002. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25003. tempVector3.toArray(normalsData, index);
  25004. finalMatrix.reset();
  25005. }
  25006. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25007. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25008. return this;
  25009. };
  25010. // Tools
  25011. /**
  25012. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25013. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25014. */
  25015. Mesh.MinMax = function (meshes) {
  25016. var minVector = null;
  25017. var maxVector = null;
  25018. meshes.forEach(function (mesh, index, array) {
  25019. var boundingInfo = mesh.getBoundingInfo();
  25020. if (!boundingInfo) {
  25021. return;
  25022. }
  25023. var boundingBox = boundingInfo.boundingBox;
  25024. if (!minVector || !maxVector) {
  25025. minVector = boundingBox.minimumWorld;
  25026. maxVector = boundingBox.maximumWorld;
  25027. }
  25028. else {
  25029. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25030. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25031. }
  25032. });
  25033. if (!minVector || !maxVector) {
  25034. return {
  25035. min: BABYLON.Vector3.Zero(),
  25036. max: BABYLON.Vector3.Zero()
  25037. };
  25038. }
  25039. return {
  25040. min: minVector,
  25041. max: maxVector
  25042. };
  25043. };
  25044. /**
  25045. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25046. */
  25047. Mesh.Center = function (meshesOrMinMaxVector) {
  25048. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25049. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25050. };
  25051. /**
  25052. * Merge the array of meshes into a single mesh for performance reasons.
  25053. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25054. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25055. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25056. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25057. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25058. */
  25059. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25060. if (disposeSource === void 0) { disposeSource = true; }
  25061. var index;
  25062. if (!allow32BitsIndices) {
  25063. var totalVertices = 0;
  25064. // Counting vertices
  25065. for (index = 0; index < meshes.length; index++) {
  25066. if (meshes[index]) {
  25067. totalVertices += meshes[index].getTotalVertices();
  25068. if (totalVertices > 65536) {
  25069. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25070. return null;
  25071. }
  25072. }
  25073. }
  25074. }
  25075. // Merge
  25076. var vertexData = null;
  25077. var otherVertexData;
  25078. var indiceArray = new Array();
  25079. var source = null;
  25080. for (index = 0; index < meshes.length; index++) {
  25081. if (meshes[index]) {
  25082. meshes[index].computeWorldMatrix(true);
  25083. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25084. otherVertexData.transform(meshes[index].getWorldMatrix());
  25085. if (vertexData) {
  25086. vertexData.merge(otherVertexData);
  25087. }
  25088. else {
  25089. vertexData = otherVertexData;
  25090. source = meshes[index];
  25091. }
  25092. if (subdivideWithSubMeshes) {
  25093. indiceArray.push(meshes[index].getTotalIndices());
  25094. }
  25095. }
  25096. }
  25097. source = source;
  25098. if (!meshSubclass) {
  25099. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25100. }
  25101. vertexData.applyToMesh(meshSubclass);
  25102. // Setting properties
  25103. meshSubclass.material = source.material;
  25104. meshSubclass.checkCollisions = source.checkCollisions;
  25105. // Cleaning
  25106. if (disposeSource) {
  25107. for (index = 0; index < meshes.length; index++) {
  25108. if (meshes[index]) {
  25109. meshes[index].dispose();
  25110. }
  25111. }
  25112. }
  25113. // Subdivide
  25114. if (subdivideWithSubMeshes) {
  25115. //-- Suppresions du submesh global
  25116. meshSubclass.releaseSubMeshes();
  25117. index = 0;
  25118. var offset = 0;
  25119. //-- aplique la subdivision en fonction du tableau d'indices
  25120. while (index < indiceArray.length) {
  25121. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25122. offset += indiceArray[index];
  25123. index++;
  25124. }
  25125. }
  25126. return meshSubclass;
  25127. };
  25128. // Consts
  25129. Mesh._FRONTSIDE = 0;
  25130. Mesh._BACKSIDE = 1;
  25131. Mesh._DOUBLESIDE = 2;
  25132. Mesh._DEFAULTSIDE = 0;
  25133. Mesh._NO_CAP = 0;
  25134. Mesh._CAP_START = 1;
  25135. Mesh._CAP_END = 2;
  25136. Mesh._CAP_ALL = 3;
  25137. return Mesh;
  25138. }(BABYLON.AbstractMesh));
  25139. BABYLON.Mesh = Mesh;
  25140. })(BABYLON || (BABYLON = {}));
  25141. //# sourceMappingURL=babylon.mesh.js.map
  25142. var BABYLON;
  25143. (function (BABYLON) {
  25144. var BaseSubMesh = /** @class */ (function () {
  25145. function BaseSubMesh() {
  25146. }
  25147. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25148. get: function () {
  25149. return this._materialEffect;
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25155. if (defines === void 0) { defines = null; }
  25156. if (this._materialEffect === effect) {
  25157. if (!effect) {
  25158. this._materialDefines = null;
  25159. }
  25160. return;
  25161. }
  25162. this._materialDefines = defines;
  25163. this._materialEffect = effect;
  25164. };
  25165. return BaseSubMesh;
  25166. }());
  25167. BABYLON.BaseSubMesh = BaseSubMesh;
  25168. var SubMesh = /** @class */ (function (_super) {
  25169. __extends(SubMesh, _super);
  25170. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25171. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25172. var _this = _super.call(this) || this;
  25173. _this.materialIndex = materialIndex;
  25174. _this.verticesStart = verticesStart;
  25175. _this.verticesCount = verticesCount;
  25176. _this.indexStart = indexStart;
  25177. _this.indexCount = indexCount;
  25178. _this._renderId = 0;
  25179. _this._mesh = mesh;
  25180. _this._renderingMesh = renderingMesh || mesh;
  25181. mesh.subMeshes.push(_this);
  25182. _this._trianglePlanes = [];
  25183. _this._id = mesh.subMeshes.length - 1;
  25184. if (createBoundingBox) {
  25185. _this.refreshBoundingInfo();
  25186. mesh.computeWorldMatrix(true);
  25187. }
  25188. return _this;
  25189. }
  25190. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25191. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25192. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25193. };
  25194. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25195. get: function () {
  25196. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25197. },
  25198. enumerable: true,
  25199. configurable: true
  25200. });
  25201. /**
  25202. * Returns the submesh BoudingInfo object.
  25203. */
  25204. SubMesh.prototype.getBoundingInfo = function () {
  25205. if (this.IsGlobal) {
  25206. return this._mesh.getBoundingInfo();
  25207. }
  25208. return this._boundingInfo;
  25209. };
  25210. /**
  25211. * Sets the submesh BoundingInfo.
  25212. * Return the SubMesh.
  25213. */
  25214. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25215. this._boundingInfo = boundingInfo;
  25216. return this;
  25217. };
  25218. /**
  25219. * Returns the mesh of the current submesh.
  25220. */
  25221. SubMesh.prototype.getMesh = function () {
  25222. return this._mesh;
  25223. };
  25224. /**
  25225. * Returns the rendering mesh of the submesh.
  25226. */
  25227. SubMesh.prototype.getRenderingMesh = function () {
  25228. return this._renderingMesh;
  25229. };
  25230. /**
  25231. * Returns the submesh material.
  25232. */
  25233. SubMesh.prototype.getMaterial = function () {
  25234. var rootMaterial = this._renderingMesh.material;
  25235. if (rootMaterial && rootMaterial.getSubMaterial) {
  25236. var multiMaterial = rootMaterial;
  25237. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25238. if (this._currentMaterial !== effectiveMaterial) {
  25239. this._currentMaterial = effectiveMaterial;
  25240. this._materialDefines = null;
  25241. }
  25242. return effectiveMaterial;
  25243. }
  25244. if (!rootMaterial) {
  25245. return this._mesh.getScene().defaultMaterial;
  25246. }
  25247. return rootMaterial;
  25248. };
  25249. // Methods
  25250. /**
  25251. * Sets a new updated BoundingInfo object to the submesh.
  25252. * Returns the SubMesh.
  25253. */
  25254. SubMesh.prototype.refreshBoundingInfo = function () {
  25255. this._lastColliderWorldVertices = null;
  25256. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25257. return this;
  25258. }
  25259. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25260. if (!data) {
  25261. this._boundingInfo = this._mesh._boundingInfo;
  25262. return this;
  25263. }
  25264. var indices = this._renderingMesh.getIndices();
  25265. var extend;
  25266. //is this the only submesh?
  25267. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25268. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25269. if (!boundingInfo) {
  25270. return this;
  25271. }
  25272. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25273. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25274. }
  25275. else {
  25276. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25277. }
  25278. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25279. return this;
  25280. };
  25281. SubMesh.prototype._checkCollision = function (collider) {
  25282. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25283. if (!boundingInfo) {
  25284. return false;
  25285. }
  25286. return boundingInfo._checkCollision(collider);
  25287. };
  25288. /**
  25289. * Updates the submesh BoundingInfo.
  25290. * Returns the Submesh.
  25291. */
  25292. SubMesh.prototype.updateBoundingInfo = function (world) {
  25293. var boundingInfo = this.getBoundingInfo();
  25294. if (!boundingInfo) {
  25295. this.refreshBoundingInfo();
  25296. }
  25297. boundingInfo.update(world);
  25298. return this;
  25299. };
  25300. /**
  25301. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25302. * Boolean returned.
  25303. */
  25304. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25305. var boundingInfo = this.getBoundingInfo();
  25306. if (!boundingInfo) {
  25307. return false;
  25308. }
  25309. return boundingInfo.isInFrustum(frustumPlanes);
  25310. };
  25311. /**
  25312. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25313. * Boolean returned.
  25314. */
  25315. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25316. var boundingInfo = this.getBoundingInfo();
  25317. if (!boundingInfo) {
  25318. return false;
  25319. }
  25320. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25321. };
  25322. /**
  25323. * Renders the submesh.
  25324. * Returns it.
  25325. */
  25326. SubMesh.prototype.render = function (enableAlphaMode) {
  25327. this._renderingMesh.render(this, enableAlphaMode);
  25328. return this;
  25329. };
  25330. /**
  25331. * Returns a new Index Buffer.
  25332. * Type returned : WebGLBuffer.
  25333. */
  25334. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25335. if (!this._linesIndexBuffer) {
  25336. var linesIndices = [];
  25337. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25338. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25339. }
  25340. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25341. this.linesIndexCount = linesIndices.length;
  25342. }
  25343. return this._linesIndexBuffer;
  25344. };
  25345. /**
  25346. * True is the passed Ray intersects the submesh bounding box.
  25347. * Boolean returned.
  25348. */
  25349. SubMesh.prototype.canIntersects = function (ray) {
  25350. var boundingInfo = this.getBoundingInfo();
  25351. if (!boundingInfo) {
  25352. return false;
  25353. }
  25354. return ray.intersectsBox(boundingInfo.boundingBox);
  25355. };
  25356. /**
  25357. * Returns an object IntersectionInfo.
  25358. */
  25359. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25360. var intersectInfo = null;
  25361. // LineMesh first as it's also a Mesh...
  25362. if (this._mesh instanceof BABYLON.LinesMesh) {
  25363. var lineMesh = this._mesh;
  25364. // Line test
  25365. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25366. var p0 = positions[indices[index]];
  25367. var p1 = positions[indices[index + 1]];
  25368. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25369. if (length < 0) {
  25370. continue;
  25371. }
  25372. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25373. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25374. if (fastCheck) {
  25375. break;
  25376. }
  25377. }
  25378. }
  25379. }
  25380. else {
  25381. // Triangles test
  25382. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25383. var p0 = positions[indices[index]];
  25384. var p1 = positions[indices[index + 1]];
  25385. var p2 = positions[indices[index + 2]];
  25386. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25387. if (currentIntersectInfo) {
  25388. if (currentIntersectInfo.distance < 0) {
  25389. continue;
  25390. }
  25391. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25392. intersectInfo = currentIntersectInfo;
  25393. intersectInfo.faceId = index / 3;
  25394. if (fastCheck) {
  25395. break;
  25396. }
  25397. }
  25398. }
  25399. }
  25400. }
  25401. return intersectInfo;
  25402. };
  25403. SubMesh.prototype._rebuild = function () {
  25404. if (this._linesIndexBuffer) {
  25405. this._linesIndexBuffer = null;
  25406. }
  25407. };
  25408. // Clone
  25409. /**
  25410. * Creates a new Submesh from the passed Mesh.
  25411. */
  25412. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25413. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25414. if (!this.IsGlobal) {
  25415. var boundingInfo = this.getBoundingInfo();
  25416. if (!boundingInfo) {
  25417. return result;
  25418. }
  25419. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25420. }
  25421. return result;
  25422. };
  25423. // Dispose
  25424. /**
  25425. * Disposes the Submesh.
  25426. * Returns nothing.
  25427. */
  25428. SubMesh.prototype.dispose = function () {
  25429. if (this._linesIndexBuffer) {
  25430. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25431. this._linesIndexBuffer = null;
  25432. }
  25433. // Remove from mesh
  25434. var index = this._mesh.subMeshes.indexOf(this);
  25435. this._mesh.subMeshes.splice(index, 1);
  25436. };
  25437. // Statics
  25438. /**
  25439. * Creates a new Submesh from the passed parameters :
  25440. * - materialIndex (integer) : the index of the main mesh material.
  25441. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25442. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25443. * - mesh (Mesh) : the main mesh to create the submesh from.
  25444. * - renderingMesh (optional Mesh) : rendering mesh.
  25445. */
  25446. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25447. var minVertexIndex = Number.MAX_VALUE;
  25448. var maxVertexIndex = -Number.MAX_VALUE;
  25449. renderingMesh = (renderingMesh || mesh);
  25450. var indices = renderingMesh.getIndices();
  25451. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25452. var vertexIndex = indices[index];
  25453. if (vertexIndex < minVertexIndex)
  25454. minVertexIndex = vertexIndex;
  25455. if (vertexIndex > maxVertexIndex)
  25456. maxVertexIndex = vertexIndex;
  25457. }
  25458. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25459. };
  25460. return SubMesh;
  25461. }(BaseSubMesh));
  25462. BABYLON.SubMesh = SubMesh;
  25463. })(BABYLON || (BABYLON = {}));
  25464. //# sourceMappingURL=babylon.subMesh.js.map
  25465. var BABYLON;
  25466. (function (BABYLON) {
  25467. var EffectFallbacks = /** @class */ (function () {
  25468. function EffectFallbacks() {
  25469. this._defines = {};
  25470. this._currentRank = 32;
  25471. this._maxRank = -1;
  25472. }
  25473. EffectFallbacks.prototype.unBindMesh = function () {
  25474. this._mesh = null;
  25475. };
  25476. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25477. if (!this._defines[rank]) {
  25478. if (rank < this._currentRank) {
  25479. this._currentRank = rank;
  25480. }
  25481. if (rank > this._maxRank) {
  25482. this._maxRank = rank;
  25483. }
  25484. this._defines[rank] = new Array();
  25485. }
  25486. this._defines[rank].push(define);
  25487. };
  25488. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25489. this._meshRank = rank;
  25490. this._mesh = mesh;
  25491. if (rank < this._currentRank) {
  25492. this._currentRank = rank;
  25493. }
  25494. if (rank > this._maxRank) {
  25495. this._maxRank = rank;
  25496. }
  25497. };
  25498. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25499. get: function () {
  25500. return this._currentRank <= this._maxRank;
  25501. },
  25502. enumerable: true,
  25503. configurable: true
  25504. });
  25505. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25506. // First we try to switch to CPU skinning
  25507. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25508. this._mesh.computeBonesUsingShaders = false;
  25509. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25510. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25511. var scene = this._mesh.getScene();
  25512. for (var index = 0; index < scene.meshes.length; index++) {
  25513. var otherMesh = scene.meshes[index];
  25514. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25515. otherMesh.computeBonesUsingShaders = false;
  25516. }
  25517. }
  25518. }
  25519. else {
  25520. var currentFallbacks = this._defines[this._currentRank];
  25521. if (currentFallbacks) {
  25522. for (var index = 0; index < currentFallbacks.length; index++) {
  25523. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25524. }
  25525. }
  25526. this._currentRank++;
  25527. }
  25528. return currentDefines;
  25529. };
  25530. return EffectFallbacks;
  25531. }());
  25532. BABYLON.EffectFallbacks = EffectFallbacks;
  25533. var EffectCreationOptions = /** @class */ (function () {
  25534. function EffectCreationOptions() {
  25535. }
  25536. return EffectCreationOptions;
  25537. }());
  25538. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25539. var Effect = /** @class */ (function () {
  25540. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25541. if (samplers === void 0) { samplers = null; }
  25542. if (defines === void 0) { defines = null; }
  25543. if (fallbacks === void 0) { fallbacks = null; }
  25544. if (onCompiled === void 0) { onCompiled = null; }
  25545. if (onError === void 0) { onError = null; }
  25546. var _this = this;
  25547. this.uniqueId = 0;
  25548. this.onCompileObservable = new BABYLON.Observable();
  25549. this.onErrorObservable = new BABYLON.Observable();
  25550. this.onBindObservable = new BABYLON.Observable();
  25551. this._uniformBuffersNames = {};
  25552. this._isReady = false;
  25553. this._compilationError = "";
  25554. this.name = baseName;
  25555. if (attributesNamesOrOptions.attributes) {
  25556. var options = attributesNamesOrOptions;
  25557. this._engine = uniformsNamesOrEngine;
  25558. this._attributesNames = options.attributes;
  25559. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25560. this._samplers = options.samplers;
  25561. this.defines = options.defines;
  25562. this.onError = options.onError;
  25563. this.onCompiled = options.onCompiled;
  25564. this._fallbacks = options.fallbacks;
  25565. this._indexParameters = options.indexParameters;
  25566. if (options.uniformBuffersNames) {
  25567. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25568. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25569. }
  25570. }
  25571. }
  25572. else {
  25573. this._engine = engine;
  25574. this.defines = defines;
  25575. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25576. this._samplers = samplers;
  25577. this._attributesNames = attributesNamesOrOptions;
  25578. this.onError = onError;
  25579. this.onCompiled = onCompiled;
  25580. this._indexParameters = indexParameters;
  25581. this._fallbacks = fallbacks;
  25582. }
  25583. this.uniqueId = Effect._uniqueIdSeed++;
  25584. var vertexSource;
  25585. var fragmentSource;
  25586. if (baseName.vertexElement) {
  25587. vertexSource = document.getElementById(baseName.vertexElement);
  25588. if (!vertexSource) {
  25589. vertexSource = baseName.vertexElement;
  25590. }
  25591. }
  25592. else {
  25593. vertexSource = baseName.vertex || baseName;
  25594. }
  25595. if (baseName.fragmentElement) {
  25596. fragmentSource = document.getElementById(baseName.fragmentElement);
  25597. if (!fragmentSource) {
  25598. fragmentSource = baseName.fragmentElement;
  25599. }
  25600. }
  25601. else {
  25602. fragmentSource = baseName.fragment || baseName;
  25603. }
  25604. this._loadVertexShader(vertexSource, function (vertexCode) {
  25605. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25606. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25607. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25608. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25609. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25610. if (baseName) {
  25611. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25612. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25613. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25614. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25615. }
  25616. else {
  25617. _this._vertexSourceCode = migratedVertexCode;
  25618. _this._fragmentSourceCode = migratedFragmentCode;
  25619. }
  25620. _this._prepareEffect();
  25621. });
  25622. });
  25623. });
  25624. });
  25625. });
  25626. });
  25627. }
  25628. Object.defineProperty(Effect.prototype, "key", {
  25629. get: function () {
  25630. return this._key;
  25631. },
  25632. enumerable: true,
  25633. configurable: true
  25634. });
  25635. // Properties
  25636. Effect.prototype.isReady = function () {
  25637. return this._isReady;
  25638. };
  25639. Effect.prototype.getEngine = function () {
  25640. return this._engine;
  25641. };
  25642. Effect.prototype.getProgram = function () {
  25643. return this._program;
  25644. };
  25645. Effect.prototype.getAttributesNames = function () {
  25646. return this._attributesNames;
  25647. };
  25648. Effect.prototype.getAttributeLocation = function (index) {
  25649. return this._attributes[index];
  25650. };
  25651. Effect.prototype.getAttributeLocationByName = function (name) {
  25652. var index = this._attributesNames.indexOf(name);
  25653. return this._attributes[index];
  25654. };
  25655. Effect.prototype.getAttributesCount = function () {
  25656. return this._attributes.length;
  25657. };
  25658. Effect.prototype.getUniformIndex = function (uniformName) {
  25659. return this._uniformsNames.indexOf(uniformName);
  25660. };
  25661. Effect.prototype.getUniform = function (uniformName) {
  25662. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25663. };
  25664. Effect.prototype.getSamplers = function () {
  25665. return this._samplers;
  25666. };
  25667. Effect.prototype.getCompilationError = function () {
  25668. return this._compilationError;
  25669. };
  25670. // Methods
  25671. Effect.prototype.executeWhenCompiled = function (func) {
  25672. if (this.isReady()) {
  25673. func(this);
  25674. return;
  25675. }
  25676. this.onCompileObservable.add(function (effect) {
  25677. func(effect);
  25678. });
  25679. };
  25680. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25681. if (BABYLON.Tools.IsWindowObjectExist()) {
  25682. // DOM element ?
  25683. if (vertex instanceof HTMLElement) {
  25684. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25685. callback(vertexCode);
  25686. return;
  25687. }
  25688. }
  25689. // Base64 encoded ?
  25690. if (vertex.substr(0, 7) === "base64:") {
  25691. var vertexBinary = window.atob(vertex.substr(7));
  25692. callback(vertexBinary);
  25693. return;
  25694. }
  25695. // Is in local store ?
  25696. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25697. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25698. return;
  25699. }
  25700. var vertexShaderUrl;
  25701. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25702. vertexShaderUrl = vertex;
  25703. }
  25704. else {
  25705. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25706. }
  25707. // Vertex shader
  25708. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25709. };
  25710. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25711. if (BABYLON.Tools.IsWindowObjectExist()) {
  25712. // DOM element ?
  25713. if (fragment instanceof HTMLElement) {
  25714. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25715. callback(fragmentCode);
  25716. return;
  25717. }
  25718. }
  25719. // Base64 encoded ?
  25720. if (fragment.substr(0, 7) === "base64:") {
  25721. var fragmentBinary = window.atob(fragment.substr(7));
  25722. callback(fragmentBinary);
  25723. return;
  25724. }
  25725. // Is in local store ?
  25726. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25727. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25728. return;
  25729. }
  25730. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25731. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25732. return;
  25733. }
  25734. var fragmentShaderUrl;
  25735. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25736. fragmentShaderUrl = fragment;
  25737. }
  25738. else {
  25739. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25740. }
  25741. // Fragment shader
  25742. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25743. };
  25744. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25745. // Rebuild shaders source code
  25746. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25747. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25748. vertexCode = prefix + vertexCode;
  25749. fragmentCode = prefix + fragmentCode;
  25750. // Number lines of shaders source code
  25751. var i = 2;
  25752. var regex = /\n/gm;
  25753. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25754. i = 2;
  25755. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25756. // Dump shaders name and formatted source code
  25757. if (this.name.vertexElement) {
  25758. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25759. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25760. }
  25761. else if (this.name.vertex) {
  25762. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25763. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25764. }
  25765. else {
  25766. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25767. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25768. }
  25769. };
  25770. ;
  25771. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25772. var preparedSourceCode = this._processPrecision(sourceCode);
  25773. if (this._engine.webGLVersion == 1) {
  25774. callback(preparedSourceCode);
  25775. return;
  25776. }
  25777. // Already converted
  25778. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25779. callback(preparedSourceCode.replace("#version 300 es", ""));
  25780. return;
  25781. }
  25782. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25783. // Remove extensions
  25784. // #extension GL_OES_standard_derivatives : enable
  25785. // #extension GL_EXT_shader_texture_lod : enable
  25786. // #extension GL_EXT_frag_depth : enable
  25787. // #extension GL_EXT_draw_buffers : require
  25788. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25789. var result = preparedSourceCode.replace(regex, "");
  25790. // Migrate to GLSL v300
  25791. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25792. result = result.replace(/attribute[ \t]/g, "in ");
  25793. result = result.replace(/[ \t]attribute/g, " in");
  25794. if (isFragment) {
  25795. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25796. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25797. result = result.replace(/texture2D\s*\(/g, "texture(");
  25798. result = result.replace(/textureCube\s*\(/g, "texture(");
  25799. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25800. result = result.replace(/gl_FragColor/g, "glFragColor");
  25801. result = result.replace(/gl_FragData/g, "glFragData");
  25802. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25803. }
  25804. callback(result);
  25805. };
  25806. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25807. var _this = this;
  25808. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25809. var match = regex.exec(sourceCode);
  25810. var returnValue = new String(sourceCode);
  25811. while (match != null) {
  25812. var includeFile = match[1];
  25813. // Uniform declaration
  25814. if (includeFile.indexOf("__decl__") !== -1) {
  25815. includeFile = includeFile.replace(/__decl__/, "");
  25816. if (this._engine.supportsUniformBuffers) {
  25817. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25818. includeFile = includeFile.replace(/Fragment/, "Ubo");
  25819. }
  25820. includeFile = includeFile + "Declaration";
  25821. }
  25822. if (Effect.IncludesShadersStore[includeFile]) {
  25823. // Substitution
  25824. var includeContent = Effect.IncludesShadersStore[includeFile];
  25825. if (match[2]) {
  25826. var splits = match[3].split(",");
  25827. for (var index = 0; index < splits.length; index += 2) {
  25828. var source = new RegExp(splits[index], "g");
  25829. var dest = splits[index + 1];
  25830. includeContent = includeContent.replace(source, dest);
  25831. }
  25832. }
  25833. if (match[4]) {
  25834. var indexString = match[5];
  25835. if (indexString.indexOf("..") !== -1) {
  25836. var indexSplits = indexString.split("..");
  25837. var minIndex = parseInt(indexSplits[0]);
  25838. var maxIndex = parseInt(indexSplits[1]);
  25839. var sourceIncludeContent = includeContent.slice(0);
  25840. includeContent = "";
  25841. if (isNaN(maxIndex)) {
  25842. maxIndex = this._indexParameters[indexSplits[1]];
  25843. }
  25844. for (var i = minIndex; i < maxIndex; i++) {
  25845. if (!this._engine.supportsUniformBuffers) {
  25846. // Ubo replacement
  25847. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25848. return p1 + "{X}";
  25849. });
  25850. }
  25851. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  25852. }
  25853. }
  25854. else {
  25855. if (!this._engine.supportsUniformBuffers) {
  25856. // Ubo replacement
  25857. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  25858. return p1 + "{X}";
  25859. });
  25860. }
  25861. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25862. }
  25863. }
  25864. // Replace
  25865. returnValue = returnValue.replace(match[0], includeContent);
  25866. }
  25867. else {
  25868. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25869. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25870. Effect.IncludesShadersStore[includeFile] = fileContent;
  25871. _this._processIncludes(returnValue, callback);
  25872. });
  25873. return;
  25874. }
  25875. match = regex.exec(sourceCode);
  25876. }
  25877. callback(returnValue);
  25878. };
  25879. Effect.prototype._processPrecision = function (source) {
  25880. if (source.indexOf("precision highp float") === -1) {
  25881. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25882. source = "precision mediump float;\n" + source;
  25883. }
  25884. else {
  25885. source = "precision highp float;\n" + source;
  25886. }
  25887. }
  25888. else {
  25889. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25890. source = source.replace("precision highp float", "precision mediump float");
  25891. }
  25892. }
  25893. return source;
  25894. };
  25895. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  25896. var _this = this;
  25897. this._isReady = false;
  25898. this._vertexSourceCodeOverride = vertexSourceCode;
  25899. this._fragmentSourceCodeOverride = fragmentSourceCode;
  25900. this.onError = function (effect, error) {
  25901. if (onError) {
  25902. onError(error);
  25903. }
  25904. };
  25905. this.onCompiled = function () {
  25906. var scenes = _this.getEngine().scenes;
  25907. for (var i = 0; i < scenes.length; i++) {
  25908. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25909. }
  25910. if (onCompiled) {
  25911. onCompiled(_this._program);
  25912. }
  25913. };
  25914. this._fallbacks = null;
  25915. this._prepareEffect();
  25916. };
  25917. Effect.prototype._prepareEffect = function () {
  25918. var attributesNames = this._attributesNames;
  25919. var defines = this.defines;
  25920. var fallbacks = this._fallbacks;
  25921. this._valueCache = {};
  25922. var previousProgram = this._program;
  25923. try {
  25924. var engine = this._engine;
  25925. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  25926. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride);
  25927. }
  25928. else {
  25929. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25930. }
  25931. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  25932. if (engine.webGLVersion > 1) {
  25933. for (var name in this._uniformBuffersNames) {
  25934. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  25935. }
  25936. }
  25937. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25938. this._attributes = engine.getAttributes(this._program, attributesNames);
  25939. var index;
  25940. for (index = 0; index < this._samplers.length; index++) {
  25941. var sampler = this.getUniform(this._samplers[index]);
  25942. if (sampler == null) {
  25943. this._samplers.splice(index, 1);
  25944. index--;
  25945. }
  25946. }
  25947. engine.bindSamplers(this);
  25948. this._compilationError = "";
  25949. this._isReady = true;
  25950. if (this.onCompiled) {
  25951. this.onCompiled(this);
  25952. }
  25953. this.onCompileObservable.notifyObservers(this);
  25954. this.onCompileObservable.clear();
  25955. // Unbind mesh reference in fallbacks
  25956. if (this._fallbacks) {
  25957. this._fallbacks.unBindMesh();
  25958. }
  25959. if (previousProgram) {
  25960. this.getEngine()._deleteProgram(previousProgram);
  25961. }
  25962. }
  25963. catch (e) {
  25964. this._compilationError = e.message;
  25965. // Let's go through fallbacks then
  25966. BABYLON.Tools.Error("Unable to compile effect:");
  25967. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25968. return " " + uniform;
  25969. }));
  25970. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25971. return " " + attribute;
  25972. }));
  25973. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25974. BABYLON.Tools.Error("Error: " + this._compilationError);
  25975. if (previousProgram) {
  25976. this._program = previousProgram;
  25977. this._isReady = true;
  25978. if (this.onError) {
  25979. this.onError(this, this._compilationError);
  25980. }
  25981. this.onErrorObservable.notifyObservers(this);
  25982. }
  25983. if (fallbacks && fallbacks.isMoreFallbacks) {
  25984. BABYLON.Tools.Error("Trying next fallback.");
  25985. this.defines = fallbacks.reduce(this.defines);
  25986. this._prepareEffect();
  25987. }
  25988. else {
  25989. if (this.onError) {
  25990. this.onError(this, this._compilationError);
  25991. }
  25992. this.onErrorObservable.notifyObservers(this);
  25993. this.onErrorObservable.clear();
  25994. // Unbind mesh reference in fallbacks
  25995. if (this._fallbacks) {
  25996. this._fallbacks.unBindMesh();
  25997. }
  25998. }
  25999. }
  26000. };
  26001. Object.defineProperty(Effect.prototype, "isSupported", {
  26002. get: function () {
  26003. return this._compilationError === "";
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. Effect.prototype._bindTexture = function (channel, texture) {
  26009. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26010. };
  26011. Effect.prototype.setTexture = function (channel, texture) {
  26012. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26013. };
  26014. Effect.prototype.setTextureArray = function (channel, textures) {
  26015. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26016. var initialPos = this._samplers.indexOf(channel);
  26017. for (var index = 1; index < textures.length; index++) {
  26018. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26019. }
  26020. }
  26021. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26022. };
  26023. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26024. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26025. };
  26026. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26027. var cache = this._valueCache[uniformName];
  26028. var flag = matrix.updateFlag;
  26029. if (cache !== undefined && cache === flag) {
  26030. return false;
  26031. }
  26032. this._valueCache[uniformName] = flag;
  26033. return true;
  26034. };
  26035. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26036. var cache = this._valueCache[uniformName];
  26037. if (!cache) {
  26038. cache = [x, y];
  26039. this._valueCache[uniformName] = cache;
  26040. return true;
  26041. }
  26042. var changed = false;
  26043. if (cache[0] !== x) {
  26044. cache[0] = x;
  26045. changed = true;
  26046. }
  26047. if (cache[1] !== y) {
  26048. cache[1] = y;
  26049. changed = true;
  26050. }
  26051. return changed;
  26052. };
  26053. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26054. var cache = this._valueCache[uniformName];
  26055. if (!cache) {
  26056. cache = [x, y, z];
  26057. this._valueCache[uniformName] = cache;
  26058. return true;
  26059. }
  26060. var changed = false;
  26061. if (cache[0] !== x) {
  26062. cache[0] = x;
  26063. changed = true;
  26064. }
  26065. if (cache[1] !== y) {
  26066. cache[1] = y;
  26067. changed = true;
  26068. }
  26069. if (cache[2] !== z) {
  26070. cache[2] = z;
  26071. changed = true;
  26072. }
  26073. return changed;
  26074. };
  26075. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26076. var cache = this._valueCache[uniformName];
  26077. if (!cache) {
  26078. cache = [x, y, z, w];
  26079. this._valueCache[uniformName] = cache;
  26080. return true;
  26081. }
  26082. var changed = false;
  26083. if (cache[0] !== x) {
  26084. cache[0] = x;
  26085. changed = true;
  26086. }
  26087. if (cache[1] !== y) {
  26088. cache[1] = y;
  26089. changed = true;
  26090. }
  26091. if (cache[2] !== z) {
  26092. cache[2] = z;
  26093. changed = true;
  26094. }
  26095. if (cache[3] !== w) {
  26096. cache[3] = w;
  26097. changed = true;
  26098. }
  26099. return changed;
  26100. };
  26101. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26102. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  26103. return;
  26104. }
  26105. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  26106. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  26107. };
  26108. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26109. this._engine.bindUniformBlock(this._program, blockName, index);
  26110. };
  26111. Effect.prototype.setIntArray = function (uniformName, array) {
  26112. this._valueCache[uniformName] = null;
  26113. this._engine.setIntArray(this.getUniform(uniformName), array);
  26114. return this;
  26115. };
  26116. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26117. this._valueCache[uniformName] = null;
  26118. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26119. return this;
  26120. };
  26121. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26122. this._valueCache[uniformName] = null;
  26123. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26124. return this;
  26125. };
  26126. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26127. this._valueCache[uniformName] = null;
  26128. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26129. return this;
  26130. };
  26131. Effect.prototype.setFloatArray = function (uniformName, array) {
  26132. this._valueCache[uniformName] = null;
  26133. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26134. return this;
  26135. };
  26136. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26137. this._valueCache[uniformName] = null;
  26138. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26139. return this;
  26140. };
  26141. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26142. this._valueCache[uniformName] = null;
  26143. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26144. return this;
  26145. };
  26146. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26147. this._valueCache[uniformName] = null;
  26148. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26149. return this;
  26150. };
  26151. Effect.prototype.setArray = function (uniformName, array) {
  26152. this._valueCache[uniformName] = null;
  26153. this._engine.setArray(this.getUniform(uniformName), array);
  26154. return this;
  26155. };
  26156. Effect.prototype.setArray2 = function (uniformName, array) {
  26157. this._valueCache[uniformName] = null;
  26158. this._engine.setArray2(this.getUniform(uniformName), array);
  26159. return this;
  26160. };
  26161. Effect.prototype.setArray3 = function (uniformName, array) {
  26162. this._valueCache[uniformName] = null;
  26163. this._engine.setArray3(this.getUniform(uniformName), array);
  26164. return this;
  26165. };
  26166. Effect.prototype.setArray4 = function (uniformName, array) {
  26167. this._valueCache[uniformName] = null;
  26168. this._engine.setArray4(this.getUniform(uniformName), array);
  26169. return this;
  26170. };
  26171. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26172. if (!matrices) {
  26173. return this;
  26174. }
  26175. this._valueCache[uniformName] = null;
  26176. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26177. return this;
  26178. };
  26179. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26180. if (this._cacheMatrix(uniformName, matrix)) {
  26181. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26182. }
  26183. return this;
  26184. };
  26185. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26186. this._valueCache[uniformName] = null;
  26187. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26188. return this;
  26189. };
  26190. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26191. this._valueCache[uniformName] = null;
  26192. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26193. return this;
  26194. };
  26195. Effect.prototype.setFloat = function (uniformName, value) {
  26196. var cache = this._valueCache[uniformName];
  26197. if (cache !== undefined && cache === value)
  26198. return this;
  26199. this._valueCache[uniformName] = value;
  26200. this._engine.setFloat(this.getUniform(uniformName), value);
  26201. return this;
  26202. };
  26203. Effect.prototype.setBool = function (uniformName, bool) {
  26204. var cache = this._valueCache[uniformName];
  26205. if (cache !== undefined && cache === bool)
  26206. return this;
  26207. this._valueCache[uniformName] = bool;
  26208. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26209. return this;
  26210. };
  26211. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26212. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26213. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26214. }
  26215. return this;
  26216. };
  26217. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26218. if (this._cacheFloat2(uniformName, x, y)) {
  26219. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26220. }
  26221. return this;
  26222. };
  26223. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26224. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26225. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26226. }
  26227. return this;
  26228. };
  26229. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26230. if (this._cacheFloat3(uniformName, x, y, z)) {
  26231. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26232. }
  26233. return this;
  26234. };
  26235. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26236. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26237. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26238. }
  26239. return this;
  26240. };
  26241. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26242. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26243. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26244. }
  26245. return this;
  26246. };
  26247. Effect.prototype.setColor3 = function (uniformName, color3) {
  26248. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26249. this._engine.setColor3(this.getUniform(uniformName), color3);
  26250. }
  26251. return this;
  26252. };
  26253. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26254. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26255. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26256. }
  26257. return this;
  26258. };
  26259. Effect.ResetCache = function () {
  26260. Effect._baseCache = {};
  26261. };
  26262. Effect._uniqueIdSeed = 0;
  26263. Effect._baseCache = {};
  26264. // Statics
  26265. Effect.ShadersStore = {};
  26266. Effect.IncludesShadersStore = {};
  26267. return Effect;
  26268. }());
  26269. BABYLON.Effect = Effect;
  26270. })(BABYLON || (BABYLON = {}));
  26271. //# sourceMappingURL=babylon.effect.js.map
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. var MaterialHelper = /** @class */ (function () {
  26275. function MaterialHelper() {
  26276. }
  26277. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26278. defines._needUVs = true;
  26279. defines[key] = true;
  26280. if (texture.getTextureMatrix().isIdentity(true)) {
  26281. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26282. if (texture.coordinatesIndex === 0) {
  26283. defines["MAINUV1"] = true;
  26284. }
  26285. else {
  26286. defines["MAINUV2"] = true;
  26287. }
  26288. }
  26289. else {
  26290. defines[key + "DIRECTUV"] = 0;
  26291. }
  26292. };
  26293. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26294. var matrix = texture.getTextureMatrix();
  26295. if (!matrix.isIdentity(true)) {
  26296. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26297. }
  26298. };
  26299. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26300. if (defines._areMiscDirty) {
  26301. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26302. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26303. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26304. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26305. }
  26306. };
  26307. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26308. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26309. var changed = false;
  26310. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26311. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26312. changed = true;
  26313. }
  26314. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26315. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26316. changed = true;
  26317. }
  26318. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26319. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26320. changed = true;
  26321. }
  26322. if (defines["INSTANCES"] !== useInstances) {
  26323. defines["INSTANCES"] = useInstances;
  26324. changed = true;
  26325. }
  26326. if (changed) {
  26327. defines.markAsUnprocessed();
  26328. }
  26329. };
  26330. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  26331. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26332. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26333. return false;
  26334. }
  26335. defines._normals = defines._needNormals;
  26336. defines._uvs = defines._needUVs;
  26337. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26338. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26339. defines["TANGENT"] = true;
  26340. }
  26341. if (defines._needUVs) {
  26342. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26343. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26344. }
  26345. else {
  26346. defines["UV1"] = false;
  26347. defines["UV2"] = false;
  26348. }
  26349. if (useVertexColor) {
  26350. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26351. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  26352. }
  26353. if (useBones) {
  26354. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26355. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26356. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26357. }
  26358. else {
  26359. defines["NUM_BONE_INFLUENCERS"] = 0;
  26360. defines["BonesPerMesh"] = 0;
  26361. }
  26362. }
  26363. if (useMorphTargets) {
  26364. var manager = mesh.morphTargetManager;
  26365. if (manager) {
  26366. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26367. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26368. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26369. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26370. }
  26371. else {
  26372. defines["MORPHTARGETS_TANGENT"] = false;
  26373. defines["MORPHTARGETS_NORMAL"] = false;
  26374. defines["MORPHTARGETS"] = false;
  26375. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26376. }
  26377. }
  26378. return true;
  26379. };
  26380. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26381. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26382. if (disableLighting === void 0) { disableLighting = false; }
  26383. if (!defines._areLightsDirty) {
  26384. return defines._needNormals;
  26385. }
  26386. var lightIndex = 0;
  26387. var needNormals = false;
  26388. var needRebuild = false;
  26389. var lightmapMode = false;
  26390. var shadowEnabled = false;
  26391. var specularEnabled = false;
  26392. if (scene.lightsEnabled && !disableLighting) {
  26393. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26394. var light = _a[_i];
  26395. needNormals = true;
  26396. if (defines["LIGHT" + lightIndex] === undefined) {
  26397. needRebuild = true;
  26398. }
  26399. defines["LIGHT" + lightIndex] = true;
  26400. defines["SPOTLIGHT" + lightIndex] = false;
  26401. defines["HEMILIGHT" + lightIndex] = false;
  26402. defines["POINTLIGHT" + lightIndex] = false;
  26403. defines["DIRLIGHT" + lightIndex] = false;
  26404. var type;
  26405. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26406. type = "SPOTLIGHT" + lightIndex;
  26407. }
  26408. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26409. type = "HEMILIGHT" + lightIndex;
  26410. }
  26411. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26412. type = "POINTLIGHT" + lightIndex;
  26413. }
  26414. else {
  26415. type = "DIRLIGHT" + lightIndex;
  26416. }
  26417. defines[type] = true;
  26418. // Specular
  26419. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26420. specularEnabled = true;
  26421. }
  26422. // Shadows
  26423. defines["SHADOW" + lightIndex] = false;
  26424. defines["SHADOWPCF" + lightIndex] = false;
  26425. defines["SHADOWESM" + lightIndex] = false;
  26426. defines["SHADOWCUBE" + lightIndex] = false;
  26427. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26428. var shadowGenerator = light.getShadowGenerator();
  26429. if (shadowGenerator) {
  26430. shadowEnabled = true;
  26431. shadowGenerator.prepareDefines(defines, lightIndex);
  26432. }
  26433. }
  26434. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26435. lightmapMode = true;
  26436. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26437. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26438. }
  26439. else {
  26440. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26441. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26442. }
  26443. lightIndex++;
  26444. if (lightIndex === maxSimultaneousLights)
  26445. break;
  26446. }
  26447. }
  26448. defines["SPECULARTERM"] = specularEnabled;
  26449. defines["SHADOWS"] = shadowEnabled;
  26450. // Resetting all other lights if any
  26451. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26452. if (defines["LIGHT" + index] !== undefined) {
  26453. defines["LIGHT" + index] = false;
  26454. defines["HEMILIGHT" + lightIndex] = false;
  26455. defines["POINTLIGHT" + lightIndex] = false;
  26456. defines["DIRLIGHT" + lightIndex] = false;
  26457. defines["SPOTLIGHT" + lightIndex] = false;
  26458. defines["SHADOW" + lightIndex] = false;
  26459. }
  26460. }
  26461. var caps = scene.getEngine().getCaps();
  26462. if (defines["SHADOWFLOAT"] === undefined) {
  26463. needRebuild = true;
  26464. }
  26465. defines["SHADOWFLOAT"] = shadowEnabled &&
  26466. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26467. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26468. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26469. if (needRebuild) {
  26470. defines.rebuild();
  26471. }
  26472. return needNormals;
  26473. };
  26474. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26475. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26476. var uniformsList;
  26477. var uniformBuffersList = null;
  26478. if (uniformsListOrOptions.uniformsNames) {
  26479. var options = uniformsListOrOptions;
  26480. uniformsList = options.uniformsNames;
  26481. uniformBuffersList = options.uniformBuffersNames;
  26482. samplersList = options.samplers;
  26483. defines = options.defines;
  26484. maxSimultaneousLights = options.maxSimultaneousLights;
  26485. }
  26486. else {
  26487. uniformsList = uniformsListOrOptions;
  26488. if (!samplersList) {
  26489. samplersList = [];
  26490. }
  26491. }
  26492. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26493. if (!defines["LIGHT" + lightIndex]) {
  26494. break;
  26495. }
  26496. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26497. if (uniformBuffersList) {
  26498. uniformBuffersList.push("Light" + lightIndex);
  26499. }
  26500. samplersList.push("shadowSampler" + lightIndex);
  26501. }
  26502. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26503. uniformsList.push("morphTargetInfluences");
  26504. }
  26505. };
  26506. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26507. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26508. if (!defines["SHADOWS"]) {
  26509. return;
  26510. }
  26511. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26512. if (!defines["LIGHT" + lightIndex]) {
  26513. break;
  26514. }
  26515. if (lightIndex > 0) {
  26516. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26517. }
  26518. if (defines["SHADOW" + lightIndex]) {
  26519. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26520. }
  26521. if (defines["SHADOWPCF" + lightIndex]) {
  26522. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26523. }
  26524. if (defines["SHADOWESM" + lightIndex]) {
  26525. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  26526. }
  26527. }
  26528. };
  26529. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26530. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26531. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26532. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26533. var manager = mesh.morphTargetManager;
  26534. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26535. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26536. for (var index = 0; index < influencers; index++) {
  26537. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26538. if (normal) {
  26539. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26540. }
  26541. if (tangent) {
  26542. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26543. }
  26544. if (attribs.length > maxAttributesCount) {
  26545. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26546. }
  26547. }
  26548. }
  26549. };
  26550. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26551. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26552. fallbacks.addCPUSkinningFallback(0, mesh);
  26553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26555. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26558. }
  26559. }
  26560. };
  26561. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26562. if (defines["INSTANCES"]) {
  26563. attribs.push("world0");
  26564. attribs.push("world1");
  26565. attribs.push("world2");
  26566. attribs.push("world3");
  26567. }
  26568. };
  26569. // Bindings
  26570. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26571. if (light.shadowEnabled && mesh.receiveShadows) {
  26572. var shadowGenerator = light.getShadowGenerator();
  26573. if (shadowGenerator) {
  26574. shadowGenerator.bindShadowLight(lightIndex, effect);
  26575. }
  26576. }
  26577. };
  26578. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26579. light.transferToEffect(effect, lightIndex + "");
  26580. };
  26581. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26582. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26583. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26584. var lightIndex = 0;
  26585. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26586. var light = _a[_i];
  26587. var scaledIntensity = light.getScaledIntensity();
  26588. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26589. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26590. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26591. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26592. if (defines["SPECULARTERM"]) {
  26593. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26594. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26595. }
  26596. // Shadows
  26597. if (scene.shadowsEnabled) {
  26598. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26599. }
  26600. light._uniformBuffer.update();
  26601. lightIndex++;
  26602. if (lightIndex === maxSimultaneousLights)
  26603. break;
  26604. }
  26605. };
  26606. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26607. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26608. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26609. effect.setColor3("vFogColor", scene.fogColor);
  26610. }
  26611. };
  26612. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26613. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26614. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26615. if (matrices && effect) {
  26616. effect.setMatrices("mBones", matrices);
  26617. }
  26618. }
  26619. };
  26620. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26621. var manager = abstractMesh.morphTargetManager;
  26622. if (!abstractMesh || !manager) {
  26623. return;
  26624. }
  26625. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26626. };
  26627. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26628. if (defines["LOGARITHMICDEPTH"]) {
  26629. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26630. }
  26631. };
  26632. MaterialHelper.BindClipPlane = function (effect, scene) {
  26633. if (scene.clipPlane) {
  26634. var clipPlane = scene.clipPlane;
  26635. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26636. }
  26637. };
  26638. return MaterialHelper;
  26639. }());
  26640. BABYLON.MaterialHelper = MaterialHelper;
  26641. })(BABYLON || (BABYLON = {}));
  26642. //# sourceMappingURL=babylon.materialHelper.js.map
  26643. var BABYLON;
  26644. (function (BABYLON) {
  26645. var MaterialDefines = /** @class */ (function () {
  26646. function MaterialDefines() {
  26647. this._isDirty = true;
  26648. this._areLightsDirty = true;
  26649. this._areAttributesDirty = true;
  26650. this._areTexturesDirty = true;
  26651. this._areFresnelDirty = true;
  26652. this._areMiscDirty = true;
  26653. this._areImageProcessingDirty = true;
  26654. this._normals = false;
  26655. this._uvs = false;
  26656. this._needNormals = false;
  26657. this._needUVs = false;
  26658. }
  26659. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26660. get: function () {
  26661. return this._isDirty;
  26662. },
  26663. enumerable: true,
  26664. configurable: true
  26665. });
  26666. MaterialDefines.prototype.markAsProcessed = function () {
  26667. this._isDirty = false;
  26668. this._areAttributesDirty = false;
  26669. this._areTexturesDirty = false;
  26670. this._areFresnelDirty = false;
  26671. this._areLightsDirty = false;
  26672. this._areMiscDirty = false;
  26673. this._areImageProcessingDirty = false;
  26674. };
  26675. MaterialDefines.prototype.markAsUnprocessed = function () {
  26676. this._isDirty = true;
  26677. };
  26678. MaterialDefines.prototype.markAllAsDirty = function () {
  26679. this._areTexturesDirty = true;
  26680. this._areAttributesDirty = true;
  26681. this._areLightsDirty = true;
  26682. this._areFresnelDirty = true;
  26683. this._areMiscDirty = true;
  26684. this._areImageProcessingDirty = true;
  26685. this._isDirty = true;
  26686. };
  26687. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26688. this._areImageProcessingDirty = true;
  26689. this._isDirty = true;
  26690. };
  26691. MaterialDefines.prototype.markAsLightDirty = function () {
  26692. this._areLightsDirty = true;
  26693. this._isDirty = true;
  26694. };
  26695. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26696. this._areAttributesDirty = true;
  26697. this._isDirty = true;
  26698. };
  26699. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26700. this._areTexturesDirty = true;
  26701. this._isDirty = true;
  26702. };
  26703. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26704. this._areFresnelDirty = true;
  26705. this._isDirty = true;
  26706. };
  26707. MaterialDefines.prototype.markAsMiscDirty = function () {
  26708. this._areMiscDirty = true;
  26709. this._isDirty = true;
  26710. };
  26711. MaterialDefines.prototype.rebuild = function () {
  26712. if (this._keys) {
  26713. delete this._keys;
  26714. }
  26715. this._keys = [];
  26716. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26717. var key = _a[_i];
  26718. if (key[0] === "_") {
  26719. continue;
  26720. }
  26721. this._keys.push(key);
  26722. }
  26723. };
  26724. MaterialDefines.prototype.isEqual = function (other) {
  26725. if (this._keys.length !== other._keys.length) {
  26726. return false;
  26727. }
  26728. for (var index = 0; index < this._keys.length; index++) {
  26729. var prop = this._keys[index];
  26730. if (this[prop] !== other[prop]) {
  26731. return false;
  26732. }
  26733. }
  26734. return true;
  26735. };
  26736. MaterialDefines.prototype.cloneTo = function (other) {
  26737. if (this._keys.length !== other._keys.length) {
  26738. other._keys = this._keys.slice(0);
  26739. }
  26740. for (var index = 0; index < this._keys.length; index++) {
  26741. var prop = this._keys[index];
  26742. other[prop] = this[prop];
  26743. }
  26744. };
  26745. MaterialDefines.prototype.reset = function () {
  26746. for (var index = 0; index < this._keys.length; index++) {
  26747. var prop = this._keys[index];
  26748. if (typeof (this[prop]) === "number") {
  26749. this[prop] = 0;
  26750. }
  26751. else {
  26752. this[prop] = false;
  26753. }
  26754. }
  26755. };
  26756. MaterialDefines.prototype.toString = function () {
  26757. var result = "";
  26758. for (var index = 0; index < this._keys.length; index++) {
  26759. var prop = this._keys[index];
  26760. var value = this[prop];
  26761. if (typeof (value) === "number") {
  26762. result += "#define " + prop + " " + this[prop] + "\n";
  26763. }
  26764. else if (value) {
  26765. result += "#define " + prop + "\n";
  26766. }
  26767. }
  26768. return result;
  26769. };
  26770. return MaterialDefines;
  26771. }());
  26772. BABYLON.MaterialDefines = MaterialDefines;
  26773. var Material = /** @class */ (function () {
  26774. function Material(name, scene, doNotAdd) {
  26775. this.checkReadyOnEveryCall = false;
  26776. this.checkReadyOnlyOnce = false;
  26777. this.state = "";
  26778. this.alpha = 1.0;
  26779. this._backFaceCulling = true;
  26780. this.doNotSerialize = false;
  26781. this.storeEffectOnSubMeshes = false;
  26782. /**
  26783. * An event triggered when the material is disposed.
  26784. * @type {BABYLON.Observable}
  26785. */
  26786. this.onDisposeObservable = new BABYLON.Observable();
  26787. /**
  26788. * An event triggered when the material is bound.
  26789. * @type {BABYLON.Observable}
  26790. */
  26791. this.onBindObservable = new BABYLON.Observable();
  26792. /**
  26793. * An event triggered when the material is unbound.
  26794. * @type {BABYLON.Observable}
  26795. */
  26796. this.onUnBindObservable = new BABYLON.Observable();
  26797. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26798. this._needDepthPrePass = false;
  26799. this.disableDepthWrite = false;
  26800. this.forceDepthWrite = false;
  26801. this.separateCullingPass = false;
  26802. this._fogEnabled = true;
  26803. this.pointSize = 1.0;
  26804. this.zOffset = 0;
  26805. this._wasPreviouslyReady = false;
  26806. this._fillMode = Material.TriangleFillMode;
  26807. this.name = name;
  26808. this.id = name || BABYLON.Tools.RandomId();
  26809. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26810. if (this._scene.useRightHandedSystem) {
  26811. this.sideOrientation = Material.ClockWiseSideOrientation;
  26812. }
  26813. else {
  26814. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26815. }
  26816. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  26817. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  26818. if (!doNotAdd) {
  26819. this._scene.materials.push(this);
  26820. }
  26821. }
  26822. Object.defineProperty(Material, "TriangleFillMode", {
  26823. get: function () {
  26824. return Material._TriangleFillMode;
  26825. },
  26826. enumerable: true,
  26827. configurable: true
  26828. });
  26829. Object.defineProperty(Material, "WireFrameFillMode", {
  26830. get: function () {
  26831. return Material._WireFrameFillMode;
  26832. },
  26833. enumerable: true,
  26834. configurable: true
  26835. });
  26836. Object.defineProperty(Material, "PointFillMode", {
  26837. get: function () {
  26838. return Material._PointFillMode;
  26839. },
  26840. enumerable: true,
  26841. configurable: true
  26842. });
  26843. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26844. get: function () {
  26845. return Material._ClockWiseSideOrientation;
  26846. },
  26847. enumerable: true,
  26848. configurable: true
  26849. });
  26850. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26851. get: function () {
  26852. return Material._CounterClockWiseSideOrientation;
  26853. },
  26854. enumerable: true,
  26855. configurable: true
  26856. });
  26857. Object.defineProperty(Material, "TextureDirtyFlag", {
  26858. get: function () {
  26859. return Material._TextureDirtyFlag;
  26860. },
  26861. enumerable: true,
  26862. configurable: true
  26863. });
  26864. Object.defineProperty(Material, "LightDirtyFlag", {
  26865. get: function () {
  26866. return Material._LightDirtyFlag;
  26867. },
  26868. enumerable: true,
  26869. configurable: true
  26870. });
  26871. Object.defineProperty(Material, "FresnelDirtyFlag", {
  26872. get: function () {
  26873. return Material._FresnelDirtyFlag;
  26874. },
  26875. enumerable: true,
  26876. configurable: true
  26877. });
  26878. Object.defineProperty(Material, "AttributesDirtyFlag", {
  26879. get: function () {
  26880. return Material._AttributesDirtyFlag;
  26881. },
  26882. enumerable: true,
  26883. configurable: true
  26884. });
  26885. Object.defineProperty(Material, "MiscDirtyFlag", {
  26886. get: function () {
  26887. return Material._MiscDirtyFlag;
  26888. },
  26889. enumerable: true,
  26890. configurable: true
  26891. });
  26892. Object.defineProperty(Material.prototype, "backFaceCulling", {
  26893. get: function () {
  26894. return this._backFaceCulling;
  26895. },
  26896. set: function (value) {
  26897. if (this._backFaceCulling === value) {
  26898. return;
  26899. }
  26900. this._backFaceCulling = value;
  26901. this.markAsDirty(Material.TextureDirtyFlag);
  26902. },
  26903. enumerable: true,
  26904. configurable: true
  26905. });
  26906. Object.defineProperty(Material.prototype, "onDispose", {
  26907. set: function (callback) {
  26908. if (this._onDisposeObserver) {
  26909. this.onDisposeObservable.remove(this._onDisposeObserver);
  26910. }
  26911. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26912. },
  26913. enumerable: true,
  26914. configurable: true
  26915. });
  26916. Object.defineProperty(Material.prototype, "onBind", {
  26917. set: function (callback) {
  26918. if (this._onBindObserver) {
  26919. this.onBindObservable.remove(this._onBindObserver);
  26920. }
  26921. this._onBindObserver = this.onBindObservable.add(callback);
  26922. },
  26923. enumerable: true,
  26924. configurable: true
  26925. });
  26926. Object.defineProperty(Material.prototype, "alphaMode", {
  26927. get: function () {
  26928. return this._alphaMode;
  26929. },
  26930. set: function (value) {
  26931. if (this._alphaMode === value) {
  26932. return;
  26933. }
  26934. this._alphaMode = value;
  26935. this.markAsDirty(Material.TextureDirtyFlag);
  26936. },
  26937. enumerable: true,
  26938. configurable: true
  26939. });
  26940. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  26941. get: function () {
  26942. return this._needDepthPrePass;
  26943. },
  26944. set: function (value) {
  26945. if (this._needDepthPrePass === value) {
  26946. return;
  26947. }
  26948. this._needDepthPrePass = value;
  26949. if (this._needDepthPrePass) {
  26950. this.checkReadyOnEveryCall = true;
  26951. }
  26952. },
  26953. enumerable: true,
  26954. configurable: true
  26955. });
  26956. Object.defineProperty(Material.prototype, "fogEnabled", {
  26957. get: function () {
  26958. return this._fogEnabled;
  26959. },
  26960. set: function (value) {
  26961. if (this._fogEnabled === value) {
  26962. return;
  26963. }
  26964. this._fogEnabled = value;
  26965. this.markAsDirty(Material.MiscDirtyFlag);
  26966. },
  26967. enumerable: true,
  26968. configurable: true
  26969. });
  26970. Object.defineProperty(Material.prototype, "wireframe", {
  26971. get: function () {
  26972. return this._fillMode === Material.WireFrameFillMode;
  26973. },
  26974. set: function (value) {
  26975. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26976. },
  26977. enumerable: true,
  26978. configurable: true
  26979. });
  26980. Object.defineProperty(Material.prototype, "pointsCloud", {
  26981. get: function () {
  26982. return this._fillMode === Material.PointFillMode;
  26983. },
  26984. set: function (value) {
  26985. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26986. },
  26987. enumerable: true,
  26988. configurable: true
  26989. });
  26990. Object.defineProperty(Material.prototype, "fillMode", {
  26991. get: function () {
  26992. return this._fillMode;
  26993. },
  26994. set: function (value) {
  26995. if (this._fillMode === value) {
  26996. return;
  26997. }
  26998. this._fillMode = value;
  26999. this.markAsDirty(Material.MiscDirtyFlag);
  27000. },
  27001. enumerable: true,
  27002. configurable: true
  27003. });
  27004. /**
  27005. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27006. * subclasses should override adding information pertainent to themselves
  27007. */
  27008. Material.prototype.toString = function (fullDetails) {
  27009. var ret = "Name: " + this.name;
  27010. if (fullDetails) {
  27011. }
  27012. return ret;
  27013. };
  27014. /**
  27015. * Child classes can use it to update shaders
  27016. */
  27017. Material.prototype.getClassName = function () {
  27018. return "Material";
  27019. };
  27020. Object.defineProperty(Material.prototype, "isFrozen", {
  27021. get: function () {
  27022. return this.checkReadyOnlyOnce;
  27023. },
  27024. enumerable: true,
  27025. configurable: true
  27026. });
  27027. Material.prototype.freeze = function () {
  27028. this.checkReadyOnlyOnce = true;
  27029. };
  27030. Material.prototype.unfreeze = function () {
  27031. this.checkReadyOnlyOnce = false;
  27032. };
  27033. Material.prototype.isReady = function (mesh, useInstances) {
  27034. return true;
  27035. };
  27036. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27037. return false;
  27038. };
  27039. Material.prototype.getEffect = function () {
  27040. return this._effect;
  27041. };
  27042. Material.prototype.getScene = function () {
  27043. return this._scene;
  27044. };
  27045. Material.prototype.needAlphaBlending = function () {
  27046. return (this.alpha < 1.0);
  27047. };
  27048. Material.prototype.needAlphaTesting = function () {
  27049. return false;
  27050. };
  27051. Material.prototype.getAlphaTestTexture = function () {
  27052. return null;
  27053. };
  27054. Material.prototype.markDirty = function () {
  27055. this._wasPreviouslyReady = false;
  27056. };
  27057. Material.prototype._preBind = function (effect, overrideOrientation) {
  27058. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27059. var engine = this._scene.getEngine();
  27060. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27061. var reverse = orientation === Material.ClockWiseSideOrientation;
  27062. engine.enableEffect(effect ? effect : this._effect);
  27063. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27064. return reverse;
  27065. };
  27066. Material.prototype.bind = function (world, mesh) {
  27067. };
  27068. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27069. };
  27070. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27071. };
  27072. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27073. sceneUbo.bindToEffect(effect, "Scene");
  27074. };
  27075. Material.prototype.bindView = function (effect) {
  27076. if (!this._useUBO) {
  27077. effect.setMatrix("view", this.getScene().getViewMatrix());
  27078. }
  27079. else {
  27080. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27081. }
  27082. };
  27083. Material.prototype.bindViewProjection = function (effect) {
  27084. if (!this._useUBO) {
  27085. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27086. }
  27087. else {
  27088. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27089. }
  27090. };
  27091. Material.prototype._afterBind = function (mesh) {
  27092. this._scene._cachedMaterial = this;
  27093. if (mesh) {
  27094. this._scene._cachedVisibility = mesh.visibility;
  27095. }
  27096. else {
  27097. this._scene._cachedVisibility = 1;
  27098. }
  27099. if (mesh) {
  27100. this.onBindObservable.notifyObservers(mesh);
  27101. }
  27102. if (this.disableDepthWrite) {
  27103. var engine = this._scene.getEngine();
  27104. this._cachedDepthWriteState = engine.getDepthWrite();
  27105. engine.setDepthWrite(false);
  27106. }
  27107. };
  27108. Material.prototype.unbind = function () {
  27109. this.onUnBindObservable.notifyObservers(this);
  27110. if (this.disableDepthWrite) {
  27111. var engine = this._scene.getEngine();
  27112. engine.setDepthWrite(this._cachedDepthWriteState);
  27113. }
  27114. };
  27115. Material.prototype.getActiveTextures = function () {
  27116. return [];
  27117. };
  27118. Material.prototype.hasTexture = function (texture) {
  27119. return false;
  27120. };
  27121. Material.prototype.clone = function (name) {
  27122. return null;
  27123. };
  27124. Material.prototype.getBindedMeshes = function () {
  27125. var result = new Array();
  27126. for (var index = 0; index < this._scene.meshes.length; index++) {
  27127. var mesh = this._scene.meshes[index];
  27128. if (mesh.material === this) {
  27129. result.push(mesh);
  27130. }
  27131. }
  27132. return result;
  27133. };
  27134. /**
  27135. * Force shader compilation including textures ready check
  27136. */
  27137. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27138. var _this = this;
  27139. var subMesh = new BABYLON.BaseSubMesh();
  27140. var scene = this.getScene();
  27141. var engine = scene.getEngine();
  27142. var checkReady = function () {
  27143. if (!_this._scene || !_this._scene.getEngine()) {
  27144. return;
  27145. }
  27146. if (subMesh._materialDefines) {
  27147. subMesh._materialDefines._renderId = -1;
  27148. }
  27149. var alphaTestState = engine.getAlphaTesting();
  27150. var clipPlaneState = scene.clipPlane;
  27151. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27152. if (options && options.clipPlane) {
  27153. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27154. }
  27155. if (_this.storeEffectOnSubMeshes) {
  27156. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27157. if (onCompiled) {
  27158. onCompiled(_this);
  27159. }
  27160. }
  27161. else {
  27162. setTimeout(checkReady, 16);
  27163. }
  27164. }
  27165. else {
  27166. if (_this.isReady(mesh)) {
  27167. if (onCompiled) {
  27168. onCompiled(_this);
  27169. }
  27170. }
  27171. else {
  27172. setTimeout(checkReady, 16);
  27173. }
  27174. }
  27175. engine.setAlphaTesting(alphaTestState);
  27176. if (options && options.clipPlane) {
  27177. scene.clipPlane = clipPlaneState;
  27178. }
  27179. };
  27180. checkReady();
  27181. };
  27182. Material.prototype.markAsDirty = function (flag) {
  27183. if (flag & Material.TextureDirtyFlag) {
  27184. this._markAllSubMeshesAsTexturesDirty();
  27185. }
  27186. if (flag & Material.LightDirtyFlag) {
  27187. this._markAllSubMeshesAsLightsDirty();
  27188. }
  27189. if (flag & Material.FresnelDirtyFlag) {
  27190. this._markAllSubMeshesAsFresnelDirty();
  27191. }
  27192. if (flag & Material.AttributesDirtyFlag) {
  27193. this._markAllSubMeshesAsAttributesDirty();
  27194. }
  27195. if (flag & Material.MiscDirtyFlag) {
  27196. this._markAllSubMeshesAsMiscDirty();
  27197. }
  27198. this.getScene().resetCachedMaterial();
  27199. };
  27200. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27201. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27202. var mesh = _a[_i];
  27203. if (!mesh.subMeshes) {
  27204. continue;
  27205. }
  27206. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27207. var subMesh = _c[_b];
  27208. if (subMesh.getMaterial() !== this) {
  27209. continue;
  27210. }
  27211. if (!subMesh._materialDefines) {
  27212. continue;
  27213. }
  27214. func(subMesh._materialDefines);
  27215. }
  27216. }
  27217. };
  27218. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27219. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27220. };
  27221. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27222. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27223. };
  27224. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27225. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27226. };
  27227. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27228. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27229. };
  27230. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27231. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27232. };
  27233. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27234. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27235. };
  27236. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27237. // Animations
  27238. this.getScene().stopAnimation(this);
  27239. // Remove from scene
  27240. var index = this._scene.materials.indexOf(this);
  27241. if (index >= 0) {
  27242. this._scene.materials.splice(index, 1);
  27243. }
  27244. // Remove from meshes
  27245. for (index = 0; index < this._scene.meshes.length; index++) {
  27246. var mesh = this._scene.meshes[index];
  27247. if (mesh.material === this) {
  27248. mesh.material = null;
  27249. if (mesh.geometry) {
  27250. var geometry = (mesh.geometry);
  27251. if (this.storeEffectOnSubMeshes) {
  27252. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27253. var subMesh = _a[_i];
  27254. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27255. if (forceDisposeEffect && subMesh._materialEffect) {
  27256. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27257. }
  27258. }
  27259. }
  27260. else {
  27261. geometry._releaseVertexArrayObject(this._effect);
  27262. }
  27263. }
  27264. }
  27265. }
  27266. this._uniformBuffer.dispose();
  27267. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27268. if (forceDisposeEffect && this._effect) {
  27269. if (!this.storeEffectOnSubMeshes) {
  27270. this._scene.getEngine()._releaseEffect(this._effect);
  27271. }
  27272. this._effect = null;
  27273. }
  27274. // Callback
  27275. this.onDisposeObservable.notifyObservers(this);
  27276. this.onDisposeObservable.clear();
  27277. this.onBindObservable.clear();
  27278. this.onUnBindObservable.clear();
  27279. };
  27280. Material.prototype.serialize = function () {
  27281. return BABYLON.SerializationHelper.Serialize(this);
  27282. };
  27283. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27284. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27285. multiMaterial.id = parsedMultiMaterial.id;
  27286. if (BABYLON.Tags) {
  27287. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27288. }
  27289. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27290. var subMatId = parsedMultiMaterial.materials[matIndex];
  27291. if (subMatId) {
  27292. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27293. }
  27294. else {
  27295. multiMaterial.subMaterials.push(null);
  27296. }
  27297. }
  27298. return multiMaterial;
  27299. };
  27300. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27301. if (!parsedMaterial.customType) {
  27302. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27303. }
  27304. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27305. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27306. if (!BABYLON.LegacyPBRMaterial) {
  27307. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27308. return;
  27309. }
  27310. }
  27311. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27312. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27313. ;
  27314. };
  27315. Material._TriangleFillMode = 0;
  27316. Material._WireFrameFillMode = 1;
  27317. Material._PointFillMode = 2;
  27318. Material._ClockWiseSideOrientation = 0;
  27319. Material._CounterClockWiseSideOrientation = 1;
  27320. Material._TextureDirtyFlag = 1;
  27321. Material._LightDirtyFlag = 2;
  27322. Material._FresnelDirtyFlag = 4;
  27323. Material._AttributesDirtyFlag = 8;
  27324. Material._MiscDirtyFlag = 16;
  27325. __decorate([
  27326. BABYLON.serialize()
  27327. ], Material.prototype, "id", void 0);
  27328. __decorate([
  27329. BABYLON.serialize()
  27330. ], Material.prototype, "name", void 0);
  27331. __decorate([
  27332. BABYLON.serialize()
  27333. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27334. __decorate([
  27335. BABYLON.serialize()
  27336. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27337. __decorate([
  27338. BABYLON.serialize()
  27339. ], Material.prototype, "state", void 0);
  27340. __decorate([
  27341. BABYLON.serialize()
  27342. ], Material.prototype, "alpha", void 0);
  27343. __decorate([
  27344. BABYLON.serialize("backFaceCulling")
  27345. ], Material.prototype, "_backFaceCulling", void 0);
  27346. __decorate([
  27347. BABYLON.serialize()
  27348. ], Material.prototype, "sideOrientation", void 0);
  27349. __decorate([
  27350. BABYLON.serialize("alphaMode")
  27351. ], Material.prototype, "_alphaMode", void 0);
  27352. __decorate([
  27353. BABYLON.serialize()
  27354. ], Material.prototype, "_needDepthPrePass", void 0);
  27355. __decorate([
  27356. BABYLON.serialize()
  27357. ], Material.prototype, "disableDepthWrite", void 0);
  27358. __decorate([
  27359. BABYLON.serialize()
  27360. ], Material.prototype, "forceDepthWrite", void 0);
  27361. __decorate([
  27362. BABYLON.serialize()
  27363. ], Material.prototype, "separateCullingPass", void 0);
  27364. __decorate([
  27365. BABYLON.serialize("fogEnabled")
  27366. ], Material.prototype, "_fogEnabled", void 0);
  27367. __decorate([
  27368. BABYLON.serialize()
  27369. ], Material.prototype, "pointSize", void 0);
  27370. __decorate([
  27371. BABYLON.serialize()
  27372. ], Material.prototype, "zOffset", void 0);
  27373. __decorate([
  27374. BABYLON.serialize()
  27375. ], Material.prototype, "wireframe", null);
  27376. __decorate([
  27377. BABYLON.serialize()
  27378. ], Material.prototype, "pointsCloud", null);
  27379. __decorate([
  27380. BABYLON.serialize()
  27381. ], Material.prototype, "fillMode", null);
  27382. return Material;
  27383. }());
  27384. BABYLON.Material = Material;
  27385. })(BABYLON || (BABYLON = {}));
  27386. //# sourceMappingURL=babylon.material.js.map
  27387. var BABYLON;
  27388. (function (BABYLON) {
  27389. var UniformBuffer = /** @class */ (function () {
  27390. /**
  27391. * Uniform buffer objects.
  27392. *
  27393. * Handles blocks of uniform on the GPU.
  27394. *
  27395. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27396. *
  27397. * For more information, please refer to :
  27398. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27399. */
  27400. function UniformBuffer(engine, data, dynamic) {
  27401. this._engine = engine;
  27402. this._noUBO = !engine.supportsUniformBuffers;
  27403. this._dynamic = dynamic;
  27404. this._data = data || [];
  27405. this._uniformLocations = {};
  27406. this._uniformSizes = {};
  27407. this._uniformLocationPointer = 0;
  27408. this._needSync = false;
  27409. if (this._noUBO) {
  27410. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27411. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27412. this.updateFloat = this._updateFloatForEffect;
  27413. this.updateFloat2 = this._updateFloat2ForEffect;
  27414. this.updateFloat3 = this._updateFloat3ForEffect;
  27415. this.updateFloat4 = this._updateFloat4ForEffect;
  27416. this.updateMatrix = this._updateMatrixForEffect;
  27417. this.updateVector3 = this._updateVector3ForEffect;
  27418. this.updateVector4 = this._updateVector4ForEffect;
  27419. this.updateColor3 = this._updateColor3ForEffect;
  27420. this.updateColor4 = this._updateColor4ForEffect;
  27421. }
  27422. else {
  27423. this._engine._uniformBuffers.push(this);
  27424. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27425. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27426. this.updateFloat = this._updateFloatForUniform;
  27427. this.updateFloat2 = this._updateFloat2ForUniform;
  27428. this.updateFloat3 = this._updateFloat3ForUniform;
  27429. this.updateFloat4 = this._updateFloat4ForUniform;
  27430. this.updateMatrix = this._updateMatrixForUniform;
  27431. this.updateVector3 = this._updateVector3ForUniform;
  27432. this.updateVector4 = this._updateVector4ForUniform;
  27433. this.updateColor3 = this._updateColor3ForUniform;
  27434. this.updateColor4 = this._updateColor4ForUniform;
  27435. }
  27436. }
  27437. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27438. // Properties
  27439. /**
  27440. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27441. * or just falling back on setUniformXXX calls.
  27442. */
  27443. get: function () {
  27444. return !this._noUBO;
  27445. },
  27446. enumerable: true,
  27447. configurable: true
  27448. });
  27449. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27450. /**
  27451. * Indicates if the WebGL underlying uniform buffer is in sync
  27452. * with the javascript cache data.
  27453. */
  27454. get: function () {
  27455. return !this._needSync;
  27456. },
  27457. enumerable: true,
  27458. configurable: true
  27459. });
  27460. /**
  27461. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27462. * Also, a dynamic UniformBuffer will disable cache verification and always
  27463. * update the underlying WebGL uniform buffer to the GPU.
  27464. */
  27465. UniformBuffer.prototype.isDynamic = function () {
  27466. return this._dynamic !== undefined;
  27467. };
  27468. /**
  27469. * The data cache on JS side.
  27470. */
  27471. UniformBuffer.prototype.getData = function () {
  27472. return this._bufferData;
  27473. };
  27474. /**
  27475. * The underlying WebGL Uniform buffer.
  27476. */
  27477. UniformBuffer.prototype.getBuffer = function () {
  27478. return this._buffer;
  27479. };
  27480. /**
  27481. * std140 layout specifies how to align data within an UBO structure.
  27482. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27483. * for specs.
  27484. */
  27485. UniformBuffer.prototype._fillAlignment = function (size) {
  27486. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27487. // and 4x4 matrices
  27488. // TODO : change if other types are used
  27489. var alignment;
  27490. if (size <= 2) {
  27491. alignment = size;
  27492. }
  27493. else {
  27494. alignment = 4;
  27495. }
  27496. if ((this._uniformLocationPointer % alignment) !== 0) {
  27497. var oldPointer = this._uniformLocationPointer;
  27498. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27499. var diff = this._uniformLocationPointer - oldPointer;
  27500. for (var i = 0; i < diff; i++) {
  27501. this._data.push(0);
  27502. }
  27503. }
  27504. };
  27505. /**
  27506. * Adds an uniform in the buffer.
  27507. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27508. * for the layout to be correct !
  27509. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27510. * @param {number|number[]} size Data size, or data directly.
  27511. */
  27512. UniformBuffer.prototype.addUniform = function (name, size) {
  27513. if (this._noUBO) {
  27514. return;
  27515. }
  27516. if (this._uniformLocations[name] !== undefined) {
  27517. // Already existing uniform
  27518. return;
  27519. }
  27520. // This function must be called in the order of the shader layout !
  27521. // size can be the size of the uniform, or data directly
  27522. var data;
  27523. if (size instanceof Array) {
  27524. data = size;
  27525. size = data.length;
  27526. }
  27527. else {
  27528. size = size;
  27529. data = [];
  27530. // Fill with zeros
  27531. for (var i = 0; i < size; i++) {
  27532. data.push(0);
  27533. }
  27534. }
  27535. this._fillAlignment(size);
  27536. this._uniformSizes[name] = size;
  27537. this._uniformLocations[name] = this._uniformLocationPointer;
  27538. this._uniformLocationPointer += size;
  27539. for (var i = 0; i < size; i++) {
  27540. this._data.push(data[i]);
  27541. }
  27542. this._needSync = true;
  27543. };
  27544. /**
  27545. * Wrapper for addUniform.
  27546. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27547. * @param {Matrix} mat A 4x4 matrix.
  27548. */
  27549. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27550. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27551. };
  27552. /**
  27553. * Wrapper for addUniform.
  27554. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27555. * @param {number} x
  27556. * @param {number} y
  27557. */
  27558. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27559. var temp = [x, y];
  27560. this.addUniform(name, temp);
  27561. };
  27562. /**
  27563. * Wrapper for addUniform.
  27564. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27565. * @param {number} x
  27566. * @param {number} y
  27567. * @param {number} z
  27568. */
  27569. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27570. var temp = [x, y, z];
  27571. this.addUniform(name, temp);
  27572. };
  27573. /**
  27574. * Wrapper for addUniform.
  27575. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27576. * @param {Color3} color
  27577. */
  27578. UniformBuffer.prototype.addColor3 = function (name, color) {
  27579. var temp = new Array();
  27580. color.toArray(temp);
  27581. this.addUniform(name, temp);
  27582. };
  27583. /**
  27584. * Wrapper for addUniform.
  27585. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27586. * @param {Color3} color
  27587. * @param {number} alpha
  27588. */
  27589. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27590. var temp = new Array();
  27591. color.toArray(temp);
  27592. temp.push(alpha);
  27593. this.addUniform(name, temp);
  27594. };
  27595. /**
  27596. * Wrapper for addUniform.
  27597. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27598. * @param {Vector3} vector
  27599. */
  27600. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27601. var temp = new Array();
  27602. vector.toArray(temp);
  27603. this.addUniform(name, temp);
  27604. };
  27605. /**
  27606. * Wrapper for addUniform.
  27607. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27608. */
  27609. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27610. this.addUniform(name, 12);
  27611. };
  27612. /**
  27613. * Wrapper for addUniform.
  27614. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27615. */
  27616. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27617. this.addUniform(name, 8);
  27618. };
  27619. /**
  27620. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27621. */
  27622. UniformBuffer.prototype.create = function () {
  27623. if (this._noUBO) {
  27624. return;
  27625. }
  27626. if (this._buffer) {
  27627. return; // nothing to do
  27628. }
  27629. // See spec, alignment must be filled as a vec4
  27630. this._fillAlignment(4);
  27631. this._bufferData = new Float32Array(this._data);
  27632. this._rebuild();
  27633. this._needSync = true;
  27634. };
  27635. UniformBuffer.prototype._rebuild = function () {
  27636. if (this._noUBO) {
  27637. return;
  27638. }
  27639. if (this._dynamic) {
  27640. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27641. }
  27642. else {
  27643. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27644. }
  27645. };
  27646. /**
  27647. * Updates the WebGL Uniform Buffer on the GPU.
  27648. * If the `dynamic` flag is set to true, no cache comparison is done.
  27649. * Otherwise, the buffer will be updated only if the cache differs.
  27650. */
  27651. UniformBuffer.prototype.update = function () {
  27652. if (!this._buffer) {
  27653. this.create();
  27654. return;
  27655. }
  27656. if (!this._dynamic && !this._needSync) {
  27657. return;
  27658. }
  27659. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27660. this._needSync = false;
  27661. };
  27662. /**
  27663. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27664. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27665. * @param {number[]|Float32Array} data Flattened data
  27666. * @param {number} size Size of the data.
  27667. */
  27668. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27669. var location = this._uniformLocations[uniformName];
  27670. if (location === undefined) {
  27671. if (this._buffer) {
  27672. // Cannot add an uniform if the buffer is already created
  27673. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27674. return;
  27675. }
  27676. this.addUniform(uniformName, size);
  27677. location = this._uniformLocations[uniformName];
  27678. }
  27679. if (!this._buffer) {
  27680. this.create();
  27681. }
  27682. if (!this._dynamic) {
  27683. // Cache for static uniform buffers
  27684. var changed = false;
  27685. for (var i = 0; i < size; i++) {
  27686. if (this._bufferData[location + i] !== data[i]) {
  27687. changed = true;
  27688. this._bufferData[location + i] = data[i];
  27689. }
  27690. }
  27691. this._needSync = this._needSync || changed;
  27692. }
  27693. else {
  27694. // No cache for dynamic
  27695. for (var i = 0; i < size; i++) {
  27696. this._bufferData[location + i] = data[i];
  27697. }
  27698. }
  27699. };
  27700. // Update methods
  27701. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27702. // To match std140, matrix must be realigned
  27703. for (var i = 0; i < 3; i++) {
  27704. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27705. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27706. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27707. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27708. }
  27709. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27710. };
  27711. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27712. this._currentEffect.setMatrix3x3(name, matrix);
  27713. };
  27714. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27715. this._currentEffect.setMatrix2x2(name, matrix);
  27716. };
  27717. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27718. // To match std140, matrix must be realigned
  27719. for (var i = 0; i < 2; i++) {
  27720. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27721. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27722. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27723. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27724. }
  27725. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27726. };
  27727. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27728. this._currentEffect.setFloat(name, x);
  27729. };
  27730. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27731. UniformBuffer._tempBuffer[0] = x;
  27732. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27733. };
  27734. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27735. if (suffix === void 0) { suffix = ""; }
  27736. this._currentEffect.setFloat2(name + suffix, x, y);
  27737. };
  27738. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27739. if (suffix === void 0) { suffix = ""; }
  27740. UniformBuffer._tempBuffer[0] = x;
  27741. UniformBuffer._tempBuffer[1] = y;
  27742. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27743. };
  27744. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27745. if (suffix === void 0) { suffix = ""; }
  27746. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27747. };
  27748. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27749. if (suffix === void 0) { suffix = ""; }
  27750. UniformBuffer._tempBuffer[0] = x;
  27751. UniformBuffer._tempBuffer[1] = y;
  27752. UniformBuffer._tempBuffer[2] = z;
  27753. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27754. };
  27755. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27756. if (suffix === void 0) { suffix = ""; }
  27757. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27758. };
  27759. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27760. if (suffix === void 0) { suffix = ""; }
  27761. UniformBuffer._tempBuffer[0] = x;
  27762. UniformBuffer._tempBuffer[1] = y;
  27763. UniformBuffer._tempBuffer[2] = z;
  27764. UniformBuffer._tempBuffer[3] = w;
  27765. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27766. };
  27767. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27768. this._currentEffect.setMatrix(name, mat);
  27769. };
  27770. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27771. this.updateUniform(name, mat.toArray(), 16);
  27772. };
  27773. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27774. this._currentEffect.setVector3(name, vector);
  27775. };
  27776. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27777. vector.toArray(UniformBuffer._tempBuffer);
  27778. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27779. };
  27780. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27781. this._currentEffect.setVector4(name, vector);
  27782. };
  27783. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27784. vector.toArray(UniformBuffer._tempBuffer);
  27785. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27786. };
  27787. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27788. if (suffix === void 0) { suffix = ""; }
  27789. this._currentEffect.setColor3(name + suffix, color);
  27790. };
  27791. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27792. if (suffix === void 0) { suffix = ""; }
  27793. color.toArray(UniformBuffer._tempBuffer);
  27794. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27795. };
  27796. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27797. if (suffix === void 0) { suffix = ""; }
  27798. this._currentEffect.setColor4(name + suffix, color, alpha);
  27799. };
  27800. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27801. if (suffix === void 0) { suffix = ""; }
  27802. color.toArray(UniformBuffer._tempBuffer);
  27803. UniformBuffer._tempBuffer[3] = alpha;
  27804. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27805. };
  27806. /**
  27807. * Sets a sampler uniform on the effect.
  27808. * @param {string} name Name of the sampler.
  27809. * @param {Texture} texture
  27810. */
  27811. UniformBuffer.prototype.setTexture = function (name, texture) {
  27812. this._currentEffect.setTexture(name, texture);
  27813. };
  27814. /**
  27815. * Directly updates the value of the uniform in the cache AND on the GPU.
  27816. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27817. * @param {number[]|Float32Array} data Flattened data
  27818. */
  27819. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  27820. this.updateUniform(uniformName, data, data.length);
  27821. this.update();
  27822. };
  27823. /**
  27824. * Binds this uniform buffer to an effect.
  27825. * @param {Effect} effect
  27826. * @param {string} name Name of the uniform block in the shader.
  27827. */
  27828. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  27829. this._currentEffect = effect;
  27830. if (this._noUBO || !this._buffer) {
  27831. return;
  27832. }
  27833. effect.bindUniformBuffer(this._buffer, name);
  27834. };
  27835. /**
  27836. * Disposes the uniform buffer.
  27837. */
  27838. UniformBuffer.prototype.dispose = function () {
  27839. if (this._noUBO) {
  27840. return;
  27841. }
  27842. var index = this._engine._uniformBuffers.indexOf(this);
  27843. if (index !== -1) {
  27844. this._engine._uniformBuffers.splice(index, 1);
  27845. }
  27846. if (!this._buffer) {
  27847. return;
  27848. }
  27849. if (this._engine._releaseBuffer(this._buffer)) {
  27850. this._buffer = null;
  27851. }
  27852. };
  27853. // Pool for avoiding memory leaks
  27854. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  27855. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  27856. return UniformBuffer;
  27857. }());
  27858. BABYLON.UniformBuffer = UniformBuffer;
  27859. })(BABYLON || (BABYLON = {}));
  27860. //# sourceMappingURL=babylon.uniformBuffer.js.map
  27861. var BABYLON;
  27862. (function (BABYLON) {
  27863. var PushMaterial = /** @class */ (function (_super) {
  27864. __extends(PushMaterial, _super);
  27865. function PushMaterial(name, scene) {
  27866. var _this = _super.call(this, name, scene) || this;
  27867. _this.storeEffectOnSubMeshes = true;
  27868. return _this;
  27869. }
  27870. PushMaterial.prototype.getEffect = function () {
  27871. return this._activeEffect;
  27872. };
  27873. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  27874. if (!mesh) {
  27875. return false;
  27876. }
  27877. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27878. return true;
  27879. }
  27880. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  27881. };
  27882. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27883. this._activeEffect.setMatrix("world", world);
  27884. };
  27885. PushMaterial.prototype.bind = function (world, mesh) {
  27886. if (!mesh) {
  27887. return;
  27888. }
  27889. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  27890. };
  27891. PushMaterial.prototype._afterBind = function (mesh, effect) {
  27892. if (effect === void 0) { effect = null; }
  27893. _super.prototype._afterBind.call(this, mesh);
  27894. this.getScene()._cachedEffect = effect;
  27895. };
  27896. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  27897. if (visibility === void 0) { visibility = 1; }
  27898. return scene.isCachedMaterialInvalid(this, effect, visibility);
  27899. };
  27900. return PushMaterial;
  27901. }(BABYLON.Material));
  27902. BABYLON.PushMaterial = PushMaterial;
  27903. })(BABYLON || (BABYLON = {}));
  27904. //# sourceMappingURL=babylon.pushMaterial.js.map
  27905. var BABYLON;
  27906. (function (BABYLON) {
  27907. var VertexData = /** @class */ (function () {
  27908. function VertexData() {
  27909. }
  27910. VertexData.prototype.set = function (data, kind) {
  27911. switch (kind) {
  27912. case BABYLON.VertexBuffer.PositionKind:
  27913. this.positions = data;
  27914. break;
  27915. case BABYLON.VertexBuffer.NormalKind:
  27916. this.normals = data;
  27917. break;
  27918. case BABYLON.VertexBuffer.TangentKind:
  27919. this.tangents = data;
  27920. break;
  27921. case BABYLON.VertexBuffer.UVKind:
  27922. this.uvs = data;
  27923. break;
  27924. case BABYLON.VertexBuffer.UV2Kind:
  27925. this.uvs2 = data;
  27926. break;
  27927. case BABYLON.VertexBuffer.UV3Kind:
  27928. this.uvs3 = data;
  27929. break;
  27930. case BABYLON.VertexBuffer.UV4Kind:
  27931. this.uvs4 = data;
  27932. break;
  27933. case BABYLON.VertexBuffer.UV5Kind:
  27934. this.uvs5 = data;
  27935. break;
  27936. case BABYLON.VertexBuffer.UV6Kind:
  27937. this.uvs6 = data;
  27938. break;
  27939. case BABYLON.VertexBuffer.ColorKind:
  27940. this.colors = data;
  27941. break;
  27942. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27943. this.matricesIndices = data;
  27944. break;
  27945. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27946. this.matricesWeights = data;
  27947. break;
  27948. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27949. this.matricesIndicesExtra = data;
  27950. break;
  27951. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27952. this.matricesWeightsExtra = data;
  27953. break;
  27954. }
  27955. };
  27956. /**
  27957. * Associates the vertexData to the passed Mesh.
  27958. * Sets it as updatable or not (default `false`).
  27959. * Returns the VertexData.
  27960. */
  27961. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27962. this._applyTo(mesh, updatable);
  27963. return this;
  27964. };
  27965. /**
  27966. * Associates the vertexData to the passed Geometry.
  27967. * Sets it as updatable or not (default `false`).
  27968. * Returns the VertexData.
  27969. */
  27970. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27971. this._applyTo(geometry, updatable);
  27972. return this;
  27973. };
  27974. /**
  27975. * Updates the associated mesh.
  27976. * Returns the VertexData.
  27977. */
  27978. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27979. this._update(mesh);
  27980. return this;
  27981. };
  27982. /**
  27983. * Updates the associated geometry.
  27984. * Returns the VertexData.
  27985. */
  27986. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27987. this._update(geometry);
  27988. return this;
  27989. };
  27990. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27991. if (updatable === void 0) { updatable = false; }
  27992. if (this.positions) {
  27993. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27994. }
  27995. if (this.normals) {
  27996. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27997. }
  27998. if (this.tangents) {
  27999. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28000. }
  28001. if (this.uvs) {
  28002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28003. }
  28004. if (this.uvs2) {
  28005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28006. }
  28007. if (this.uvs3) {
  28008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28009. }
  28010. if (this.uvs4) {
  28011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28012. }
  28013. if (this.uvs5) {
  28014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28015. }
  28016. if (this.uvs6) {
  28017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28018. }
  28019. if (this.colors) {
  28020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28021. }
  28022. if (this.matricesIndices) {
  28023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28024. }
  28025. if (this.matricesWeights) {
  28026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28027. }
  28028. if (this.matricesIndicesExtra) {
  28029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28030. }
  28031. if (this.matricesWeightsExtra) {
  28032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28033. }
  28034. if (this.indices) {
  28035. meshOrGeometry.setIndices(this.indices, null, updatable);
  28036. }
  28037. return this;
  28038. };
  28039. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28040. if (this.positions) {
  28041. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28042. }
  28043. if (this.normals) {
  28044. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28045. }
  28046. if (this.tangents) {
  28047. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28048. }
  28049. if (this.uvs) {
  28050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28051. }
  28052. if (this.uvs2) {
  28053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28054. }
  28055. if (this.uvs3) {
  28056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28057. }
  28058. if (this.uvs4) {
  28059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28060. }
  28061. if (this.uvs5) {
  28062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28063. }
  28064. if (this.uvs6) {
  28065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28066. }
  28067. if (this.colors) {
  28068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28069. }
  28070. if (this.matricesIndices) {
  28071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28072. }
  28073. if (this.matricesWeights) {
  28074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28075. }
  28076. if (this.matricesIndicesExtra) {
  28077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28078. }
  28079. if (this.matricesWeightsExtra) {
  28080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28081. }
  28082. if (this.indices) {
  28083. meshOrGeometry.setIndices(this.indices, null);
  28084. }
  28085. return this;
  28086. };
  28087. /**
  28088. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28089. * Returns the VertexData.
  28090. */
  28091. VertexData.prototype.transform = function (matrix) {
  28092. var transformed = BABYLON.Vector3.Zero();
  28093. var index;
  28094. if (this.positions) {
  28095. var position = BABYLON.Vector3.Zero();
  28096. for (index = 0; index < this.positions.length; index += 3) {
  28097. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28098. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28099. this.positions[index] = transformed.x;
  28100. this.positions[index + 1] = transformed.y;
  28101. this.positions[index + 2] = transformed.z;
  28102. }
  28103. }
  28104. if (this.normals) {
  28105. var normal = BABYLON.Vector3.Zero();
  28106. for (index = 0; index < this.normals.length; index += 3) {
  28107. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28108. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28109. this.normals[index] = transformed.x;
  28110. this.normals[index + 1] = transformed.y;
  28111. this.normals[index + 2] = transformed.z;
  28112. }
  28113. }
  28114. if (this.tangents) {
  28115. var tangent = BABYLON.Vector4.Zero();
  28116. var tangentTransformed = BABYLON.Vector4.Zero();
  28117. for (index = 0; index < this.tangents.length; index += 4) {
  28118. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28119. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28120. this.tangents[index] = tangentTransformed.x;
  28121. this.tangents[index + 1] = tangentTransformed.y;
  28122. this.tangents[index + 2] = tangentTransformed.z;
  28123. this.tangents[index + 3] = tangentTransformed.w;
  28124. }
  28125. }
  28126. return this;
  28127. };
  28128. /**
  28129. * Merges the passed VertexData into the current one.
  28130. * Returns the modified VertexData.
  28131. */
  28132. VertexData.prototype.merge = function (other, options) {
  28133. options = options || {};
  28134. if (other.indices) {
  28135. if (!this.indices) {
  28136. this.indices = [];
  28137. }
  28138. var offset = this.positions ? this.positions.length / 3 : 0;
  28139. for (var index = 0; index < other.indices.length; index++) {
  28140. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28141. this.indices.push(other.indices[index] + offset);
  28142. }
  28143. }
  28144. this.positions = this._mergeElement(this.positions, other.positions);
  28145. if (!this.positions) {
  28146. return this;
  28147. }
  28148. var count = this.positions.length / 3;
  28149. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28150. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28151. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28152. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28153. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28154. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28155. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28156. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28157. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28158. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28159. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28160. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28161. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28162. return this;
  28163. };
  28164. VertexData.prototype._mergeElement = function (source, other, length) {
  28165. if (length === void 0) { length = 0; }
  28166. if (!other && !source) {
  28167. return null;
  28168. }
  28169. if (!other) {
  28170. return this._mergeElement(source, new Float32Array(source.length), length);
  28171. }
  28172. if (!source) {
  28173. if (length === 0 || length === other.length) {
  28174. return other;
  28175. }
  28176. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28177. }
  28178. var len = other.length + source.length;
  28179. var isSrcTypedArray = source instanceof Float32Array;
  28180. var isOthTypedArray = other instanceof Float32Array;
  28181. // use non-loop method when the source is Float32Array
  28182. if (isSrcTypedArray) {
  28183. var ret32 = new Float32Array(len);
  28184. ret32.set(source);
  28185. ret32.set(other, source.length);
  28186. return ret32;
  28187. // source is number[], when other is also use concat
  28188. }
  28189. else if (!isOthTypedArray) {
  28190. return source.concat(other);
  28191. // source is a number[], but other is a Float32Array, loop required
  28192. }
  28193. else {
  28194. var ret = source.slice(0); // copy source to a separate array
  28195. for (var i = 0, len = other.length; i < len; i++) {
  28196. ret.push(other[i]);
  28197. }
  28198. return ret;
  28199. }
  28200. };
  28201. /**
  28202. * Serializes the VertexData.
  28203. * Returns a serialized object.
  28204. */
  28205. VertexData.prototype.serialize = function () {
  28206. var serializationObject = this.serialize();
  28207. if (this.positions) {
  28208. serializationObject.positions = this.positions;
  28209. }
  28210. if (this.normals) {
  28211. serializationObject.normals = this.normals;
  28212. }
  28213. if (this.tangents) {
  28214. serializationObject.tangents = this.tangents;
  28215. }
  28216. if (this.uvs) {
  28217. serializationObject.uvs = this.uvs;
  28218. }
  28219. if (this.uvs2) {
  28220. serializationObject.uvs2 = this.uvs2;
  28221. }
  28222. if (this.uvs3) {
  28223. serializationObject.uvs3 = this.uvs3;
  28224. }
  28225. if (this.uvs4) {
  28226. serializationObject.uvs4 = this.uvs4;
  28227. }
  28228. if (this.uvs5) {
  28229. serializationObject.uvs5 = this.uvs5;
  28230. }
  28231. if (this.uvs6) {
  28232. serializationObject.uvs6 = this.uvs6;
  28233. }
  28234. if (this.colors) {
  28235. serializationObject.colors = this.colors;
  28236. }
  28237. if (this.matricesIndices) {
  28238. serializationObject.matricesIndices = this.matricesIndices;
  28239. serializationObject.matricesIndices._isExpanded = true;
  28240. }
  28241. if (this.matricesWeights) {
  28242. serializationObject.matricesWeights = this.matricesWeights;
  28243. }
  28244. if (this.matricesIndicesExtra) {
  28245. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28246. serializationObject.matricesIndicesExtra._isExpanded = true;
  28247. }
  28248. if (this.matricesWeightsExtra) {
  28249. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28250. }
  28251. serializationObject.indices = this.indices;
  28252. return serializationObject;
  28253. };
  28254. // Statics
  28255. /**
  28256. * Returns the object VertexData associated to the passed mesh.
  28257. */
  28258. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28259. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28260. };
  28261. /**
  28262. * Returns the object VertexData associated to the passed geometry.
  28263. */
  28264. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28265. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28266. };
  28267. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28268. var result = new VertexData();
  28269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28270. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28271. }
  28272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28273. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28274. }
  28275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28276. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28277. }
  28278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28279. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28280. }
  28281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28282. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28283. }
  28284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28285. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28286. }
  28287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28288. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28289. }
  28290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28291. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28292. }
  28293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28294. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28295. }
  28296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28297. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28298. }
  28299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28300. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28301. }
  28302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28303. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28304. }
  28305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28306. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28307. }
  28308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28309. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28310. }
  28311. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28312. return result;
  28313. };
  28314. /**
  28315. * Creates the vertexData of the Ribbon.
  28316. */
  28317. VertexData.CreateRibbon = function (options) {
  28318. var pathArray = options.pathArray;
  28319. var closeArray = options.closeArray || false;
  28320. var closePath = options.closePath || false;
  28321. var invertUV = options.invertUV || false;
  28322. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28323. var offset = options.offset || defaultOffset;
  28324. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28325. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28326. var customUV = options.uvs;
  28327. var customColors = options.colors;
  28328. var positions = [];
  28329. var indices = [];
  28330. var normals = [];
  28331. var uvs = [];
  28332. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28333. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28334. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28335. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28336. var minlg; // minimal length among all paths from pathArray
  28337. var lg = []; // array of path lengths : nb of vertex per path
  28338. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28339. var p; // path iterator
  28340. var i; // point iterator
  28341. var j; // point iterator
  28342. // if single path in pathArray
  28343. if (pathArray.length < 2) {
  28344. var ar1 = [];
  28345. var ar2 = [];
  28346. for (i = 0; i < pathArray[0].length - offset; i++) {
  28347. ar1.push(pathArray[0][i]);
  28348. ar2.push(pathArray[0][i + offset]);
  28349. }
  28350. pathArray = [ar1, ar2];
  28351. }
  28352. // positions and horizontal distances (u)
  28353. var idc = 0;
  28354. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28355. var path;
  28356. var l;
  28357. minlg = pathArray[0].length;
  28358. var vectlg;
  28359. var dist;
  28360. for (p = 0; p < pathArray.length; p++) {
  28361. uTotalDistance[p] = 0;
  28362. us[p] = [0];
  28363. path = pathArray[p];
  28364. l = path.length;
  28365. minlg = (minlg < l) ? minlg : l;
  28366. j = 0;
  28367. while (j < l) {
  28368. positions.push(path[j].x, path[j].y, path[j].z);
  28369. if (j > 0) {
  28370. vectlg = path[j].subtract(path[j - 1]).length();
  28371. dist = vectlg + uTotalDistance[p];
  28372. us[p].push(dist);
  28373. uTotalDistance[p] = dist;
  28374. }
  28375. j++;
  28376. }
  28377. if (closePath) {
  28378. j--;
  28379. positions.push(path[0].x, path[0].y, path[0].z);
  28380. vectlg = path[j].subtract(path[0]).length();
  28381. dist = vectlg + uTotalDistance[p];
  28382. us[p].push(dist);
  28383. uTotalDistance[p] = dist;
  28384. }
  28385. lg[p] = l + closePathCorr;
  28386. idx[p] = idc;
  28387. idc += (l + closePathCorr);
  28388. }
  28389. // vertical distances (v)
  28390. var path1;
  28391. var path2;
  28392. var vertex1 = null;
  28393. var vertex2 = null;
  28394. for (i = 0; i < minlg + closePathCorr; i++) {
  28395. vTotalDistance[i] = 0;
  28396. vs[i] = [0];
  28397. for (p = 0; p < pathArray.length - 1; p++) {
  28398. path1 = pathArray[p];
  28399. path2 = pathArray[p + 1];
  28400. if (i === minlg) {
  28401. vertex1 = path1[0];
  28402. vertex2 = path2[0];
  28403. }
  28404. else {
  28405. vertex1 = path1[i];
  28406. vertex2 = path2[i];
  28407. }
  28408. vectlg = vertex2.subtract(vertex1).length();
  28409. dist = vectlg + vTotalDistance[i];
  28410. vs[i].push(dist);
  28411. vTotalDistance[i] = dist;
  28412. }
  28413. if (closeArray && vertex2 && vertex1) {
  28414. path1 = pathArray[p];
  28415. path2 = pathArray[0];
  28416. if (i === minlg) {
  28417. vertex2 = path2[0];
  28418. }
  28419. vectlg = vertex2.subtract(vertex1).length();
  28420. dist = vectlg + vTotalDistance[i];
  28421. vTotalDistance[i] = dist;
  28422. }
  28423. }
  28424. // uvs
  28425. var u;
  28426. var v;
  28427. if (customUV) {
  28428. for (p = 0; p < customUV.length; p++) {
  28429. uvs.push(customUV[p].x, customUV[p].y);
  28430. }
  28431. }
  28432. else {
  28433. for (p = 0; p < pathArray.length; p++) {
  28434. for (i = 0; i < minlg + closePathCorr; i++) {
  28435. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28436. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28437. if (invertUV) {
  28438. uvs.push(v, u);
  28439. }
  28440. else {
  28441. uvs.push(u, v);
  28442. }
  28443. }
  28444. }
  28445. }
  28446. // indices
  28447. p = 0; // path index
  28448. var pi = 0; // positions array index
  28449. var l1 = lg[p] - 1; // path1 length
  28450. var l2 = lg[p + 1] - 1; // path2 length
  28451. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28452. var shft = idx[1] - idx[0]; // shift
  28453. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28454. while (pi <= min && p < path1nb) {
  28455. // 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
  28456. indices.push(pi, pi + shft, pi + 1);
  28457. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28458. pi += 1;
  28459. if (pi === min) {
  28460. p++;
  28461. if (p === lg.length - 1) {
  28462. shft = idx[0] - idx[p];
  28463. l1 = lg[p] - 1;
  28464. l2 = lg[0] - 1;
  28465. }
  28466. else {
  28467. shft = idx[p + 1] - idx[p];
  28468. l1 = lg[p] - 1;
  28469. l2 = lg[p + 1] - 1;
  28470. }
  28471. pi = idx[p];
  28472. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28473. }
  28474. }
  28475. // normals
  28476. VertexData.ComputeNormals(positions, indices, normals);
  28477. if (closePath) {
  28478. var indexFirst = 0;
  28479. var indexLast = 0;
  28480. for (p = 0; p < pathArray.length; p++) {
  28481. indexFirst = idx[p] * 3;
  28482. if (p + 1 < pathArray.length) {
  28483. indexLast = (idx[p + 1] - 1) * 3;
  28484. }
  28485. else {
  28486. indexLast = normals.length - 3;
  28487. }
  28488. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28489. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28490. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28491. normals[indexLast] = normals[indexFirst];
  28492. normals[indexLast + 1] = normals[indexFirst + 1];
  28493. normals[indexLast + 2] = normals[indexFirst + 2];
  28494. }
  28495. }
  28496. // sides
  28497. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28498. // Colors
  28499. var colors = null;
  28500. if (customColors) {
  28501. colors = new Float32Array(customColors.length * 4);
  28502. for (var c = 0; c < customColors.length; c++) {
  28503. colors[c * 4] = customColors[c].r;
  28504. colors[c * 4 + 1] = customColors[c].g;
  28505. colors[c * 4 + 2] = customColors[c].b;
  28506. colors[c * 4 + 3] = customColors[c].a;
  28507. }
  28508. }
  28509. // Result
  28510. var vertexData = new VertexData();
  28511. var positions32 = new Float32Array(positions);
  28512. var normals32 = new Float32Array(normals);
  28513. var uvs32 = new Float32Array(uvs);
  28514. vertexData.indices = indices;
  28515. vertexData.positions = positions32;
  28516. vertexData.normals = normals32;
  28517. vertexData.uvs = uvs32;
  28518. if (colors) {
  28519. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28520. }
  28521. if (closePath) {
  28522. vertexData._idx = idx;
  28523. }
  28524. return vertexData;
  28525. };
  28526. /**
  28527. * Creates the VertexData of the Box.
  28528. */
  28529. VertexData.CreateBox = function (options) {
  28530. var normalsSource = [
  28531. new BABYLON.Vector3(0, 0, 1),
  28532. new BABYLON.Vector3(0, 0, -1),
  28533. new BABYLON.Vector3(1, 0, 0),
  28534. new BABYLON.Vector3(-1, 0, 0),
  28535. new BABYLON.Vector3(0, 1, 0),
  28536. new BABYLON.Vector3(0, -1, 0)
  28537. ];
  28538. var indices = [];
  28539. var positions = [];
  28540. var normals = [];
  28541. var uvs = [];
  28542. var width = options.width || options.size || 1;
  28543. var height = options.height || options.size || 1;
  28544. var depth = options.depth || options.size || 1;
  28545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28546. var faceUV = options.faceUV || new Array(6);
  28547. var faceColors = options.faceColors;
  28548. var colors = [];
  28549. // default face colors and UV if undefined
  28550. for (var f = 0; f < 6; f++) {
  28551. if (faceUV[f] === undefined) {
  28552. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28553. }
  28554. if (faceColors && faceColors[f] === undefined) {
  28555. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28556. }
  28557. }
  28558. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28559. // Create each face in turn.
  28560. for (var index = 0; index < normalsSource.length; index++) {
  28561. var normal = normalsSource[index];
  28562. // Get two vectors perpendicular to the face normal and to each other.
  28563. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28564. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28565. // Six indices (two triangles) per face.
  28566. var verticesLength = positions.length / 3;
  28567. indices.push(verticesLength);
  28568. indices.push(verticesLength + 1);
  28569. indices.push(verticesLength + 2);
  28570. indices.push(verticesLength);
  28571. indices.push(verticesLength + 2);
  28572. indices.push(verticesLength + 3);
  28573. // Four vertices per face.
  28574. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28575. positions.push(vertex.x, vertex.y, vertex.z);
  28576. normals.push(normal.x, normal.y, normal.z);
  28577. uvs.push(faceUV[index].z, faceUV[index].w);
  28578. if (faceColors) {
  28579. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28580. }
  28581. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28582. positions.push(vertex.x, vertex.y, vertex.z);
  28583. normals.push(normal.x, normal.y, normal.z);
  28584. uvs.push(faceUV[index].x, faceUV[index].w);
  28585. if (faceColors) {
  28586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28587. }
  28588. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28589. positions.push(vertex.x, vertex.y, vertex.z);
  28590. normals.push(normal.x, normal.y, normal.z);
  28591. uvs.push(faceUV[index].x, faceUV[index].y);
  28592. if (faceColors) {
  28593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28594. }
  28595. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28596. positions.push(vertex.x, vertex.y, vertex.z);
  28597. normals.push(normal.x, normal.y, normal.z);
  28598. uvs.push(faceUV[index].z, faceUV[index].y);
  28599. if (faceColors) {
  28600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28601. }
  28602. }
  28603. // sides
  28604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28605. // Result
  28606. var vertexData = new VertexData();
  28607. vertexData.indices = indices;
  28608. vertexData.positions = positions;
  28609. vertexData.normals = normals;
  28610. vertexData.uvs = uvs;
  28611. if (faceColors) {
  28612. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28613. vertexData.colors = totalColors;
  28614. }
  28615. return vertexData;
  28616. };
  28617. /**
  28618. * Creates the VertexData of the Sphere.
  28619. */
  28620. VertexData.CreateSphere = function (options) {
  28621. var segments = options.segments || 32;
  28622. var diameterX = options.diameterX || options.diameter || 1;
  28623. var diameterY = options.diameterY || options.diameter || 1;
  28624. var diameterZ = options.diameterZ || options.diameter || 1;
  28625. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28626. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28627. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28628. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28629. var totalZRotationSteps = 2 + segments;
  28630. var totalYRotationSteps = 2 * totalZRotationSteps;
  28631. var indices = [];
  28632. var positions = [];
  28633. var normals = [];
  28634. var uvs = [];
  28635. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28636. var normalizedZ = zRotationStep / totalZRotationSteps;
  28637. var angleZ = normalizedZ * Math.PI * slice;
  28638. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28639. var normalizedY = yRotationStep / totalYRotationSteps;
  28640. var angleY = normalizedY * Math.PI * 2 * arc;
  28641. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28642. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28643. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28644. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28645. var vertex = complete.multiply(radius);
  28646. var normal = complete.divide(radius).normalize();
  28647. positions.push(vertex.x, vertex.y, vertex.z);
  28648. normals.push(normal.x, normal.y, normal.z);
  28649. uvs.push(normalizedY, normalizedZ);
  28650. }
  28651. if (zRotationStep > 0) {
  28652. var verticesCount = positions.length / 3;
  28653. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28654. indices.push((firstIndex));
  28655. indices.push((firstIndex + 1));
  28656. indices.push(firstIndex + totalYRotationSteps + 1);
  28657. indices.push((firstIndex + totalYRotationSteps + 1));
  28658. indices.push((firstIndex + 1));
  28659. indices.push((firstIndex + totalYRotationSteps + 2));
  28660. }
  28661. }
  28662. }
  28663. // Sides
  28664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28665. // Result
  28666. var vertexData = new VertexData();
  28667. vertexData.indices = indices;
  28668. vertexData.positions = positions;
  28669. vertexData.normals = normals;
  28670. vertexData.uvs = uvs;
  28671. return vertexData;
  28672. };
  28673. /**
  28674. * Creates the VertexData of the Cylinder or Cone.
  28675. */
  28676. VertexData.CreateCylinder = function (options) {
  28677. var height = options.height || 2;
  28678. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28679. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28680. var tessellation = options.tessellation || 24;
  28681. var subdivisions = options.subdivisions || 1;
  28682. var hasRings = options.hasRings ? true : false;
  28683. var enclose = options.enclose ? true : false;
  28684. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28686. var faceUV = options.faceUV || new Array(3);
  28687. var faceColors = options.faceColors;
  28688. // default face colors and UV if undefined
  28689. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28690. var ringNb = (hasRings) ? subdivisions : 1;
  28691. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28692. var f;
  28693. for (f = 0; f < surfaceNb; f++) {
  28694. if (faceColors && faceColors[f] === undefined) {
  28695. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28696. }
  28697. }
  28698. for (f = 0; f < surfaceNb; f++) {
  28699. if (faceUV && faceUV[f] === undefined) {
  28700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28701. }
  28702. }
  28703. var indices = new Array();
  28704. var positions = new Array();
  28705. var normals = new Array();
  28706. var uvs = new Array();
  28707. var colors = new Array();
  28708. var angle_step = Math.PI * 2 * arc / tessellation;
  28709. var angle;
  28710. var h;
  28711. var radius;
  28712. var tan = (diameterBottom - diameterTop) / 2 / height;
  28713. var ringVertex = BABYLON.Vector3.Zero();
  28714. var ringNormal = BABYLON.Vector3.Zero();
  28715. var ringFirstVertex = BABYLON.Vector3.Zero();
  28716. var ringFirstNormal = BABYLON.Vector3.Zero();
  28717. var quadNormal = BABYLON.Vector3.Zero();
  28718. var Y = BABYLON.Axis.Y;
  28719. // positions, normals, uvs
  28720. var i;
  28721. var j;
  28722. var r;
  28723. var ringIdx = 1;
  28724. var s = 1; // surface index
  28725. var cs = 0;
  28726. var v = 0;
  28727. for (i = 0; i <= subdivisions; i++) {
  28728. h = i / subdivisions;
  28729. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28730. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28731. for (r = 0; r < ringIdx; r++) {
  28732. if (hasRings) {
  28733. s += r;
  28734. }
  28735. if (enclose) {
  28736. s += 2 * r;
  28737. }
  28738. for (j = 0; j <= tessellation; j++) {
  28739. angle = j * angle_step;
  28740. // position
  28741. ringVertex.x = Math.cos(-angle) * radius;
  28742. ringVertex.y = -height / 2 + h * height;
  28743. ringVertex.z = Math.sin(-angle) * radius;
  28744. // normal
  28745. if (diameterTop === 0 && i === subdivisions) {
  28746. // if no top cap, reuse former normals
  28747. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28748. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28749. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28750. }
  28751. else {
  28752. ringNormal.x = ringVertex.x;
  28753. ringNormal.z = ringVertex.z;
  28754. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28755. ringNormal.normalize();
  28756. }
  28757. // keep first ring vertex values for enclose
  28758. if (j === 0) {
  28759. ringFirstVertex.copyFrom(ringVertex);
  28760. ringFirstNormal.copyFrom(ringNormal);
  28761. }
  28762. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28763. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28764. if (hasRings) {
  28765. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28766. }
  28767. else {
  28768. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28769. }
  28770. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28771. if (faceColors) {
  28772. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28773. }
  28774. }
  28775. // if enclose, add four vertices and their dedicated normals
  28776. if (arc !== 1 && enclose) {
  28777. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28778. positions.push(0, ringVertex.y, 0);
  28779. positions.push(0, ringVertex.y, 0);
  28780. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28781. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28782. quadNormal.normalize();
  28783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28784. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28785. quadNormal.normalize();
  28786. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28787. if (hasRings) {
  28788. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28789. }
  28790. else {
  28791. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28792. }
  28793. uvs.push(faceUV[s + 1].x, v);
  28794. uvs.push(faceUV[s + 1].z, v);
  28795. if (hasRings) {
  28796. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28797. }
  28798. else {
  28799. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28800. }
  28801. uvs.push(faceUV[s + 2].x, v);
  28802. uvs.push(faceUV[s + 2].z, v);
  28803. if (faceColors) {
  28804. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28805. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28806. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28807. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28808. }
  28809. }
  28810. if (cs !== s) {
  28811. cs = s;
  28812. }
  28813. }
  28814. }
  28815. // indices
  28816. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28817. var s;
  28818. i = 0;
  28819. for (s = 0; s < subdivisions; s++) {
  28820. var i0 = 0;
  28821. var i1 = 0;
  28822. var i2 = 0;
  28823. var i3 = 0;
  28824. for (j = 0; j < tessellation; j++) {
  28825. i0 = i * (e + 1) + j;
  28826. i1 = (i + 1) * (e + 1) + j;
  28827. i2 = i * (e + 1) + (j + 1);
  28828. i3 = (i + 1) * (e + 1) + (j + 1);
  28829. indices.push(i0, i1, i2);
  28830. indices.push(i3, i2, i1);
  28831. }
  28832. if (arc !== 1 && enclose) {
  28833. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28834. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28835. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28836. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28837. }
  28838. i = (hasRings) ? (i + 2) : (i + 1);
  28839. }
  28840. // Caps
  28841. var createCylinderCap = function (isTop) {
  28842. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28843. if (radius === 0) {
  28844. return;
  28845. }
  28846. // Cap positions, normals & uvs
  28847. var angle;
  28848. var circleVector;
  28849. var i;
  28850. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28851. var c = null;
  28852. if (faceColors) {
  28853. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28854. }
  28855. // cap center
  28856. var vbase = positions.length / 3;
  28857. var offset = isTop ? height / 2 : -height / 2;
  28858. var center = new BABYLON.Vector3(0, offset, 0);
  28859. positions.push(center.x, center.y, center.z);
  28860. normals.push(0, isTop ? 1 : -1, 0);
  28861. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28862. if (c) {
  28863. colors.push(c.r, c.g, c.b, c.a);
  28864. }
  28865. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28866. for (i = 0; i <= tessellation; i++) {
  28867. angle = Math.PI * 2 * i * arc / tessellation;
  28868. var cos = Math.cos(-angle);
  28869. var sin = Math.sin(-angle);
  28870. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28871. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28872. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28873. normals.push(0, isTop ? 1 : -1, 0);
  28874. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28875. if (c) {
  28876. colors.push(c.r, c.g, c.b, c.a);
  28877. }
  28878. }
  28879. // Cap indices
  28880. for (i = 0; i < tessellation; i++) {
  28881. if (!isTop) {
  28882. indices.push(vbase);
  28883. indices.push(vbase + (i + 1));
  28884. indices.push(vbase + (i + 2));
  28885. }
  28886. else {
  28887. indices.push(vbase);
  28888. indices.push(vbase + (i + 2));
  28889. indices.push(vbase + (i + 1));
  28890. }
  28891. }
  28892. };
  28893. // add caps to geometry
  28894. createCylinderCap(false);
  28895. createCylinderCap(true);
  28896. // Sides
  28897. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28898. var vertexData = new VertexData();
  28899. vertexData.indices = indices;
  28900. vertexData.positions = positions;
  28901. vertexData.normals = normals;
  28902. vertexData.uvs = uvs;
  28903. if (faceColors) {
  28904. vertexData.colors = colors;
  28905. }
  28906. return vertexData;
  28907. };
  28908. /**
  28909. * Creates the VertexData of the Torus.
  28910. */
  28911. VertexData.CreateTorus = function (options) {
  28912. var indices = [];
  28913. var positions = [];
  28914. var normals = [];
  28915. var uvs = [];
  28916. var diameter = options.diameter || 1;
  28917. var thickness = options.thickness || 0.5;
  28918. var tessellation = options.tessellation || 16;
  28919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28920. var stride = tessellation + 1;
  28921. for (var i = 0; i <= tessellation; i++) {
  28922. var u = i / tessellation;
  28923. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28924. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28925. for (var j = 0; j <= tessellation; j++) {
  28926. var v = 1 - j / tessellation;
  28927. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28928. var dx = Math.cos(innerAngle);
  28929. var dy = Math.sin(innerAngle);
  28930. // Create a vertex.
  28931. var normal = new BABYLON.Vector3(dx, dy, 0);
  28932. var position = normal.scale(thickness / 2);
  28933. var textureCoordinate = new BABYLON.Vector2(u, v);
  28934. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28935. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28936. positions.push(position.x, position.y, position.z);
  28937. normals.push(normal.x, normal.y, normal.z);
  28938. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28939. // And create indices for two triangles.
  28940. var nextI = (i + 1) % stride;
  28941. var nextJ = (j + 1) % stride;
  28942. indices.push(i * stride + j);
  28943. indices.push(i * stride + nextJ);
  28944. indices.push(nextI * stride + j);
  28945. indices.push(i * stride + nextJ);
  28946. indices.push(nextI * stride + nextJ);
  28947. indices.push(nextI * stride + j);
  28948. }
  28949. }
  28950. // Sides
  28951. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28952. // Result
  28953. var vertexData = new VertexData();
  28954. vertexData.indices = indices;
  28955. vertexData.positions = positions;
  28956. vertexData.normals = normals;
  28957. vertexData.uvs = uvs;
  28958. return vertexData;
  28959. };
  28960. /**
  28961. * Creates the VertexData of the LineSystem.
  28962. */
  28963. VertexData.CreateLineSystem = function (options) {
  28964. var indices = [];
  28965. var positions = [];
  28966. var lines = options.lines;
  28967. var idx = 0;
  28968. for (var l = 0; l < lines.length; l++) {
  28969. var points = lines[l];
  28970. for (var index = 0; index < points.length; index++) {
  28971. positions.push(points[index].x, points[index].y, points[index].z);
  28972. if (index > 0) {
  28973. indices.push(idx - 1);
  28974. indices.push(idx);
  28975. }
  28976. idx++;
  28977. }
  28978. }
  28979. var vertexData = new VertexData();
  28980. vertexData.indices = indices;
  28981. vertexData.positions = positions;
  28982. return vertexData;
  28983. };
  28984. /**
  28985. * Create the VertexData of the DashedLines.
  28986. */
  28987. VertexData.CreateDashedLines = function (options) {
  28988. var dashSize = options.dashSize || 3;
  28989. var gapSize = options.gapSize || 1;
  28990. var dashNb = options.dashNb || 200;
  28991. var points = options.points;
  28992. var positions = new Array();
  28993. var indices = new Array();
  28994. var curvect = BABYLON.Vector3.Zero();
  28995. var lg = 0;
  28996. var nb = 0;
  28997. var shft = 0;
  28998. var dashshft = 0;
  28999. var curshft = 0;
  29000. var idx = 0;
  29001. var i = 0;
  29002. for (i = 0; i < points.length - 1; i++) {
  29003. points[i + 1].subtractToRef(points[i], curvect);
  29004. lg += curvect.length();
  29005. }
  29006. shft = lg / dashNb;
  29007. dashshft = dashSize * shft / (dashSize + gapSize);
  29008. for (i = 0; i < points.length - 1; i++) {
  29009. points[i + 1].subtractToRef(points[i], curvect);
  29010. nb = Math.floor(curvect.length() / shft);
  29011. curvect.normalize();
  29012. for (var j = 0; j < nb; j++) {
  29013. curshft = shft * j;
  29014. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29015. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29016. indices.push(idx, idx + 1);
  29017. idx += 2;
  29018. }
  29019. }
  29020. // Result
  29021. var vertexData = new VertexData();
  29022. vertexData.positions = positions;
  29023. vertexData.indices = indices;
  29024. return vertexData;
  29025. };
  29026. /**
  29027. * Creates the VertexData of the Ground.
  29028. */
  29029. VertexData.CreateGround = function (options) {
  29030. var indices = [];
  29031. var positions = [];
  29032. var normals = [];
  29033. var uvs = [];
  29034. var row, col;
  29035. var width = options.width || 1;
  29036. var height = options.height || 1;
  29037. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29038. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29039. for (row = 0; row <= subdivisionsY; row++) {
  29040. for (col = 0; col <= subdivisionsX; col++) {
  29041. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29042. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29043. positions.push(position.x, position.y, position.z);
  29044. normals.push(normal.x, normal.y, normal.z);
  29045. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29046. }
  29047. }
  29048. for (row = 0; row < subdivisionsY; row++) {
  29049. for (col = 0; col < subdivisionsX; col++) {
  29050. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29051. indices.push(col + 1 + row * (subdivisionsX + 1));
  29052. indices.push(col + row * (subdivisionsX + 1));
  29053. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29054. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29055. indices.push(col + row * (subdivisionsX + 1));
  29056. }
  29057. }
  29058. // Result
  29059. var vertexData = new VertexData();
  29060. vertexData.indices = indices;
  29061. vertexData.positions = positions;
  29062. vertexData.normals = normals;
  29063. vertexData.uvs = uvs;
  29064. return vertexData;
  29065. };
  29066. /**
  29067. * Creates the VertexData of the TiledGround.
  29068. */
  29069. VertexData.CreateTiledGround = function (options) {
  29070. var xmin = options.xmin || -1.0;
  29071. var zmin = options.zmin || -1.0;
  29072. var xmax = options.xmax || 1.0;
  29073. var zmax = options.zmax || 1.0;
  29074. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29075. var precision = options.precision || { w: 1, h: 1 };
  29076. var indices = new Array();
  29077. var positions = new Array();
  29078. var normals = new Array();
  29079. var uvs = new Array();
  29080. var row, col, tileRow, tileCol;
  29081. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29082. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29083. precision.w = (precision.w < 1) ? 1 : precision.w;
  29084. precision.h = (precision.h < 1) ? 1 : precision.h;
  29085. var tileSize = {
  29086. 'w': (xmax - xmin) / subdivisions.w,
  29087. 'h': (zmax - zmin) / subdivisions.h
  29088. };
  29089. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29090. // Indices
  29091. var base = positions.length / 3;
  29092. var rowLength = precision.w + 1;
  29093. for (row = 0; row < precision.h; row++) {
  29094. for (col = 0; col < precision.w; col++) {
  29095. var square = [
  29096. base + col + row * rowLength,
  29097. base + (col + 1) + row * rowLength,
  29098. base + (col + 1) + (row + 1) * rowLength,
  29099. base + col + (row + 1) * rowLength
  29100. ];
  29101. indices.push(square[1]);
  29102. indices.push(square[2]);
  29103. indices.push(square[3]);
  29104. indices.push(square[0]);
  29105. indices.push(square[1]);
  29106. indices.push(square[3]);
  29107. }
  29108. }
  29109. // Position, normals and uvs
  29110. var position = BABYLON.Vector3.Zero();
  29111. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29112. for (row = 0; row <= precision.h; row++) {
  29113. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29114. for (col = 0; col <= precision.w; col++) {
  29115. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29116. position.y = 0;
  29117. positions.push(position.x, position.y, position.z);
  29118. normals.push(normal.x, normal.y, normal.z);
  29119. uvs.push(col / precision.w, row / precision.h);
  29120. }
  29121. }
  29122. }
  29123. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29124. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29125. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29126. }
  29127. }
  29128. // Result
  29129. var vertexData = new VertexData();
  29130. vertexData.indices = indices;
  29131. vertexData.positions = positions;
  29132. vertexData.normals = normals;
  29133. vertexData.uvs = uvs;
  29134. return vertexData;
  29135. };
  29136. /**
  29137. * Creates the VertexData of the Ground designed from a heightmap.
  29138. */
  29139. VertexData.CreateGroundFromHeightMap = function (options) {
  29140. var indices = [];
  29141. var positions = [];
  29142. var normals = [];
  29143. var uvs = [];
  29144. var row, col;
  29145. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29146. // Vertices
  29147. for (row = 0; row <= options.subdivisions; row++) {
  29148. for (col = 0; col <= options.subdivisions; col++) {
  29149. 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));
  29150. // Compute height
  29151. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29152. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29153. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29154. var r = options.buffer[pos] / 255.0;
  29155. var g = options.buffer[pos + 1] / 255.0;
  29156. var b = options.buffer[pos + 2] / 255.0;
  29157. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29158. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29159. // Add vertex
  29160. positions.push(position.x, position.y, position.z);
  29161. normals.push(0, 0, 0);
  29162. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29163. }
  29164. }
  29165. // Indices
  29166. for (row = 0; row < options.subdivisions; row++) {
  29167. for (col = 0; col < options.subdivisions; col++) {
  29168. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29169. indices.push(col + 1 + row * (options.subdivisions + 1));
  29170. indices.push(col + row * (options.subdivisions + 1));
  29171. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29172. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29173. indices.push(col + row * (options.subdivisions + 1));
  29174. }
  29175. }
  29176. // Normals
  29177. VertexData.ComputeNormals(positions, indices, normals);
  29178. // Result
  29179. var vertexData = new VertexData();
  29180. vertexData.indices = indices;
  29181. vertexData.positions = positions;
  29182. vertexData.normals = normals;
  29183. vertexData.uvs = uvs;
  29184. return vertexData;
  29185. };
  29186. /**
  29187. * Creates the VertexData of the Plane.
  29188. */
  29189. VertexData.CreatePlane = function (options) {
  29190. var indices = [];
  29191. var positions = [];
  29192. var normals = [];
  29193. var uvs = [];
  29194. var width = options.width || options.size || 1;
  29195. var height = options.height || options.size || 1;
  29196. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29197. // Vertices
  29198. var halfWidth = width / 2.0;
  29199. var halfHeight = height / 2.0;
  29200. positions.push(-halfWidth, -halfHeight, 0);
  29201. normals.push(0, 0, -1.0);
  29202. uvs.push(0.0, 0.0);
  29203. positions.push(halfWidth, -halfHeight, 0);
  29204. normals.push(0, 0, -1.0);
  29205. uvs.push(1.0, 0.0);
  29206. positions.push(halfWidth, halfHeight, 0);
  29207. normals.push(0, 0, -1.0);
  29208. uvs.push(1.0, 1.0);
  29209. positions.push(-halfWidth, halfHeight, 0);
  29210. normals.push(0, 0, -1.0);
  29211. uvs.push(0.0, 1.0);
  29212. // Indices
  29213. indices.push(0);
  29214. indices.push(1);
  29215. indices.push(2);
  29216. indices.push(0);
  29217. indices.push(2);
  29218. indices.push(3);
  29219. // Sides
  29220. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29221. // Result
  29222. var vertexData = new VertexData();
  29223. vertexData.indices = indices;
  29224. vertexData.positions = positions;
  29225. vertexData.normals = normals;
  29226. vertexData.uvs = uvs;
  29227. return vertexData;
  29228. };
  29229. /**
  29230. * Creates the VertexData of the Disc or regular Polygon.
  29231. */
  29232. VertexData.CreateDisc = function (options) {
  29233. var positions = new Array();
  29234. var indices = new Array();
  29235. var normals = new Array();
  29236. var uvs = new Array();
  29237. var radius = options.radius || 0.5;
  29238. var tessellation = options.tessellation || 64;
  29239. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29240. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29241. // positions and uvs
  29242. positions.push(0, 0, 0); // disc center first
  29243. uvs.push(0.5, 0.5);
  29244. var theta = Math.PI * 2 * arc;
  29245. var step = theta / tessellation;
  29246. for (var a = 0; a < theta; a += step) {
  29247. var x = Math.cos(a);
  29248. var y = Math.sin(a);
  29249. var u = (x + 1) / 2;
  29250. var v = (1 - y) / 2;
  29251. positions.push(radius * x, radius * y, 0);
  29252. uvs.push(u, v);
  29253. }
  29254. if (arc === 1) {
  29255. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29256. uvs.push(uvs[2], uvs[3]);
  29257. }
  29258. //indices
  29259. var vertexNb = positions.length / 3;
  29260. for (var i = 1; i < vertexNb - 1; i++) {
  29261. indices.push(i + 1, 0, i);
  29262. }
  29263. // result
  29264. VertexData.ComputeNormals(positions, indices, normals);
  29265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29266. var vertexData = new VertexData();
  29267. vertexData.indices = indices;
  29268. vertexData.positions = positions;
  29269. vertexData.normals = normals;
  29270. vertexData.uvs = uvs;
  29271. return vertexData;
  29272. };
  29273. /**
  29274. * Re-creates the VertexData of the Polygon for sideOrientation.
  29275. */
  29276. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29277. var faceUV = fUV || new Array(3);
  29278. var faceColors = fColors;
  29279. var colors = [];
  29280. // default face colors and UV if undefined
  29281. for (var f = 0; f < 3; f++) {
  29282. if (faceUV[f] === undefined) {
  29283. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29284. }
  29285. if (faceColors && faceColors[f] === undefined) {
  29286. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29287. }
  29288. }
  29289. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29290. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29291. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29292. var indices = polygon.getIndices();
  29293. // set face colours and textures
  29294. var idx = 0;
  29295. var face = 0;
  29296. for (var index = 0; index < normals.length; index += 3) {
  29297. //Edge Face no. 1
  29298. if (Math.abs(normals[index + 1]) < 0.001) {
  29299. face = 1;
  29300. }
  29301. //Top Face no. 0
  29302. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29303. face = 0;
  29304. }
  29305. //Bottom Face no. 2
  29306. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29307. face = 2;
  29308. }
  29309. idx = index / 3;
  29310. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29311. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29312. if (faceColors) {
  29313. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29314. }
  29315. }
  29316. // sides
  29317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29318. // Result
  29319. var vertexData = new VertexData();
  29320. vertexData.indices = indices;
  29321. vertexData.positions = positions;
  29322. vertexData.normals = normals;
  29323. vertexData.uvs = uvs;
  29324. if (faceColors) {
  29325. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29326. vertexData.colors = totalColors;
  29327. }
  29328. return vertexData;
  29329. };
  29330. /**
  29331. * Creates the VertexData of the IcoSphere.
  29332. */
  29333. VertexData.CreateIcoSphere = function (options) {
  29334. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29335. var radius = options.radius || 1;
  29336. var flat = (options.flat === undefined) ? true : options.flat;
  29337. var subdivisions = options.subdivisions || 4;
  29338. var radiusX = options.radiusX || radius;
  29339. var radiusY = options.radiusY || radius;
  29340. var radiusZ = options.radiusZ || radius;
  29341. var t = (1 + Math.sqrt(5)) / 2;
  29342. // 12 vertex x,y,z
  29343. var ico_vertices = [
  29344. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29345. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29346. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29347. ];
  29348. // index of 3 vertex makes a face of icopshere
  29349. var ico_indices = [
  29350. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29351. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29352. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29353. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29354. ];
  29355. // vertex for uv have aliased position, not for UV
  29356. var vertices_unalias_id = [
  29357. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29358. // vertex alias
  29359. 0,
  29360. 2,
  29361. 3,
  29362. 3,
  29363. 3,
  29364. 4,
  29365. 7,
  29366. 8,
  29367. 9,
  29368. 9,
  29369. 10,
  29370. 11 // 23: B + 12
  29371. ];
  29372. // uv as integer step (not pixels !)
  29373. var ico_vertexuv = [
  29374. 5, 1, 3, 1, 6, 4, 0, 0,
  29375. 5, 3, 4, 2, 2, 2, 4, 0,
  29376. 2, 0, 1, 1, 6, 0, 6, 2,
  29377. // vertex alias (for same vertex on different faces)
  29378. 0, 4,
  29379. 3, 3,
  29380. 4, 4,
  29381. 3, 1,
  29382. 4, 2,
  29383. 4, 4,
  29384. 0, 2,
  29385. 1, 1,
  29386. 2, 2,
  29387. 3, 3,
  29388. 1, 3,
  29389. 2, 4 // 23: B + 12
  29390. ];
  29391. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29392. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29393. // First island of uv mapping
  29394. // v = 4h 3+ 2
  29395. // v = 3h 9+ 4
  29396. // v = 2h 9+ 5 B
  29397. // v = 1h 9 1 0
  29398. // v = 0h 3 8 7 A
  29399. // u = 0 1 2 3 4 5 6 *a
  29400. // Second island of uv mapping
  29401. // v = 4h 0+ B+ 4+
  29402. // v = 3h A+ 2+
  29403. // v = 2h 7+ 6 3+
  29404. // v = 1h 8+ 3+
  29405. // v = 0h
  29406. // u = 0 1 2 3 4 5 6 *a
  29407. // Face layout on texture UV mapping
  29408. // ============
  29409. // \ 4 /\ 16 / ======
  29410. // \ / \ / /\ 11 /
  29411. // \/ 7 \/ / \ /
  29412. // ======= / 10 \/
  29413. // /\ 17 /\ =======
  29414. // / \ / \ \ 15 /\
  29415. // / 8 \/ 12 \ \ / \
  29416. // ============ \/ 6 \
  29417. // \ 18 /\ ============
  29418. // \ / \ \ 5 /\ 0 /
  29419. // \/ 13 \ \ / \ /
  29420. // ======= \/ 1 \/
  29421. // =============
  29422. // /\ 19 /\ 2 /\
  29423. // / \ / \ / \
  29424. // / 14 \/ 9 \/ 3 \
  29425. // ===================
  29426. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29427. var ustep = 138 / 1024;
  29428. var vstep = 239 / 1024;
  29429. var uoffset = 60 / 1024;
  29430. var voffset = 26 / 1024;
  29431. // Second island should have margin, not to touch the first island
  29432. // avoid any borderline artefact in pixel rounding
  29433. var island_u_offset = -40 / 1024;
  29434. var island_v_offset = +20 / 1024;
  29435. // face is either island 0 or 1 :
  29436. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29437. var island = [
  29438. 0, 0, 0, 0, 1,
  29439. 0, 0, 1, 1, 0,
  29440. 0, 0, 1, 1, 0,
  29441. 0, 1, 1, 1, 0 // 15 - 19
  29442. ];
  29443. var indices = new Array();
  29444. var positions = new Array();
  29445. var normals = new Array();
  29446. var uvs = new Array();
  29447. var current_indice = 0;
  29448. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29449. var face_vertex_pos = new Array(3);
  29450. var face_vertex_uv = new Array(3);
  29451. var v012;
  29452. for (v012 = 0; v012 < 3; v012++) {
  29453. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29454. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29455. }
  29456. // create all with normals
  29457. for (var face = 0; face < 20; face++) {
  29458. // 3 vertex per face
  29459. for (v012 = 0; v012 < 3; v012++) {
  29460. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29461. var v_id = ico_indices[3 * face + v012];
  29462. // vertex have 3D position (x,y,z)
  29463. 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]);
  29464. // Normalize to get normal, then scale to radius
  29465. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29466. // uv Coordinates from vertex ID
  29467. 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);
  29468. }
  29469. // Subdivide the face (interpolate pos, norm, uv)
  29470. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29471. // - norm is linear interpolation of vertex corner normal
  29472. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29473. // - uv is linear interpolation
  29474. //
  29475. // Topology is as below for sub-divide by 2
  29476. // vertex shown as v0,v1,v2
  29477. // interp index is i1 to progress in range [v0,v1[
  29478. // interp index is i2 to progress in range [v0,v2[
  29479. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29480. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29481. //
  29482. //
  29483. // i2 v2
  29484. // ^ ^
  29485. // / / \
  29486. // / / \
  29487. // / / \
  29488. // / / (0,1) \
  29489. // / #---------\
  29490. // / / \ (0,0)'/ \
  29491. // / / \ / \
  29492. // / / \ / \
  29493. // / / (0,0) \ / (1,0) \
  29494. // / #---------#---------\
  29495. // v0 v1
  29496. //
  29497. // --------------------> i1
  29498. //
  29499. // interp of (i1,i2):
  29500. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29501. // along i1 : lerp(x0,x1, i1/(S-i2))
  29502. //
  29503. // centroid of triangle is needed to get help normal computation
  29504. // (c1,c2) are used for centroid location
  29505. var interp_vertex = function (i1, i2, c1, c2) {
  29506. // vertex is interpolated from
  29507. // - face_vertex_pos[0..2]
  29508. // - face_vertex_uv[0..2]
  29509. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29510. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29511. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29512. pos_interp.normalize();
  29513. var vertex_normal;
  29514. if (flat) {
  29515. // in flat mode, recalculate normal as face centroid normal
  29516. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29517. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29518. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29519. }
  29520. else {
  29521. // in smooth mode, recalculate normal from each single vertex position
  29522. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29523. }
  29524. // Vertex normal need correction due to X,Y,Z radius scaling
  29525. vertex_normal.x /= radiusX;
  29526. vertex_normal.y /= radiusY;
  29527. vertex_normal.z /= radiusZ;
  29528. vertex_normal.normalize();
  29529. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29530. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29531. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29532. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29533. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29534. uvs.push(uv_interp.x, uv_interp.y);
  29535. // push each vertex has member of a face
  29536. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29537. indices.push(current_indice);
  29538. current_indice++;
  29539. };
  29540. for (var i2 = 0; i2 < subdivisions; i2++) {
  29541. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29542. // face : (i1,i2) for /\ :
  29543. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29544. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29545. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29546. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29547. if (i1 + i2 + 1 < subdivisions) {
  29548. // face : (i1,i2)' for \/ :
  29549. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29550. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29551. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29552. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29553. }
  29554. }
  29555. }
  29556. }
  29557. // Sides
  29558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29559. // Result
  29560. var vertexData = new VertexData();
  29561. vertexData.indices = indices;
  29562. vertexData.positions = positions;
  29563. vertexData.normals = normals;
  29564. vertexData.uvs = uvs;
  29565. return vertexData;
  29566. };
  29567. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29568. /**
  29569. * Creates the VertexData of the Polyhedron.
  29570. */
  29571. VertexData.CreatePolyhedron = function (options) {
  29572. // provided polyhedron types :
  29573. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29574. // 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)
  29575. var polyhedra = [];
  29576. 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]] };
  29577. 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]] };
  29578. polyhedra[2] = {
  29579. 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]],
  29580. 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]]
  29581. };
  29582. polyhedra[3] = {
  29583. 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]],
  29584. 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]]
  29585. };
  29586. polyhedra[4] = {
  29587. 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]],
  29588. 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]]
  29589. };
  29590. 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]] };
  29591. 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]] };
  29592. 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]] };
  29593. 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]] };
  29594. 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]] };
  29595. 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]] };
  29596. 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]] };
  29597. 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]] };
  29598. 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]] };
  29599. polyhedra[14] = {
  29600. 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]],
  29601. 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]]
  29602. };
  29603. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29604. var size = options.size;
  29605. var sizeX = options.sizeX || size || 1;
  29606. var sizeY = options.sizeY || size || 1;
  29607. var sizeZ = options.sizeZ || size || 1;
  29608. var data = options.custom || polyhedra[type];
  29609. var nbfaces = data.face.length;
  29610. var faceUV = options.faceUV || new Array(nbfaces);
  29611. var faceColors = options.faceColors;
  29612. var flat = (options.flat === undefined) ? true : options.flat;
  29613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29614. var positions = new Array();
  29615. var indices = new Array();
  29616. var normals = new Array();
  29617. var uvs = new Array();
  29618. var colors = new Array();
  29619. var index = 0;
  29620. var faceIdx = 0; // face cursor in the array "indexes"
  29621. var indexes = new Array();
  29622. var i = 0;
  29623. var f = 0;
  29624. var u, v, ang, x, y, tmp;
  29625. // default face colors and UV if undefined
  29626. if (flat) {
  29627. for (f = 0; f < nbfaces; f++) {
  29628. if (faceColors && faceColors[f] === undefined) {
  29629. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29630. }
  29631. if (faceUV && faceUV[f] === undefined) {
  29632. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29633. }
  29634. }
  29635. }
  29636. if (!flat) {
  29637. for (i = 0; i < data.vertex.length; i++) {
  29638. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29639. uvs.push(0, 0);
  29640. }
  29641. for (f = 0; f < nbfaces; f++) {
  29642. for (i = 0; i < data.face[f].length - 2; i++) {
  29643. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29644. }
  29645. }
  29646. }
  29647. else {
  29648. for (f = 0; f < nbfaces; f++) {
  29649. var fl = data.face[f].length; // number of vertices of the current face
  29650. ang = 2 * Math.PI / fl;
  29651. x = 0.5 * Math.tan(ang / 2);
  29652. y = 0.5;
  29653. // positions, uvs, colors
  29654. for (i = 0; i < fl; i++) {
  29655. // positions
  29656. 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);
  29657. indexes.push(index);
  29658. index++;
  29659. // uvs
  29660. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29661. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29662. uvs.push(u, v);
  29663. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29664. y = x * Math.sin(ang) + y * Math.cos(ang);
  29665. x = tmp;
  29666. // colors
  29667. if (faceColors) {
  29668. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29669. }
  29670. }
  29671. // indices from indexes
  29672. for (i = 0; i < fl - 2; i++) {
  29673. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29674. }
  29675. faceIdx += fl;
  29676. }
  29677. }
  29678. VertexData.ComputeNormals(positions, indices, normals);
  29679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29680. var vertexData = new VertexData();
  29681. vertexData.positions = positions;
  29682. vertexData.indices = indices;
  29683. vertexData.normals = normals;
  29684. vertexData.uvs = uvs;
  29685. if (faceColors && flat) {
  29686. vertexData.colors = colors;
  29687. }
  29688. return vertexData;
  29689. };
  29690. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29691. /**
  29692. * Creates the VertexData of the Torus Knot.
  29693. */
  29694. VertexData.CreateTorusKnot = function (options) {
  29695. var indices = new Array();
  29696. var positions = new Array();
  29697. var normals = new Array();
  29698. var uvs = new Array();
  29699. var radius = options.radius || 2;
  29700. var tube = options.tube || 0.5;
  29701. var radialSegments = options.radialSegments || 32;
  29702. var tubularSegments = options.tubularSegments || 32;
  29703. var p = options.p || 2;
  29704. var q = options.q || 3;
  29705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29706. // Helper
  29707. var getPos = function (angle) {
  29708. var cu = Math.cos(angle);
  29709. var su = Math.sin(angle);
  29710. var quOverP = q / p * angle;
  29711. var cs = Math.cos(quOverP);
  29712. var tx = radius * (2 + cs) * 0.5 * cu;
  29713. var ty = radius * (2 + cs) * su * 0.5;
  29714. var tz = radius * Math.sin(quOverP) * 0.5;
  29715. return new BABYLON.Vector3(tx, ty, tz);
  29716. };
  29717. // Vertices
  29718. var i;
  29719. var j;
  29720. for (i = 0; i <= radialSegments; i++) {
  29721. var modI = i % radialSegments;
  29722. var u = modI / radialSegments * 2 * p * Math.PI;
  29723. var p1 = getPos(u);
  29724. var p2 = getPos(u + 0.01);
  29725. var tang = p2.subtract(p1);
  29726. var n = p2.add(p1);
  29727. var bitan = BABYLON.Vector3.Cross(tang, n);
  29728. n = BABYLON.Vector3.Cross(bitan, tang);
  29729. bitan.normalize();
  29730. n.normalize();
  29731. for (j = 0; j < tubularSegments; j++) {
  29732. var modJ = j % tubularSegments;
  29733. var v = modJ / tubularSegments * 2 * Math.PI;
  29734. var cx = -tube * Math.cos(v);
  29735. var cy = tube * Math.sin(v);
  29736. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29737. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29738. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29739. uvs.push(i / radialSegments);
  29740. uvs.push(j / tubularSegments);
  29741. }
  29742. }
  29743. for (i = 0; i < radialSegments; i++) {
  29744. for (j = 0; j < tubularSegments; j++) {
  29745. var jNext = (j + 1) % tubularSegments;
  29746. var a = i * tubularSegments + j;
  29747. var b = (i + 1) * tubularSegments + j;
  29748. var c = (i + 1) * tubularSegments + jNext;
  29749. var d = i * tubularSegments + jNext;
  29750. indices.push(d);
  29751. indices.push(b);
  29752. indices.push(a);
  29753. indices.push(d);
  29754. indices.push(c);
  29755. indices.push(b);
  29756. }
  29757. }
  29758. // Normals
  29759. VertexData.ComputeNormals(positions, indices, normals);
  29760. // Sides
  29761. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29762. // Result
  29763. var vertexData = new VertexData();
  29764. vertexData.indices = indices;
  29765. vertexData.positions = positions;
  29766. vertexData.normals = normals;
  29767. vertexData.uvs = uvs;
  29768. return vertexData;
  29769. };
  29770. // Tools
  29771. /**
  29772. * @param {any} - positions (number[] or Float32Array)
  29773. * @param {any} - indices (number[] or Uint16Array)
  29774. * @param {any} - normals (number[] or Float32Array)
  29775. * options (optional) :
  29776. * facetPositions : optional array of facet positions (vector3)
  29777. * facetNormals : optional array of facet normals (vector3)
  29778. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29779. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29780. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29781. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29782. * bInfo : optional bounding info, required for facetPartitioning computation
  29783. */
  29784. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29785. // temporary scalar variables
  29786. var index = 0; // facet index
  29787. var p1p2x = 0.0; // p1p2 vector x coordinate
  29788. var p1p2y = 0.0; // p1p2 vector y coordinate
  29789. var p1p2z = 0.0; // p1p2 vector z coordinate
  29790. var p3p2x = 0.0; // p3p2 vector x coordinate
  29791. var p3p2y = 0.0; // p3p2 vector y coordinate
  29792. var p3p2z = 0.0; // p3p2 vector z coordinate
  29793. var faceNormalx = 0.0; // facet normal x coordinate
  29794. var faceNormaly = 0.0; // facet normal y coordinate
  29795. var faceNormalz = 0.0; // facet normal z coordinate
  29796. var length = 0.0; // facet normal length before normalization
  29797. var v1x = 0; // vector1 x index in the positions array
  29798. var v1y = 0; // vector1 y index in the positions array
  29799. var v1z = 0; // vector1 z index in the positions array
  29800. var v2x = 0; // vector2 x index in the positions array
  29801. var v2y = 0; // vector2 y index in the positions array
  29802. var v2z = 0; // vector2 z index in the positions array
  29803. var v3x = 0; // vector3 x index in the positions array
  29804. var v3y = 0; // vector3 y index in the positions array
  29805. var v3z = 0; // vector3 z index in the positions array
  29806. var computeFacetNormals = false;
  29807. var computeFacetPositions = false;
  29808. var computeFacetPartitioning = false;
  29809. var faceNormalSign = 1;
  29810. var ratio = 0;
  29811. if (options) {
  29812. computeFacetNormals = (options.facetNormals) ? true : false;
  29813. computeFacetPositions = (options.facetPositions) ? true : false;
  29814. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  29815. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  29816. ratio = options.ratio || 0;
  29817. }
  29818. // facetPartitioning reinit if needed
  29819. var xSubRatio = 0;
  29820. var ySubRatio = 0;
  29821. var zSubRatio = 0;
  29822. var subSq = 0;
  29823. if (computeFacetPartitioning && options && options.bbSize) {
  29824. var ox = 0; // X partitioning index for facet position
  29825. var oy = 0; // Y partinioning index for facet position
  29826. var oz = 0; // Z partinioning index for facet position
  29827. var b1x = 0; // X partitioning index for facet v1 vertex
  29828. var b1y = 0; // Y partitioning index for facet v1 vertex
  29829. var b1z = 0; // z partitioning index for facet v1 vertex
  29830. var b2x = 0; // X partitioning index for facet v2 vertex
  29831. var b2y = 0; // Y partitioning index for facet v2 vertex
  29832. var b2z = 0; // Z partitioning index for facet v2 vertex
  29833. var b3x = 0; // X partitioning index for facet v3 vertex
  29834. var b3y = 0; // Y partitioning index for facet v3 vertex
  29835. var b3z = 0; // Z partitioning index for facet v3 vertex
  29836. var block_idx_o = 0; // facet barycenter block index
  29837. var block_idx_v1 = 0; // v1 vertex block index
  29838. var block_idx_v2 = 0; // v2 vertex block index
  29839. var block_idx_v3 = 0; // v3 vertex block index
  29840. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  29841. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  29842. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  29843. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  29844. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  29845. subSq = options.subDiv.max * options.subDiv.max;
  29846. options.facetPartitioning.length = 0;
  29847. }
  29848. // reset the normals
  29849. for (index = 0; index < positions.length; index++) {
  29850. normals[index] = 0.0;
  29851. }
  29852. // Loop : 1 indice triplet = 1 facet
  29853. var nbFaces = indices.length / 3;
  29854. for (index = 0; index < nbFaces; index++) {
  29855. // get the indexes of the coordinates of each vertex of the facet
  29856. v1x = indices[index * 3] * 3;
  29857. v1y = v1x + 1;
  29858. v1z = v1x + 2;
  29859. v2x = indices[index * 3 + 1] * 3;
  29860. v2y = v2x + 1;
  29861. v2z = v2x + 2;
  29862. v3x = indices[index * 3 + 2] * 3;
  29863. v3y = v3x + 1;
  29864. v3z = v3x + 2;
  29865. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  29866. p1p2y = positions[v1y] - positions[v2y];
  29867. p1p2z = positions[v1z] - positions[v2z];
  29868. p3p2x = positions[v3x] - positions[v2x];
  29869. p3p2y = positions[v3y] - positions[v2y];
  29870. p3p2z = positions[v3z] - positions[v2z];
  29871. // compute the face normal with the cross product
  29872. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  29873. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  29874. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  29875. // normalize this normal and store it in the array facetData
  29876. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29877. length = (length === 0) ? 1.0 : length;
  29878. faceNormalx /= length;
  29879. faceNormaly /= length;
  29880. faceNormalz /= length;
  29881. if (computeFacetNormals && options) {
  29882. options.facetNormals[index].x = faceNormalx;
  29883. options.facetNormals[index].y = faceNormaly;
  29884. options.facetNormals[index].z = faceNormalz;
  29885. }
  29886. if (computeFacetPositions && options) {
  29887. // compute and the facet barycenter coordinates in the array facetPositions
  29888. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  29889. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  29890. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  29891. }
  29892. if (computeFacetPartitioning && options) {
  29893. // store the facet indexes in arrays in the main facetPartitioning array :
  29894. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  29895. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  29896. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  29897. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  29898. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29899. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29900. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29901. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29902. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29903. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29904. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  29905. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  29906. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  29907. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  29908. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  29909. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  29910. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  29911. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  29912. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  29913. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  29914. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  29915. // push each facet index in each block containing the vertex
  29916. options.facetPartitioning[block_idx_v1].push(index);
  29917. if (block_idx_v2 != block_idx_v1) {
  29918. options.facetPartitioning[block_idx_v2].push(index);
  29919. }
  29920. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  29921. options.facetPartitioning[block_idx_v3].push(index);
  29922. }
  29923. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  29924. options.facetPartitioning[block_idx_o].push(index);
  29925. }
  29926. }
  29927. // compute the normals anyway
  29928. normals[v1x] += faceNormalx; // accumulate all the normals per face
  29929. normals[v1y] += faceNormaly;
  29930. normals[v1z] += faceNormalz;
  29931. normals[v2x] += faceNormalx;
  29932. normals[v2y] += faceNormaly;
  29933. normals[v2z] += faceNormalz;
  29934. normals[v3x] += faceNormalx;
  29935. normals[v3y] += faceNormaly;
  29936. normals[v3z] += faceNormalz;
  29937. }
  29938. // last normalization of each normal
  29939. for (index = 0; index < normals.length / 3; index++) {
  29940. faceNormalx = normals[index * 3];
  29941. faceNormaly = normals[index * 3 + 1];
  29942. faceNormalz = normals[index * 3 + 2];
  29943. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29944. length = (length === 0) ? 1.0 : length;
  29945. faceNormalx /= length;
  29946. faceNormaly /= length;
  29947. faceNormalz /= length;
  29948. normals[index * 3] = faceNormalx;
  29949. normals[index * 3 + 1] = faceNormaly;
  29950. normals[index * 3 + 2] = faceNormalz;
  29951. }
  29952. };
  29953. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  29954. var li = indices.length;
  29955. var ln = normals.length;
  29956. var i;
  29957. var n;
  29958. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29959. switch (sideOrientation) {
  29960. case BABYLON.Mesh.FRONTSIDE:
  29961. // nothing changed
  29962. break;
  29963. case BABYLON.Mesh.BACKSIDE:
  29964. var tmp;
  29965. // indices
  29966. for (i = 0; i < li; i += 3) {
  29967. tmp = indices[i];
  29968. indices[i] = indices[i + 2];
  29969. indices[i + 2] = tmp;
  29970. }
  29971. // normals
  29972. for (n = 0; n < ln; n++) {
  29973. normals[n] = -normals[n];
  29974. }
  29975. break;
  29976. case BABYLON.Mesh.DOUBLESIDE:
  29977. // positions
  29978. var lp = positions.length;
  29979. var l = lp / 3;
  29980. for (var p = 0; p < lp; p++) {
  29981. positions[lp + p] = positions[p];
  29982. }
  29983. // indices
  29984. for (i = 0; i < li; i += 3) {
  29985. indices[i + li] = indices[i + 2] + l;
  29986. indices[i + 1 + li] = indices[i + 1] + l;
  29987. indices[i + 2 + li] = indices[i] + l;
  29988. }
  29989. // normals
  29990. for (n = 0; n < ln; n++) {
  29991. normals[ln + n] = -normals[n];
  29992. }
  29993. // uvs
  29994. var lu = uvs.length;
  29995. var u = 0;
  29996. for (u = 0; u < lu; u++) {
  29997. uvs[u + lu] = uvs[u];
  29998. }
  29999. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30000. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30001. u = 0;
  30002. for (i = 0; i < lu / 2; i++) {
  30003. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30004. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30005. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30006. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30007. u += 2;
  30008. }
  30009. break;
  30010. }
  30011. };
  30012. /**
  30013. * Creates a new VertexData from the imported parameters.
  30014. */
  30015. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30016. var vertexData = new VertexData();
  30017. // positions
  30018. var positions = parsedVertexData.positions;
  30019. if (positions) {
  30020. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30021. }
  30022. // normals
  30023. var normals = parsedVertexData.normals;
  30024. if (normals) {
  30025. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30026. }
  30027. // tangents
  30028. var tangents = parsedVertexData.tangents;
  30029. if (tangents) {
  30030. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30031. }
  30032. // uvs
  30033. var uvs = parsedVertexData.uvs;
  30034. if (uvs) {
  30035. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30036. }
  30037. // uv2s
  30038. var uv2s = parsedVertexData.uv2s;
  30039. if (uv2s) {
  30040. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30041. }
  30042. // uv3s
  30043. var uv3s = parsedVertexData.uv3s;
  30044. if (uv3s) {
  30045. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30046. }
  30047. // uv4s
  30048. var uv4s = parsedVertexData.uv4s;
  30049. if (uv4s) {
  30050. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30051. }
  30052. // uv5s
  30053. var uv5s = parsedVertexData.uv5s;
  30054. if (uv5s) {
  30055. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30056. }
  30057. // uv6s
  30058. var uv6s = parsedVertexData.uv6s;
  30059. if (uv6s) {
  30060. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30061. }
  30062. // colors
  30063. var colors = parsedVertexData.colors;
  30064. if (colors) {
  30065. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30066. }
  30067. // matricesIndices
  30068. var matricesIndices = parsedVertexData.matricesIndices;
  30069. if (matricesIndices) {
  30070. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30071. }
  30072. // matricesWeights
  30073. var matricesWeights = parsedVertexData.matricesWeights;
  30074. if (matricesWeights) {
  30075. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30076. }
  30077. // indices
  30078. var indices = parsedVertexData.indices;
  30079. if (indices) {
  30080. vertexData.indices = indices;
  30081. }
  30082. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30083. };
  30084. return VertexData;
  30085. }());
  30086. BABYLON.VertexData = VertexData;
  30087. })(BABYLON || (BABYLON = {}));
  30088. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30089. var BABYLON;
  30090. (function (BABYLON) {
  30091. var Geometry = /** @class */ (function () {
  30092. function Geometry(id, scene, vertexData, updatable, mesh) {
  30093. if (updatable === void 0) { updatable = false; }
  30094. if (mesh === void 0) { mesh = null; }
  30095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30096. this._totalVertices = 0;
  30097. this._isDisposed = false;
  30098. this._indexBufferIsUpdatable = false;
  30099. this.id = id;
  30100. this._engine = scene.getEngine();
  30101. this._meshes = [];
  30102. this._scene = scene;
  30103. //Init vertex buffer cache
  30104. this._vertexBuffers = {};
  30105. this._indices = [];
  30106. this._updatable = updatable;
  30107. // vertexData
  30108. if (vertexData) {
  30109. this.setAllVerticesData(vertexData, updatable);
  30110. }
  30111. else {
  30112. this._totalVertices = 0;
  30113. this._indices = [];
  30114. }
  30115. if (this._engine.getCaps().vertexArrayObject) {
  30116. this._vertexArrayObjects = {};
  30117. }
  30118. // applyToMesh
  30119. if (mesh) {
  30120. if (mesh.getClassName() === "LinesMesh") {
  30121. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30122. this.updateExtend();
  30123. }
  30124. this.applyToMesh(mesh);
  30125. mesh.computeWorldMatrix(true);
  30126. }
  30127. }
  30128. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30129. /**
  30130. * 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
  30131. * @returns The Bias Vector
  30132. */
  30133. get: function () {
  30134. return this._boundingBias;
  30135. },
  30136. set: function (value) {
  30137. if (this._boundingBias && this._boundingBias.equals(value)) {
  30138. return;
  30139. }
  30140. this._boundingBias = value.clone();
  30141. this.updateBoundingInfo(true, null);
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Geometry.CreateGeometryForMesh = function (mesh) {
  30147. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30148. geometry.applyToMesh(mesh);
  30149. return geometry;
  30150. };
  30151. Object.defineProperty(Geometry.prototype, "extend", {
  30152. get: function () {
  30153. return this._extend;
  30154. },
  30155. enumerable: true,
  30156. configurable: true
  30157. });
  30158. Geometry.prototype.getScene = function () {
  30159. return this._scene;
  30160. };
  30161. Geometry.prototype.getEngine = function () {
  30162. return this._engine;
  30163. };
  30164. Geometry.prototype.isReady = function () {
  30165. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30166. };
  30167. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30168. get: function () {
  30169. for (var index = 0; index < this._meshes.length; index++) {
  30170. if (!this._meshes[index].doNotSerialize) {
  30171. return false;
  30172. }
  30173. }
  30174. return true;
  30175. },
  30176. enumerable: true,
  30177. configurable: true
  30178. });
  30179. Geometry.prototype._rebuild = function () {
  30180. if (this._vertexArrayObjects) {
  30181. this._vertexArrayObjects = {};
  30182. }
  30183. // Index buffer
  30184. if (this._meshes.length !== 0 && this._indices) {
  30185. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30186. }
  30187. // Vertex buffers
  30188. for (var key in this._vertexBuffers) {
  30189. var vertexBuffer = this._vertexBuffers[key];
  30190. vertexBuffer._rebuild();
  30191. }
  30192. };
  30193. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30194. vertexData.applyToGeometry(this, updatable);
  30195. this.notifyUpdate();
  30196. };
  30197. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30198. if (updatable === void 0) { updatable = false; }
  30199. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30200. this.setVerticesBuffer(buffer);
  30201. };
  30202. Geometry.prototype.removeVerticesData = function (kind) {
  30203. if (this._vertexBuffers[kind]) {
  30204. this._vertexBuffers[kind].dispose();
  30205. delete this._vertexBuffers[kind];
  30206. }
  30207. };
  30208. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30209. var kind = buffer.getKind();
  30210. if (this._vertexBuffers[kind]) {
  30211. this._vertexBuffers[kind].dispose();
  30212. }
  30213. this._vertexBuffers[kind] = buffer;
  30214. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30215. var data = buffer.getData();
  30216. var stride = buffer.getStrideSize();
  30217. this._totalVertices = data.length / stride;
  30218. this.updateExtend(data, stride);
  30219. this._resetPointsArrayCache();
  30220. var meshes = this._meshes;
  30221. var numOfMeshes = meshes.length;
  30222. for (var index = 0; index < numOfMeshes; index++) {
  30223. var mesh = meshes[index];
  30224. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30225. mesh._createGlobalSubMesh(false);
  30226. mesh.computeWorldMatrix(true);
  30227. }
  30228. }
  30229. this.notifyUpdate(kind);
  30230. if (this._vertexArrayObjects) {
  30231. this._disposeVertexArrayObjects();
  30232. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30233. }
  30234. };
  30235. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30236. var vertexBuffer = this.getVertexBuffer(kind);
  30237. if (!vertexBuffer) {
  30238. return;
  30239. }
  30240. vertexBuffer.updateDirectly(data, offset);
  30241. this.notifyUpdate(kind);
  30242. };
  30243. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30244. if (updateExtends === void 0) { updateExtends = false; }
  30245. var vertexBuffer = this.getVertexBuffer(kind);
  30246. if (!vertexBuffer) {
  30247. return;
  30248. }
  30249. vertexBuffer.update(data);
  30250. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30251. var stride = vertexBuffer.getStrideSize();
  30252. this._totalVertices = data.length / stride;
  30253. this.updateBoundingInfo(updateExtends, data);
  30254. }
  30255. this.notifyUpdate(kind);
  30256. };
  30257. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30258. if (updateExtends) {
  30259. this.updateExtend(data);
  30260. }
  30261. var meshes = this._meshes;
  30262. var numOfMeshes = meshes.length;
  30263. this._resetPointsArrayCache();
  30264. for (var index = 0; index < numOfMeshes; index++) {
  30265. var mesh = meshes[index];
  30266. if (updateExtends) {
  30267. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30268. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30269. var subMesh = mesh.subMeshes[subIndex];
  30270. subMesh.refreshBoundingInfo();
  30271. }
  30272. }
  30273. }
  30274. };
  30275. Geometry.prototype._bind = function (effect, indexToBind) {
  30276. if (!effect) {
  30277. return;
  30278. }
  30279. if (indexToBind === undefined) {
  30280. indexToBind = this._indexBuffer;
  30281. }
  30282. var vbs = this.getVertexBuffers();
  30283. if (!vbs) {
  30284. return;
  30285. }
  30286. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30287. this._engine.bindBuffers(vbs, indexToBind, effect);
  30288. return;
  30289. }
  30290. // Using VAO
  30291. if (!this._vertexArrayObjects[effect.key]) {
  30292. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30293. }
  30294. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30295. };
  30296. Geometry.prototype.getTotalVertices = function () {
  30297. if (!this.isReady()) {
  30298. return 0;
  30299. }
  30300. return this._totalVertices;
  30301. };
  30302. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30303. var vertexBuffer = this.getVertexBuffer(kind);
  30304. if (!vertexBuffer) {
  30305. return null;
  30306. }
  30307. var orig = vertexBuffer.getData();
  30308. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30309. return orig;
  30310. }
  30311. else {
  30312. var len = orig.length;
  30313. var copy = [];
  30314. for (var i = 0; i < len; i++) {
  30315. copy.push(orig[i]);
  30316. }
  30317. return copy;
  30318. }
  30319. };
  30320. /**
  30321. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30322. * Possible `kind` values :
  30323. * - BABYLON.VertexBuffer.PositionKind
  30324. * - BABYLON.VertexBuffer.UVKind
  30325. * - BABYLON.VertexBuffer.UV2Kind
  30326. * - BABYLON.VertexBuffer.UV3Kind
  30327. * - BABYLON.VertexBuffer.UV4Kind
  30328. * - BABYLON.VertexBuffer.UV5Kind
  30329. * - BABYLON.VertexBuffer.UV6Kind
  30330. * - BABYLON.VertexBuffer.ColorKind
  30331. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30332. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30333. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30334. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30335. */
  30336. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30337. var vb = this._vertexBuffers[kind];
  30338. if (!vb) {
  30339. return false;
  30340. }
  30341. return vb.isUpdatable();
  30342. };
  30343. Geometry.prototype.getVertexBuffer = function (kind) {
  30344. if (!this.isReady()) {
  30345. return null;
  30346. }
  30347. return this._vertexBuffers[kind];
  30348. };
  30349. Geometry.prototype.getVertexBuffers = function () {
  30350. if (!this.isReady()) {
  30351. return null;
  30352. }
  30353. return this._vertexBuffers;
  30354. };
  30355. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30356. if (!this._vertexBuffers) {
  30357. if (this._delayInfo) {
  30358. return this._delayInfo.indexOf(kind) !== -1;
  30359. }
  30360. return false;
  30361. }
  30362. return this._vertexBuffers[kind] !== undefined;
  30363. };
  30364. Geometry.prototype.getVerticesDataKinds = function () {
  30365. var result = [];
  30366. var kind;
  30367. if (!this._vertexBuffers && this._delayInfo) {
  30368. for (kind in this._delayInfo) {
  30369. result.push(kind);
  30370. }
  30371. }
  30372. else {
  30373. for (kind in this._vertexBuffers) {
  30374. result.push(kind);
  30375. }
  30376. }
  30377. return result;
  30378. };
  30379. Geometry.prototype.updateIndices = function (indices, offset) {
  30380. if (!this._indexBuffer) {
  30381. return;
  30382. }
  30383. if (!this._indexBufferIsUpdatable) {
  30384. this.setIndices(indices, null, true);
  30385. }
  30386. else {
  30387. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30388. }
  30389. };
  30390. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30391. if (totalVertices === void 0) { totalVertices = null; }
  30392. if (updatable === void 0) { updatable = false; }
  30393. if (this._indexBuffer) {
  30394. this._engine._releaseBuffer(this._indexBuffer);
  30395. }
  30396. this._disposeVertexArrayObjects();
  30397. this._indices = indices;
  30398. this._indexBufferIsUpdatable = updatable;
  30399. if (this._meshes.length !== 0 && this._indices) {
  30400. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30401. }
  30402. if (totalVertices != undefined) {
  30403. this._totalVertices = totalVertices;
  30404. }
  30405. var meshes = this._meshes;
  30406. var numOfMeshes = meshes.length;
  30407. for (var index = 0; index < numOfMeshes; index++) {
  30408. meshes[index]._createGlobalSubMesh(true);
  30409. }
  30410. this.notifyUpdate();
  30411. };
  30412. Geometry.prototype.getTotalIndices = function () {
  30413. if (!this.isReady()) {
  30414. return 0;
  30415. }
  30416. return this._indices.length;
  30417. };
  30418. Geometry.prototype.getIndices = function (copyWhenShared) {
  30419. if (!this.isReady()) {
  30420. return null;
  30421. }
  30422. var orig = this._indices;
  30423. if (!copyWhenShared || this._meshes.length === 1) {
  30424. return orig;
  30425. }
  30426. else {
  30427. var len = orig.length;
  30428. var copy = [];
  30429. for (var i = 0; i < len; i++) {
  30430. copy.push(orig[i]);
  30431. }
  30432. return copy;
  30433. }
  30434. };
  30435. Geometry.prototype.getIndexBuffer = function () {
  30436. if (!this.isReady()) {
  30437. return null;
  30438. }
  30439. return this._indexBuffer;
  30440. };
  30441. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30442. if (effect === void 0) { effect = null; }
  30443. if (!effect || !this._vertexArrayObjects) {
  30444. return;
  30445. }
  30446. if (this._vertexArrayObjects[effect.key]) {
  30447. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30448. delete this._vertexArrayObjects[effect.key];
  30449. }
  30450. };
  30451. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30452. var meshes = this._meshes;
  30453. var index = meshes.indexOf(mesh);
  30454. if (index === -1) {
  30455. return;
  30456. }
  30457. meshes.splice(index, 1);
  30458. mesh._geometry = null;
  30459. if (meshes.length === 0 && shouldDispose) {
  30460. this.dispose();
  30461. }
  30462. };
  30463. Geometry.prototype.applyToMesh = function (mesh) {
  30464. if (mesh._geometry === this) {
  30465. return;
  30466. }
  30467. var previousGeometry = mesh._geometry;
  30468. if (previousGeometry) {
  30469. previousGeometry.releaseForMesh(mesh);
  30470. }
  30471. var meshes = this._meshes;
  30472. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30473. mesh._geometry = this;
  30474. this._scene.pushGeometry(this);
  30475. meshes.push(mesh);
  30476. if (this.isReady()) {
  30477. this._applyToMesh(mesh);
  30478. }
  30479. else {
  30480. mesh._boundingInfo = this._boundingInfo;
  30481. }
  30482. };
  30483. Geometry.prototype.updateExtend = function (data, stride) {
  30484. if (data === void 0) { data = null; }
  30485. if (!data) {
  30486. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30487. }
  30488. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30489. };
  30490. Geometry.prototype._applyToMesh = function (mesh) {
  30491. var numOfMeshes = this._meshes.length;
  30492. // vertexBuffers
  30493. for (var kind in this._vertexBuffers) {
  30494. if (numOfMeshes === 1) {
  30495. this._vertexBuffers[kind].create();
  30496. }
  30497. var buffer = this._vertexBuffers[kind].getBuffer();
  30498. if (buffer)
  30499. buffer.references = numOfMeshes;
  30500. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30501. if (!this._extend) {
  30502. this.updateExtend(this._vertexBuffers[kind].getData());
  30503. }
  30504. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30505. mesh._createGlobalSubMesh(false);
  30506. //bounding info was just created again, world matrix should be applied again.
  30507. mesh._updateBoundingInfo();
  30508. }
  30509. }
  30510. // indexBuffer
  30511. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30512. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30513. }
  30514. if (this._indexBuffer) {
  30515. this._indexBuffer.references = numOfMeshes;
  30516. }
  30517. };
  30518. Geometry.prototype.notifyUpdate = function (kind) {
  30519. if (this.onGeometryUpdated) {
  30520. this.onGeometryUpdated(this, kind);
  30521. }
  30522. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30523. var mesh = _a[_i];
  30524. mesh._markSubMeshesAsAttributesDirty();
  30525. }
  30526. };
  30527. Geometry.prototype.load = function (scene, onLoaded) {
  30528. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30529. return;
  30530. }
  30531. if (this.isReady()) {
  30532. if (onLoaded) {
  30533. onLoaded();
  30534. }
  30535. return;
  30536. }
  30537. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30538. this._queueLoad(scene, onLoaded);
  30539. };
  30540. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30541. var _this = this;
  30542. if (!this.delayLoadingFile) {
  30543. return;
  30544. }
  30545. scene._addPendingData(this);
  30546. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30547. if (!_this._delayLoadingFunction) {
  30548. return;
  30549. }
  30550. _this._delayLoadingFunction(JSON.parse(data), _this);
  30551. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30552. _this._delayInfo = [];
  30553. scene._removePendingData(_this);
  30554. var meshes = _this._meshes;
  30555. var numOfMeshes = meshes.length;
  30556. for (var index = 0; index < numOfMeshes; index++) {
  30557. _this._applyToMesh(meshes[index]);
  30558. }
  30559. if (onLoaded) {
  30560. onLoaded();
  30561. }
  30562. }, function () { }, scene.database);
  30563. };
  30564. /**
  30565. * Invert the geometry to move from a right handed system to a left handed one.
  30566. */
  30567. Geometry.prototype.toLeftHanded = function () {
  30568. // Flip faces
  30569. var tIndices = this.getIndices(false);
  30570. if (tIndices != null && tIndices.length > 0) {
  30571. for (var i = 0; i < tIndices.length; i += 3) {
  30572. var tTemp = tIndices[i + 0];
  30573. tIndices[i + 0] = tIndices[i + 2];
  30574. tIndices[i + 2] = tTemp;
  30575. }
  30576. this.setIndices(tIndices);
  30577. }
  30578. // Negate position.z
  30579. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30580. if (tPositions != null && tPositions.length > 0) {
  30581. for (var i = 0; i < tPositions.length; i += 3) {
  30582. tPositions[i + 2] = -tPositions[i + 2];
  30583. }
  30584. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30585. }
  30586. // Negate normal.z
  30587. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30588. if (tNormals != null && tNormals.length > 0) {
  30589. for (var i = 0; i < tNormals.length; i += 3) {
  30590. tNormals[i + 2] = -tNormals[i + 2];
  30591. }
  30592. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30593. }
  30594. };
  30595. // Cache
  30596. Geometry.prototype._resetPointsArrayCache = function () {
  30597. this._positions = null;
  30598. };
  30599. Geometry.prototype._generatePointsArray = function () {
  30600. if (this._positions)
  30601. return true;
  30602. this._positions = [];
  30603. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30604. if (!data) {
  30605. return false;
  30606. }
  30607. for (var index = 0; index < data.length; index += 3) {
  30608. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30609. }
  30610. return true;
  30611. };
  30612. Geometry.prototype.isDisposed = function () {
  30613. return this._isDisposed;
  30614. };
  30615. Geometry.prototype._disposeVertexArrayObjects = function () {
  30616. if (this._vertexArrayObjects) {
  30617. for (var kind in this._vertexArrayObjects) {
  30618. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30619. }
  30620. this._vertexArrayObjects = {};
  30621. }
  30622. };
  30623. Geometry.prototype.dispose = function () {
  30624. var meshes = this._meshes;
  30625. var numOfMeshes = meshes.length;
  30626. var index;
  30627. for (index = 0; index < numOfMeshes; index++) {
  30628. this.releaseForMesh(meshes[index]);
  30629. }
  30630. this._meshes = [];
  30631. this._disposeVertexArrayObjects();
  30632. for (var kind in this._vertexBuffers) {
  30633. this._vertexBuffers[kind].dispose();
  30634. }
  30635. this._vertexBuffers = {};
  30636. this._totalVertices = 0;
  30637. if (this._indexBuffer) {
  30638. this._engine._releaseBuffer(this._indexBuffer);
  30639. }
  30640. this._indexBuffer = null;
  30641. this._indices = [];
  30642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30643. this.delayLoadingFile = null;
  30644. this._delayLoadingFunction = null;
  30645. this._delayInfo = [];
  30646. this._boundingInfo = null;
  30647. this._scene.removeGeometry(this);
  30648. this._isDisposed = true;
  30649. };
  30650. Geometry.prototype.copy = function (id) {
  30651. var vertexData = new BABYLON.VertexData();
  30652. vertexData.indices = [];
  30653. var indices = this.getIndices();
  30654. if (indices) {
  30655. for (var index = 0; index < indices.length; index++) {
  30656. vertexData.indices.push(indices[index]);
  30657. }
  30658. }
  30659. var updatable = false;
  30660. var stopChecking = false;
  30661. var kind;
  30662. for (kind in this._vertexBuffers) {
  30663. // using slice() to make a copy of the array and not just reference it
  30664. var data = this.getVerticesData(kind);
  30665. if (data instanceof Float32Array) {
  30666. vertexData.set(new Float32Array(data), kind);
  30667. }
  30668. else {
  30669. vertexData.set(data.slice(0), kind);
  30670. }
  30671. if (!stopChecking) {
  30672. var vb = this.getVertexBuffer(kind);
  30673. if (vb) {
  30674. updatable = vb.isUpdatable();
  30675. stopChecking = !updatable;
  30676. }
  30677. }
  30678. }
  30679. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30680. geometry.delayLoadState = this.delayLoadState;
  30681. geometry.delayLoadingFile = this.delayLoadingFile;
  30682. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30683. for (kind in this._delayInfo) {
  30684. geometry._delayInfo = geometry._delayInfo || [];
  30685. geometry._delayInfo.push(kind);
  30686. }
  30687. // Bounding info
  30688. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30689. return geometry;
  30690. };
  30691. Geometry.prototype.serialize = function () {
  30692. var serializationObject = {};
  30693. serializationObject.id = this.id;
  30694. serializationObject.updatable = this._updatable;
  30695. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30696. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30697. }
  30698. return serializationObject;
  30699. };
  30700. Geometry.prototype.toNumberArray = function (origin) {
  30701. if (Array.isArray(origin)) {
  30702. return origin;
  30703. }
  30704. else {
  30705. return Array.prototype.slice.call(origin);
  30706. }
  30707. };
  30708. Geometry.prototype.serializeVerticeData = function () {
  30709. var serializationObject = this.serialize();
  30710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30711. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30712. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30713. serializationObject.positions._updatable = true;
  30714. }
  30715. }
  30716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30717. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30718. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30719. serializationObject.normals._updatable = true;
  30720. }
  30721. }
  30722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30723. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30724. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30725. serializationObject.uvs._updatable = true;
  30726. }
  30727. }
  30728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30729. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30730. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30731. serializationObject.uv2s._updatable = true;
  30732. }
  30733. }
  30734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30735. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30737. serializationObject.uv3s._updatable = true;
  30738. }
  30739. }
  30740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30741. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30742. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30743. serializationObject.uv4s._updatable = true;
  30744. }
  30745. }
  30746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30747. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30748. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30749. serializationObject.uv5s._updatable = true;
  30750. }
  30751. }
  30752. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30753. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30754. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30755. serializationObject.uv6s._updatable = true;
  30756. }
  30757. }
  30758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30759. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30760. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30761. serializationObject.colors._updatable = true;
  30762. }
  30763. }
  30764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30765. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30766. serializationObject.matricesIndices._isExpanded = true;
  30767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30768. serializationObject.matricesIndices._updatable = true;
  30769. }
  30770. }
  30771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30772. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30774. serializationObject.matricesWeights._updatable = true;
  30775. }
  30776. }
  30777. serializationObject.indices = this.toNumberArray(this.getIndices());
  30778. return serializationObject;
  30779. };
  30780. // Statics
  30781. Geometry.ExtractFromMesh = function (mesh, id) {
  30782. var geometry = mesh._geometry;
  30783. if (!geometry) {
  30784. return null;
  30785. }
  30786. return geometry.copy(id);
  30787. };
  30788. /**
  30789. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30790. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30791. * Be aware Math.random() could cause collisions, but:
  30792. * "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"
  30793. */
  30794. Geometry.RandomId = function () {
  30795. return BABYLON.Tools.RandomId();
  30796. };
  30797. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30798. var scene = mesh.getScene();
  30799. // Geometry
  30800. var geometryId = parsedGeometry.geometryId;
  30801. if (geometryId) {
  30802. var geometry = scene.getGeometryByID(geometryId);
  30803. if (geometry) {
  30804. geometry.applyToMesh(mesh);
  30805. }
  30806. }
  30807. else if (parsedGeometry instanceof ArrayBuffer) {
  30808. var binaryInfo = mesh._binaryInfo;
  30809. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  30810. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  30811. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  30812. }
  30813. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  30814. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  30815. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  30816. }
  30817. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  30818. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  30819. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  30820. }
  30821. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  30822. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  30823. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  30824. }
  30825. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  30826. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  30827. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  30828. }
  30829. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  30830. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  30831. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  30832. }
  30833. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  30834. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  30835. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  30836. }
  30837. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  30838. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  30839. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  30840. }
  30841. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  30842. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  30843. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  30844. }
  30845. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  30846. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  30847. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  30848. }
  30849. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  30850. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  30851. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  30852. }
  30853. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  30854. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  30855. mesh.setIndices(indicesData, null);
  30856. }
  30857. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  30858. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  30859. mesh.subMeshes = [];
  30860. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  30861. var materialIndex = subMeshesData[(i * 5) + 0];
  30862. var verticesStart = subMeshesData[(i * 5) + 1];
  30863. var verticesCount = subMeshesData[(i * 5) + 2];
  30864. var indexStart = subMeshesData[(i * 5) + 3];
  30865. var indexCount = subMeshesData[(i * 5) + 4];
  30866. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  30867. }
  30868. }
  30869. }
  30870. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  30871. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  30872. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  30873. if (parsedGeometry.uvs) {
  30874. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  30875. }
  30876. if (parsedGeometry.uvs2) {
  30877. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  30878. }
  30879. if (parsedGeometry.uvs3) {
  30880. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  30881. }
  30882. if (parsedGeometry.uvs4) {
  30883. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  30884. }
  30885. if (parsedGeometry.uvs5) {
  30886. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  30887. }
  30888. if (parsedGeometry.uvs6) {
  30889. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  30890. }
  30891. if (parsedGeometry.colors) {
  30892. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  30893. }
  30894. if (parsedGeometry.matricesIndices) {
  30895. if (!parsedGeometry.matricesIndices._isExpanded) {
  30896. var floatIndices = [];
  30897. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  30898. var matricesIndex = parsedGeometry.matricesIndices[i];
  30899. floatIndices.push(matricesIndex & 0x000000FF);
  30900. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30901. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30902. floatIndices.push(matricesIndex >> 24);
  30903. }
  30904. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  30905. }
  30906. else {
  30907. delete parsedGeometry.matricesIndices._isExpanded;
  30908. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  30909. }
  30910. }
  30911. if (parsedGeometry.matricesIndicesExtra) {
  30912. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  30913. var floatIndices = [];
  30914. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  30915. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  30916. floatIndices.push(matricesIndex & 0x000000FF);
  30917. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  30918. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  30919. floatIndices.push(matricesIndex >> 24);
  30920. }
  30921. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  30922. }
  30923. else {
  30924. delete parsedGeometry.matricesIndices._isExpanded;
  30925. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  30926. }
  30927. }
  30928. if (parsedGeometry.matricesWeights) {
  30929. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  30930. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  30931. }
  30932. if (parsedGeometry.matricesWeightsExtra) {
  30933. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  30934. }
  30935. mesh.setIndices(parsedGeometry.indices, null);
  30936. }
  30937. // SubMeshes
  30938. if (parsedGeometry.subMeshes) {
  30939. mesh.subMeshes = [];
  30940. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  30941. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  30942. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  30943. }
  30944. }
  30945. // Flat shading
  30946. if (mesh._shouldGenerateFlatShading) {
  30947. mesh.convertToFlatShadedMesh();
  30948. delete mesh._shouldGenerateFlatShading;
  30949. }
  30950. // Update
  30951. mesh.computeWorldMatrix(true);
  30952. // Octree
  30953. if (scene['_selectionOctree']) {
  30954. scene['_selectionOctree'].addMesh(mesh);
  30955. }
  30956. };
  30957. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  30958. var epsilon = 1e-3;
  30959. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  30960. return;
  30961. }
  30962. var noInfluenceBoneIndex = 0.0;
  30963. if (parsedGeometry.skeletonId > -1) {
  30964. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  30965. if (!skeleton) {
  30966. return;
  30967. }
  30968. noInfluenceBoneIndex = skeleton.bones.length;
  30969. }
  30970. else {
  30971. return;
  30972. }
  30973. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30974. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  30975. var matricesWeights = parsedGeometry.matricesWeights;
  30976. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  30977. var influencers = parsedGeometry.numBoneInfluencer;
  30978. var size = matricesWeights.length;
  30979. for (var i = 0; i < size; i += 4) {
  30980. var weight = 0.0;
  30981. var firstZeroWeight = -1;
  30982. for (var j = 0; j < 4; j++) {
  30983. var w = matricesWeights[i + j];
  30984. weight += w;
  30985. if (w < epsilon && firstZeroWeight < 0) {
  30986. firstZeroWeight = j;
  30987. }
  30988. }
  30989. if (matricesWeightsExtra) {
  30990. for (var j = 0; j < 4; j++) {
  30991. var w = matricesWeightsExtra[i + j];
  30992. weight += w;
  30993. if (w < epsilon && firstZeroWeight < 0) {
  30994. firstZeroWeight = j + 4;
  30995. }
  30996. }
  30997. }
  30998. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  30999. firstZeroWeight = influencers - 1;
  31000. }
  31001. if (weight > epsilon) {
  31002. var mweight = 1.0 / weight;
  31003. for (var j = 0; j < 4; j++) {
  31004. matricesWeights[i + j] *= mweight;
  31005. }
  31006. if (matricesWeightsExtra) {
  31007. for (var j = 0; j < 4; j++) {
  31008. matricesWeightsExtra[i + j] *= mweight;
  31009. }
  31010. }
  31011. }
  31012. else {
  31013. if (firstZeroWeight >= 4) {
  31014. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31015. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31016. }
  31017. else {
  31018. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31019. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31020. }
  31021. }
  31022. }
  31023. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31024. if (parsedGeometry.matricesWeightsExtra) {
  31025. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31026. }
  31027. };
  31028. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31029. if (scene.getGeometryByID(parsedVertexData.id)) {
  31030. return null; // null since geometry could be something else than a box...
  31031. }
  31032. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31033. if (BABYLON.Tags) {
  31034. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31035. }
  31036. if (parsedVertexData.delayLoadingFile) {
  31037. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31038. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31039. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31040. geometry._delayInfo = [];
  31041. if (parsedVertexData.hasUVs) {
  31042. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31043. }
  31044. if (parsedVertexData.hasUVs2) {
  31045. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31046. }
  31047. if (parsedVertexData.hasUVs3) {
  31048. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31049. }
  31050. if (parsedVertexData.hasUVs4) {
  31051. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31052. }
  31053. if (parsedVertexData.hasUVs5) {
  31054. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31055. }
  31056. if (parsedVertexData.hasUVs6) {
  31057. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31058. }
  31059. if (parsedVertexData.hasColors) {
  31060. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31061. }
  31062. if (parsedVertexData.hasMatricesIndices) {
  31063. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31064. }
  31065. if (parsedVertexData.hasMatricesWeights) {
  31066. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31067. }
  31068. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31069. }
  31070. else {
  31071. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31072. }
  31073. scene.pushGeometry(geometry, true);
  31074. return geometry;
  31075. };
  31076. return Geometry;
  31077. }());
  31078. BABYLON.Geometry = Geometry;
  31079. /////// Primitives //////////////////////////////////////////////
  31080. (function (Geometry) {
  31081. var Primitives;
  31082. (function (Primitives) {
  31083. /// Abstract class
  31084. var _Primitive = /** @class */ (function (_super) {
  31085. __extends(_Primitive, _super);
  31086. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31087. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31088. if (mesh === void 0) { mesh = null; }
  31089. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31090. _this._canBeRegenerated = _canBeRegenerated;
  31091. _this._beingRegenerated = true;
  31092. _this.regenerate();
  31093. _this._beingRegenerated = false;
  31094. return _this;
  31095. }
  31096. _Primitive.prototype.canBeRegenerated = function () {
  31097. return this._canBeRegenerated;
  31098. };
  31099. _Primitive.prototype.regenerate = function () {
  31100. if (!this._canBeRegenerated) {
  31101. return;
  31102. }
  31103. this._beingRegenerated = true;
  31104. this.setAllVerticesData(this._regenerateVertexData(), false);
  31105. this._beingRegenerated = false;
  31106. };
  31107. _Primitive.prototype.asNewGeometry = function (id) {
  31108. return _super.prototype.copy.call(this, id);
  31109. };
  31110. // overrides
  31111. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31112. if (!this._beingRegenerated) {
  31113. return;
  31114. }
  31115. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31116. };
  31117. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31118. if (!this._beingRegenerated) {
  31119. return;
  31120. }
  31121. _super.prototype.setVerticesData.call(this, kind, data, false);
  31122. };
  31123. // to override
  31124. // protected
  31125. _Primitive.prototype._regenerateVertexData = function () {
  31126. throw new Error("Abstract method");
  31127. };
  31128. _Primitive.prototype.copy = function (id) {
  31129. throw new Error("Must be overriden in sub-classes.");
  31130. };
  31131. _Primitive.prototype.serialize = function () {
  31132. var serializationObject = _super.prototype.serialize.call(this);
  31133. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31134. return serializationObject;
  31135. };
  31136. return _Primitive;
  31137. }(Geometry));
  31138. Primitives._Primitive = _Primitive;
  31139. var Ribbon = /** @class */ (function (_super) {
  31140. __extends(Ribbon, _super);
  31141. // Members
  31142. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31144. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31145. _this.pathArray = pathArray;
  31146. _this.closeArray = closeArray;
  31147. _this.closePath = closePath;
  31148. _this.offset = offset;
  31149. _this.side = side;
  31150. return _this;
  31151. }
  31152. Ribbon.prototype._regenerateVertexData = function () {
  31153. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31154. };
  31155. Ribbon.prototype.copy = function (id) {
  31156. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31157. };
  31158. return Ribbon;
  31159. }(_Primitive));
  31160. Primitives.Ribbon = Ribbon;
  31161. var Box = /** @class */ (function (_super) {
  31162. __extends(Box, _super);
  31163. // Members
  31164. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31165. if (mesh === void 0) { mesh = null; }
  31166. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31167. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31168. _this.size = size;
  31169. _this.side = side;
  31170. return _this;
  31171. }
  31172. Box.prototype._regenerateVertexData = function () {
  31173. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31174. };
  31175. Box.prototype.copy = function (id) {
  31176. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31177. };
  31178. Box.prototype.serialize = function () {
  31179. var serializationObject = _super.prototype.serialize.call(this);
  31180. serializationObject.size = this.size;
  31181. return serializationObject;
  31182. };
  31183. Box.Parse = function (parsedBox, scene) {
  31184. if (scene.getGeometryByID(parsedBox.id)) {
  31185. return null; // null since geometry could be something else than a box...
  31186. }
  31187. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31188. if (BABYLON.Tags) {
  31189. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31190. }
  31191. scene.pushGeometry(box, true);
  31192. return box;
  31193. };
  31194. return Box;
  31195. }(_Primitive));
  31196. Primitives.Box = Box;
  31197. var Sphere = /** @class */ (function (_super) {
  31198. __extends(Sphere, _super);
  31199. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31200. if (mesh === void 0) { mesh = null; }
  31201. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31202. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31203. _this.segments = segments;
  31204. _this.diameter = diameter;
  31205. _this.side = side;
  31206. return _this;
  31207. }
  31208. Sphere.prototype._regenerateVertexData = function () {
  31209. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31210. };
  31211. Sphere.prototype.copy = function (id) {
  31212. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31213. };
  31214. Sphere.prototype.serialize = function () {
  31215. var serializationObject = _super.prototype.serialize.call(this);
  31216. serializationObject.segments = this.segments;
  31217. serializationObject.diameter = this.diameter;
  31218. return serializationObject;
  31219. };
  31220. Sphere.Parse = function (parsedSphere, scene) {
  31221. if (scene.getGeometryByID(parsedSphere.id)) {
  31222. return null; // null since geometry could be something else than a sphere...
  31223. }
  31224. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31225. if (BABYLON.Tags) {
  31226. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31227. }
  31228. scene.pushGeometry(sphere, true);
  31229. return sphere;
  31230. };
  31231. return Sphere;
  31232. }(_Primitive));
  31233. Primitives.Sphere = Sphere;
  31234. var Disc = /** @class */ (function (_super) {
  31235. __extends(Disc, _super);
  31236. // Members
  31237. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31238. if (mesh === void 0) { mesh = null; }
  31239. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31240. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31241. _this.radius = radius;
  31242. _this.tessellation = tessellation;
  31243. _this.side = side;
  31244. return _this;
  31245. }
  31246. Disc.prototype._regenerateVertexData = function () {
  31247. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31248. };
  31249. Disc.prototype.copy = function (id) {
  31250. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31251. };
  31252. return Disc;
  31253. }(_Primitive));
  31254. Primitives.Disc = Disc;
  31255. var Cylinder = /** @class */ (function (_super) {
  31256. __extends(Cylinder, _super);
  31257. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31258. if (subdivisions === void 0) { subdivisions = 1; }
  31259. if (mesh === void 0) { mesh = null; }
  31260. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31262. _this.height = height;
  31263. _this.diameterTop = diameterTop;
  31264. _this.diameterBottom = diameterBottom;
  31265. _this.tessellation = tessellation;
  31266. _this.subdivisions = subdivisions;
  31267. _this.side = side;
  31268. return _this;
  31269. }
  31270. Cylinder.prototype._regenerateVertexData = function () {
  31271. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31272. };
  31273. Cylinder.prototype.copy = function (id) {
  31274. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31275. };
  31276. Cylinder.prototype.serialize = function () {
  31277. var serializationObject = _super.prototype.serialize.call(this);
  31278. serializationObject.height = this.height;
  31279. serializationObject.diameterTop = this.diameterTop;
  31280. serializationObject.diameterBottom = this.diameterBottom;
  31281. serializationObject.tessellation = this.tessellation;
  31282. return serializationObject;
  31283. };
  31284. Cylinder.Parse = function (parsedCylinder, scene) {
  31285. if (scene.getGeometryByID(parsedCylinder.id)) {
  31286. return null; // null since geometry could be something else than a cylinder...
  31287. }
  31288. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31289. if (BABYLON.Tags) {
  31290. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31291. }
  31292. scene.pushGeometry(cylinder, true);
  31293. return cylinder;
  31294. };
  31295. return Cylinder;
  31296. }(_Primitive));
  31297. Primitives.Cylinder = Cylinder;
  31298. var Torus = /** @class */ (function (_super) {
  31299. __extends(Torus, _super);
  31300. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31301. if (mesh === void 0) { mesh = null; }
  31302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31304. _this.diameter = diameter;
  31305. _this.thickness = thickness;
  31306. _this.tessellation = tessellation;
  31307. _this.side = side;
  31308. return _this;
  31309. }
  31310. Torus.prototype._regenerateVertexData = function () {
  31311. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31312. };
  31313. Torus.prototype.copy = function (id) {
  31314. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31315. };
  31316. Torus.prototype.serialize = function () {
  31317. var serializationObject = _super.prototype.serialize.call(this);
  31318. serializationObject.diameter = this.diameter;
  31319. serializationObject.thickness = this.thickness;
  31320. serializationObject.tessellation = this.tessellation;
  31321. return serializationObject;
  31322. };
  31323. Torus.Parse = function (parsedTorus, scene) {
  31324. if (scene.getGeometryByID(parsedTorus.id)) {
  31325. return null; // null since geometry could be something else than a torus...
  31326. }
  31327. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31328. if (BABYLON.Tags) {
  31329. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31330. }
  31331. scene.pushGeometry(torus, true);
  31332. return torus;
  31333. };
  31334. return Torus;
  31335. }(_Primitive));
  31336. Primitives.Torus = Torus;
  31337. var Ground = /** @class */ (function (_super) {
  31338. __extends(Ground, _super);
  31339. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31340. if (mesh === void 0) { mesh = null; }
  31341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31342. _this.width = width;
  31343. _this.height = height;
  31344. _this.subdivisions = subdivisions;
  31345. return _this;
  31346. }
  31347. Ground.prototype._regenerateVertexData = function () {
  31348. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31349. };
  31350. Ground.prototype.copy = function (id) {
  31351. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31352. };
  31353. Ground.prototype.serialize = function () {
  31354. var serializationObject = _super.prototype.serialize.call(this);
  31355. serializationObject.width = this.width;
  31356. serializationObject.height = this.height;
  31357. serializationObject.subdivisions = this.subdivisions;
  31358. return serializationObject;
  31359. };
  31360. Ground.Parse = function (parsedGround, scene) {
  31361. if (scene.getGeometryByID(parsedGround.id)) {
  31362. return null; // null since geometry could be something else than a ground...
  31363. }
  31364. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31365. if (BABYLON.Tags) {
  31366. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31367. }
  31368. scene.pushGeometry(ground, true);
  31369. return ground;
  31370. };
  31371. return Ground;
  31372. }(_Primitive));
  31373. Primitives.Ground = Ground;
  31374. var TiledGround = /** @class */ (function (_super) {
  31375. __extends(TiledGround, _super);
  31376. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31377. if (mesh === void 0) { mesh = null; }
  31378. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31379. _this.xmin = xmin;
  31380. _this.zmin = zmin;
  31381. _this.xmax = xmax;
  31382. _this.zmax = zmax;
  31383. _this.subdivisions = subdivisions;
  31384. _this.precision = precision;
  31385. return _this;
  31386. }
  31387. TiledGround.prototype._regenerateVertexData = function () {
  31388. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31389. };
  31390. TiledGround.prototype.copy = function (id) {
  31391. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31392. };
  31393. return TiledGround;
  31394. }(_Primitive));
  31395. Primitives.TiledGround = TiledGround;
  31396. var Plane = /** @class */ (function (_super) {
  31397. __extends(Plane, _super);
  31398. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31399. if (mesh === void 0) { mesh = null; }
  31400. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31401. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31402. _this.size = size;
  31403. _this.side = side;
  31404. return _this;
  31405. }
  31406. Plane.prototype._regenerateVertexData = function () {
  31407. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31408. };
  31409. Plane.prototype.copy = function (id) {
  31410. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31411. };
  31412. Plane.prototype.serialize = function () {
  31413. var serializationObject = _super.prototype.serialize.call(this);
  31414. serializationObject.size = this.size;
  31415. return serializationObject;
  31416. };
  31417. Plane.Parse = function (parsedPlane, scene) {
  31418. if (scene.getGeometryByID(parsedPlane.id)) {
  31419. return null; // null since geometry could be something else than a ground...
  31420. }
  31421. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31422. if (BABYLON.Tags) {
  31423. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31424. }
  31425. scene.pushGeometry(plane, true);
  31426. return plane;
  31427. };
  31428. return Plane;
  31429. }(_Primitive));
  31430. Primitives.Plane = Plane;
  31431. var TorusKnot = /** @class */ (function (_super) {
  31432. __extends(TorusKnot, _super);
  31433. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31434. if (mesh === void 0) { mesh = null; }
  31435. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31436. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31437. _this.radius = radius;
  31438. _this.tube = tube;
  31439. _this.radialSegments = radialSegments;
  31440. _this.tubularSegments = tubularSegments;
  31441. _this.p = p;
  31442. _this.q = q;
  31443. _this.side = side;
  31444. return _this;
  31445. }
  31446. TorusKnot.prototype._regenerateVertexData = function () {
  31447. 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 });
  31448. };
  31449. TorusKnot.prototype.copy = function (id) {
  31450. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31451. };
  31452. TorusKnot.prototype.serialize = function () {
  31453. var serializationObject = _super.prototype.serialize.call(this);
  31454. serializationObject.radius = this.radius;
  31455. serializationObject.tube = this.tube;
  31456. serializationObject.radialSegments = this.radialSegments;
  31457. serializationObject.tubularSegments = this.tubularSegments;
  31458. serializationObject.p = this.p;
  31459. serializationObject.q = this.q;
  31460. return serializationObject;
  31461. };
  31462. ;
  31463. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31464. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31465. return null; // null since geometry could be something else than a ground...
  31466. }
  31467. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31468. if (BABYLON.Tags) {
  31469. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31470. }
  31471. scene.pushGeometry(torusKnot, true);
  31472. return torusKnot;
  31473. };
  31474. return TorusKnot;
  31475. }(_Primitive));
  31476. Primitives.TorusKnot = TorusKnot;
  31477. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31478. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31479. })(BABYLON || (BABYLON = {}));
  31480. //# sourceMappingURL=babylon.geometry.js.map
  31481. var BABYLON;
  31482. (function (BABYLON) {
  31483. var PostProcessManager = /** @class */ (function () {
  31484. function PostProcessManager(scene) {
  31485. this._vertexBuffers = {};
  31486. this._scene = scene;
  31487. }
  31488. PostProcessManager.prototype._prepareBuffers = function () {
  31489. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31490. return;
  31491. }
  31492. // VBO
  31493. var vertices = [];
  31494. vertices.push(1, 1);
  31495. vertices.push(-1, 1);
  31496. vertices.push(-1, -1);
  31497. vertices.push(1, -1);
  31498. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31499. this._buildIndexBuffer();
  31500. };
  31501. PostProcessManager.prototype._buildIndexBuffer = function () {
  31502. // Indices
  31503. var indices = [];
  31504. indices.push(0);
  31505. indices.push(1);
  31506. indices.push(2);
  31507. indices.push(0);
  31508. indices.push(2);
  31509. indices.push(3);
  31510. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31511. };
  31512. PostProcessManager.prototype._rebuild = function () {
  31513. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31514. if (!vb) {
  31515. return;
  31516. }
  31517. vb._rebuild();
  31518. this._buildIndexBuffer();
  31519. };
  31520. // Methods
  31521. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31522. if (sourceTexture === void 0) { sourceTexture = null; }
  31523. if (postProcesses === void 0) { postProcesses = null; }
  31524. var camera = this._scene.activeCamera;
  31525. if (!camera) {
  31526. return false;
  31527. }
  31528. var postProcesses = postProcesses || camera._postProcesses;
  31529. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31530. return false;
  31531. }
  31532. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31533. return true;
  31534. };
  31535. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31536. if (targetTexture === void 0) { targetTexture = null; }
  31537. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31538. if (!this._scene.activeCamera) {
  31539. return;
  31540. }
  31541. var engine = this._scene.getEngine();
  31542. for (var index = 0; index < postProcesses.length; index++) {
  31543. if (index < postProcesses.length - 1) {
  31544. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31545. }
  31546. else {
  31547. if (targetTexture) {
  31548. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31549. }
  31550. else {
  31551. engine.restoreDefaultFramebuffer();
  31552. }
  31553. }
  31554. var pp = postProcesses[index];
  31555. var effect = pp.apply();
  31556. if (effect) {
  31557. pp.onBeforeRenderObservable.notifyObservers(effect);
  31558. // VBOs
  31559. this._prepareBuffers();
  31560. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31561. // Draw order
  31562. engine.draw(true, 0, 6);
  31563. pp.onAfterRenderObservable.notifyObservers(effect);
  31564. }
  31565. }
  31566. // Restore depth buffer
  31567. engine.setDepthBuffer(true);
  31568. engine.setDepthWrite(true);
  31569. };
  31570. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31571. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31572. var camera = this._scene.activeCamera;
  31573. if (!camera) {
  31574. return;
  31575. }
  31576. postProcesses = postProcesses || camera._postProcesses;
  31577. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31578. return;
  31579. }
  31580. var engine = this._scene.getEngine();
  31581. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31582. if (index < len - 1) {
  31583. postProcesses[index + 1].activate(camera, targetTexture);
  31584. }
  31585. else {
  31586. if (targetTexture) {
  31587. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31588. }
  31589. else {
  31590. engine.restoreDefaultFramebuffer();
  31591. }
  31592. }
  31593. if (doNotPresent) {
  31594. break;
  31595. }
  31596. var pp = postProcesses[index];
  31597. var effect = pp.apply();
  31598. if (effect) {
  31599. pp.onBeforeRenderObservable.notifyObservers(effect);
  31600. // VBOs
  31601. this._prepareBuffers();
  31602. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31603. // Draw order
  31604. engine.draw(true, 0, 6);
  31605. pp.onAfterRenderObservable.notifyObservers(effect);
  31606. }
  31607. }
  31608. // Restore states
  31609. engine.setDepthBuffer(true);
  31610. engine.setDepthWrite(true);
  31611. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31612. };
  31613. PostProcessManager.prototype.dispose = function () {
  31614. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31615. if (buffer) {
  31616. buffer.dispose();
  31617. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31618. }
  31619. if (this._indexBuffer) {
  31620. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31621. this._indexBuffer = null;
  31622. }
  31623. };
  31624. return PostProcessManager;
  31625. }());
  31626. BABYLON.PostProcessManager = PostProcessManager;
  31627. })(BABYLON || (BABYLON = {}));
  31628. //# sourceMappingURL=babylon.postProcessManager.js.map
  31629. var BABYLON;
  31630. (function (BABYLON) {
  31631. /**
  31632. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31633. */
  31634. var PerformanceMonitor = /** @class */ (function () {
  31635. /**
  31636. * constructor
  31637. * @param frameSampleSize The number of samples required to saturate the sliding window
  31638. */
  31639. function PerformanceMonitor(frameSampleSize) {
  31640. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31641. this._enabled = true;
  31642. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31643. }
  31644. /**
  31645. * Samples current frame
  31646. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31647. */
  31648. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31649. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31650. if (!this._enabled)
  31651. return;
  31652. if (this._lastFrameTimeMs != null) {
  31653. var dt = timeMs - this._lastFrameTimeMs;
  31654. this._rollingFrameTime.add(dt);
  31655. }
  31656. this._lastFrameTimeMs = timeMs;
  31657. };
  31658. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31659. /**
  31660. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31661. * @return Average frame time in milliseconds
  31662. */
  31663. get: function () {
  31664. return this._rollingFrameTime.average;
  31665. },
  31666. enumerable: true,
  31667. configurable: true
  31668. });
  31669. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31670. /**
  31671. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31672. * @return Frame time variance in milliseconds squared
  31673. */
  31674. get: function () {
  31675. return this._rollingFrameTime.variance;
  31676. },
  31677. enumerable: true,
  31678. configurable: true
  31679. });
  31680. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31681. /**
  31682. * Returns the frame time of the most recent frame
  31683. * @return Frame time in milliseconds
  31684. */
  31685. get: function () {
  31686. return this._rollingFrameTime.history(0);
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31692. /**
  31693. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31694. * @return Framerate in frames per second
  31695. */
  31696. get: function () {
  31697. return 1000.0 / this._rollingFrameTime.average;
  31698. },
  31699. enumerable: true,
  31700. configurable: true
  31701. });
  31702. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31703. /**
  31704. * Returns the average framerate in frames per second using the most recent frame time
  31705. * @return Framerate in frames per second
  31706. */
  31707. get: function () {
  31708. var history = this._rollingFrameTime.history(0);
  31709. if (history === 0) {
  31710. return 0;
  31711. }
  31712. return 1000.0 / history;
  31713. },
  31714. enumerable: true,
  31715. configurable: true
  31716. });
  31717. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31718. /**
  31719. * Returns true if enough samples have been taken to completely fill the sliding window
  31720. * @return true if saturated
  31721. */
  31722. get: function () {
  31723. return this._rollingFrameTime.isSaturated();
  31724. },
  31725. enumerable: true,
  31726. configurable: true
  31727. });
  31728. /**
  31729. * Enables contributions to the sliding window sample set
  31730. */
  31731. PerformanceMonitor.prototype.enable = function () {
  31732. this._enabled = true;
  31733. };
  31734. /**
  31735. * Disables contributions to the sliding window sample set
  31736. * Samples will not be interpolated over the disabled period
  31737. */
  31738. PerformanceMonitor.prototype.disable = function () {
  31739. this._enabled = false;
  31740. //clear last sample to avoid interpolating over the disabled period when next enabled
  31741. this._lastFrameTimeMs = null;
  31742. this._lastChangeTimeMs = null;
  31743. };
  31744. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31745. /**
  31746. * Returns true if sampling is enabled
  31747. * @return true if enabled
  31748. */
  31749. get: function () {
  31750. return this._enabled;
  31751. },
  31752. enumerable: true,
  31753. configurable: true
  31754. });
  31755. /**
  31756. * Resets performance monitor
  31757. */
  31758. PerformanceMonitor.prototype.reset = function () {
  31759. //clear last sample to avoid interpolating over the disabled period when next enabled
  31760. this._lastFrameTimeMs = null;
  31761. this._lastChangeTimeMs = null;
  31762. //wipe record
  31763. this._rollingFrameTime.reset();
  31764. };
  31765. return PerformanceMonitor;
  31766. }());
  31767. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31768. /**
  31769. * RollingAverage
  31770. *
  31771. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31772. */
  31773. var RollingAverage = /** @class */ (function () {
  31774. /**
  31775. * constructor
  31776. * @param length The number of samples required to saturate the sliding window
  31777. */
  31778. function RollingAverage(length) {
  31779. this._samples = new Array(length);
  31780. this.reset();
  31781. }
  31782. /**
  31783. * Adds a sample to the sample set
  31784. * @param v The sample value
  31785. */
  31786. RollingAverage.prototype.add = function (v) {
  31787. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31788. var delta;
  31789. //we need to check if we've already wrapped round
  31790. if (this.isSaturated()) {
  31791. //remove bottom of stack from mean
  31792. var bottomValue = this._samples[this._pos];
  31793. delta = bottomValue - this.average;
  31794. this.average -= delta / (this._sampleCount - 1);
  31795. this._m2 -= delta * (bottomValue - this.average);
  31796. }
  31797. else {
  31798. this._sampleCount++;
  31799. }
  31800. //add new value to mean
  31801. delta = v - this.average;
  31802. this.average += delta / (this._sampleCount);
  31803. this._m2 += delta * (v - this.average);
  31804. //set the new variance
  31805. this.variance = this._m2 / (this._sampleCount - 1);
  31806. this._samples[this._pos] = v;
  31807. this._pos++;
  31808. this._pos %= this._samples.length; //positive wrap around
  31809. };
  31810. /**
  31811. * Returns previously added values or null if outside of history or outside the sliding window domain
  31812. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  31813. * @return Value previously recorded with add() or null if outside of range
  31814. */
  31815. RollingAverage.prototype.history = function (i) {
  31816. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  31817. return 0;
  31818. }
  31819. var i0 = this._wrapPosition(this._pos - 1.0);
  31820. return this._samples[this._wrapPosition(i0 - i)];
  31821. };
  31822. /**
  31823. * Returns true if enough samples have been taken to completely fill the sliding window
  31824. * @return true if sample-set saturated
  31825. */
  31826. RollingAverage.prototype.isSaturated = function () {
  31827. return this._sampleCount >= this._samples.length;
  31828. };
  31829. /**
  31830. * Resets the rolling average (equivalent to 0 samples taken so far)
  31831. */
  31832. RollingAverage.prototype.reset = function () {
  31833. this.average = 0;
  31834. this.variance = 0;
  31835. this._sampleCount = 0;
  31836. this._pos = 0;
  31837. this._m2 = 0;
  31838. };
  31839. /**
  31840. * Wraps a value around the sample range boundaries
  31841. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  31842. * @return Wrapped position in sample range
  31843. */
  31844. RollingAverage.prototype._wrapPosition = function (i) {
  31845. var max = this._samples.length;
  31846. return ((i % max) + max) % max;
  31847. };
  31848. return RollingAverage;
  31849. }());
  31850. BABYLON.RollingAverage = RollingAverage;
  31851. })(BABYLON || (BABYLON = {}));
  31852. //# sourceMappingURL=babylon.performanceMonitor.js.map
  31853. var BABYLON;
  31854. (function (BABYLON) {
  31855. /**
  31856. * This groups together the common properties used for image processing either in direct forward pass
  31857. * or through post processing effect depending on the use of the image processing pipeline in your scene
  31858. * or not.
  31859. */
  31860. var ImageProcessingConfiguration = /** @class */ (function () {
  31861. function ImageProcessingConfiguration() {
  31862. /**
  31863. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  31864. */
  31865. this.colorCurves = new BABYLON.ColorCurves();
  31866. this._colorCurvesEnabled = false;
  31867. this._colorGradingEnabled = false;
  31868. this._colorGradingWithGreenDepth = true;
  31869. this._colorGradingBGR = true;
  31870. this._exposure = 1.0;
  31871. this._toneMappingEnabled = false;
  31872. this._contrast = 1.0;
  31873. /**
  31874. * Vignette stretch size.
  31875. */
  31876. this.vignetteStretch = 0;
  31877. /**
  31878. * Vignette centre X Offset.
  31879. */
  31880. this.vignetteCentreX = 0;
  31881. /**
  31882. * Vignette centre Y Offset.
  31883. */
  31884. this.vignetteCentreY = 0;
  31885. /**
  31886. * Vignette weight or intensity of the vignette effect.
  31887. */
  31888. this.vignetteWeight = 1.5;
  31889. /**
  31890. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  31891. * if vignetteEnabled is set to true.
  31892. */
  31893. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  31894. /**
  31895. * Camera field of view used by the Vignette effect.
  31896. */
  31897. this.vignetteCameraFov = 0.5;
  31898. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  31899. this._vignetteEnabled = false;
  31900. this._applyByPostProcess = false;
  31901. /**
  31902. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  31903. * @type {BABYLON.Observable}
  31904. */
  31905. this.onUpdateParameters = new BABYLON.Observable();
  31906. }
  31907. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  31908. /**
  31909. * Gets wether the color curves effect is enabled.
  31910. */
  31911. get: function () {
  31912. return this._colorCurvesEnabled;
  31913. },
  31914. /**
  31915. * Sets wether the color curves effect is enabled.
  31916. */
  31917. set: function (value) {
  31918. if (this._colorCurvesEnabled === value) {
  31919. return;
  31920. }
  31921. this._colorCurvesEnabled = value;
  31922. this._updateParameters();
  31923. },
  31924. enumerable: true,
  31925. configurable: true
  31926. });
  31927. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  31928. /**
  31929. * Gets wether the color grading effect is enabled.
  31930. */
  31931. get: function () {
  31932. return this._colorGradingEnabled;
  31933. },
  31934. /**
  31935. * Sets wether the color grading effect is enabled.
  31936. */
  31937. set: function (value) {
  31938. if (this._colorGradingEnabled === value) {
  31939. return;
  31940. }
  31941. this._colorGradingEnabled = value;
  31942. this._updateParameters();
  31943. },
  31944. enumerable: true,
  31945. configurable: true
  31946. });
  31947. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  31948. /**
  31949. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  31950. */
  31951. get: function () {
  31952. return this._colorGradingWithGreenDepth;
  31953. },
  31954. /**
  31955. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  31956. */
  31957. set: function (value) {
  31958. if (this._colorGradingWithGreenDepth === value) {
  31959. return;
  31960. }
  31961. this._colorGradingWithGreenDepth = value;
  31962. this._updateParameters();
  31963. },
  31964. enumerable: true,
  31965. configurable: true
  31966. });
  31967. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  31968. /**
  31969. * Gets wether the color grading texture contains BGR values.
  31970. */
  31971. get: function () {
  31972. return this._colorGradingBGR;
  31973. },
  31974. /**
  31975. * Sets wether the color grading texture contains BGR values.
  31976. */
  31977. set: function (value) {
  31978. if (this._colorGradingBGR === value) {
  31979. return;
  31980. }
  31981. this._colorGradingBGR = value;
  31982. this._updateParameters();
  31983. },
  31984. enumerable: true,
  31985. configurable: true
  31986. });
  31987. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  31988. /**
  31989. * Gets the Exposure used in the effect.
  31990. */
  31991. get: function () {
  31992. return this._exposure;
  31993. },
  31994. /**
  31995. * Sets the Exposure used in the effect.
  31996. */
  31997. set: function (value) {
  31998. if (this._exposure === value) {
  31999. return;
  32000. }
  32001. this._exposure = value;
  32002. this._updateParameters();
  32003. },
  32004. enumerable: true,
  32005. configurable: true
  32006. });
  32007. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32008. /**
  32009. * Gets wether the tone mapping effect is enabled.
  32010. */
  32011. get: function () {
  32012. return this._toneMappingEnabled;
  32013. },
  32014. /**
  32015. * Sets wether the tone mapping effect is enabled.
  32016. */
  32017. set: function (value) {
  32018. if (this._toneMappingEnabled === value) {
  32019. return;
  32020. }
  32021. this._toneMappingEnabled = value;
  32022. this._updateParameters();
  32023. },
  32024. enumerable: true,
  32025. configurable: true
  32026. });
  32027. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32028. /**
  32029. * Gets the contrast used in the effect.
  32030. */
  32031. get: function () {
  32032. return this._contrast;
  32033. },
  32034. /**
  32035. * Sets the contrast used in the effect.
  32036. */
  32037. set: function (value) {
  32038. if (this._contrast === value) {
  32039. return;
  32040. }
  32041. this._contrast = value;
  32042. this._updateParameters();
  32043. },
  32044. enumerable: true,
  32045. configurable: true
  32046. });
  32047. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32048. /**
  32049. * Gets the vignette blend mode allowing different kind of effect.
  32050. */
  32051. get: function () {
  32052. return this._vignetteBlendMode;
  32053. },
  32054. /**
  32055. * Sets the vignette blend mode allowing different kind of effect.
  32056. */
  32057. set: function (value) {
  32058. if (this._vignetteBlendMode === value) {
  32059. return;
  32060. }
  32061. this._vignetteBlendMode = value;
  32062. this._updateParameters();
  32063. },
  32064. enumerable: true,
  32065. configurable: true
  32066. });
  32067. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32068. /**
  32069. * Gets wether the vignette effect is enabled.
  32070. */
  32071. get: function () {
  32072. return this._vignetteEnabled;
  32073. },
  32074. /**
  32075. * Sets wether the vignette effect is enabled.
  32076. */
  32077. set: function (value) {
  32078. if (this._vignetteEnabled === value) {
  32079. return;
  32080. }
  32081. this._vignetteEnabled = value;
  32082. this._updateParameters();
  32083. },
  32084. enumerable: true,
  32085. configurable: true
  32086. });
  32087. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32088. /**
  32089. * Gets wether the image processing is applied through a post process or not.
  32090. */
  32091. get: function () {
  32092. return this._applyByPostProcess;
  32093. },
  32094. /**
  32095. * Sets wether the image processing is applied through a post process or not.
  32096. */
  32097. set: function (value) {
  32098. if (this._applyByPostProcess === value) {
  32099. return;
  32100. }
  32101. this._applyByPostProcess = value;
  32102. this._updateParameters();
  32103. },
  32104. enumerable: true,
  32105. configurable: true
  32106. });
  32107. /**
  32108. * Method called each time the image processing information changes requires to recompile the effect.
  32109. */
  32110. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32111. this.onUpdateParameters.notifyObservers(this);
  32112. };
  32113. ImageProcessingConfiguration.prototype.getClassName = function () {
  32114. return "ImageProcessingConfiguration";
  32115. };
  32116. /**
  32117. * Prepare the list of uniforms associated with the Image Processing effects.
  32118. * @param uniformsList The list of uniforms used in the effect
  32119. * @param defines the list of defines currently in use
  32120. */
  32121. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32122. if (defines.EXPOSURE) {
  32123. uniforms.push("exposureLinear");
  32124. }
  32125. if (defines.CONTRAST) {
  32126. uniforms.push("contrast");
  32127. }
  32128. if (defines.COLORGRADING) {
  32129. uniforms.push("colorTransformSettings");
  32130. }
  32131. if (defines.VIGNETTE) {
  32132. uniforms.push("vInverseScreenSize");
  32133. uniforms.push("vignetteSettings1");
  32134. uniforms.push("vignetteSettings2");
  32135. }
  32136. if (defines.COLORCURVES) {
  32137. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32138. }
  32139. };
  32140. /**
  32141. * Prepare the list of samplers associated with the Image Processing effects.
  32142. * @param uniformsList The list of uniforms used in the effect
  32143. * @param defines the list of defines currently in use
  32144. */
  32145. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32146. if (defines.COLORGRADING) {
  32147. samplersList.push("txColorTransform");
  32148. }
  32149. };
  32150. /**
  32151. * Prepare the list of defines associated to the shader.
  32152. * @param defines the list of defines to complete
  32153. */
  32154. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32155. if (forPostProcess === void 0) { forPostProcess = false; }
  32156. if (forPostProcess !== this.applyByPostProcess) {
  32157. defines.VIGNETTE = false;
  32158. defines.TONEMAPPING = false;
  32159. defines.CONTRAST = false;
  32160. defines.EXPOSURE = false;
  32161. defines.COLORCURVES = false;
  32162. defines.COLORGRADING = false;
  32163. defines.COLORGRADING3D = false;
  32164. defines.IMAGEPROCESSING = false;
  32165. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32166. return;
  32167. }
  32168. defines.VIGNETTE = this.vignetteEnabled;
  32169. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32170. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32171. defines.TONEMAPPING = this.toneMappingEnabled;
  32172. defines.CONTRAST = (this.contrast !== 1.0);
  32173. defines.EXPOSURE = (this.exposure !== 1.0);
  32174. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32175. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32176. if (defines.COLORGRADING) {
  32177. var texture = this.colorGradingTexture;
  32178. defines.COLORGRADING3D = (texture.getScene().getEngine().webGLVersion > 1) ? true : false;
  32179. }
  32180. else {
  32181. defines.COLORGRADING3D = false;
  32182. }
  32183. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32184. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32185. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32186. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32187. };
  32188. /**
  32189. * Returns true if all the image processing information are ready.
  32190. */
  32191. ImageProcessingConfiguration.prototype.isReady = function () {
  32192. // Color Grading texure can not be none blocking.
  32193. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32194. };
  32195. /**
  32196. * Binds the image processing to the shader.
  32197. * @param effect The effect to bind to
  32198. */
  32199. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32200. if (aspectRatio === void 0) { aspectRatio = 1; }
  32201. // Color Curves
  32202. if (this._colorCurvesEnabled && this.colorCurves) {
  32203. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32204. }
  32205. // Vignette
  32206. if (this._vignetteEnabled) {
  32207. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32208. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32209. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32210. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32211. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32212. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32213. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32214. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32215. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32216. var vignettePower = -2.0 * this.vignetteWeight;
  32217. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32218. }
  32219. // Exposure
  32220. effect.setFloat("exposureLinear", this.exposure);
  32221. // Contrast
  32222. effect.setFloat("contrast", this.contrast);
  32223. // Color transform settings
  32224. if (this.colorGradingTexture) {
  32225. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32226. var textureSize = this.colorGradingTexture.getSize().height;
  32227. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32228. 0.5 / textureSize, // textureOffset
  32229. textureSize, // textureSize
  32230. this.colorGradingTexture.level // weight
  32231. );
  32232. }
  32233. };
  32234. /**
  32235. * Clones the current image processing instance.
  32236. * @return The cloned image processing
  32237. */
  32238. ImageProcessingConfiguration.prototype.clone = function () {
  32239. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32240. };
  32241. /**
  32242. * Serializes the current image processing instance to a json representation.
  32243. * @return a JSON representation
  32244. */
  32245. ImageProcessingConfiguration.prototype.serialize = function () {
  32246. return BABYLON.SerializationHelper.Serialize(this);
  32247. };
  32248. /**
  32249. * Parses the image processing from a json representation.
  32250. * @param source the JSON source to parse
  32251. * @return The parsed image processing
  32252. */
  32253. ImageProcessingConfiguration.Parse = function (source) {
  32254. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32255. };
  32256. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32257. /**
  32258. * Used to apply the vignette as a mix with the pixel color.
  32259. */
  32260. get: function () {
  32261. return this._VIGNETTEMODE_MULTIPLY;
  32262. },
  32263. enumerable: true,
  32264. configurable: true
  32265. });
  32266. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32267. /**
  32268. * Used to apply the vignette as a replacement of the pixel color.
  32269. */
  32270. get: function () {
  32271. return this._VIGNETTEMODE_OPAQUE;
  32272. },
  32273. enumerable: true,
  32274. configurable: true
  32275. });
  32276. // Static constants associated to the image processing.
  32277. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32278. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32279. __decorate([
  32280. BABYLON.serializeAsColorCurves()
  32281. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32282. __decorate([
  32283. BABYLON.serialize()
  32284. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32285. __decorate([
  32286. BABYLON.serializeAsTexture()
  32287. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32288. __decorate([
  32289. BABYLON.serialize()
  32290. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32291. __decorate([
  32292. BABYLON.serialize()
  32293. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32294. __decorate([
  32295. BABYLON.serialize()
  32296. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32297. __decorate([
  32298. BABYLON.serialize()
  32299. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32300. __decorate([
  32301. BABYLON.serialize()
  32302. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32303. __decorate([
  32304. BABYLON.serialize()
  32305. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32306. __decorate([
  32307. BABYLON.serialize()
  32308. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32309. __decorate([
  32310. BABYLON.serialize()
  32311. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32312. __decorate([
  32313. BABYLON.serialize()
  32314. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32315. __decorate([
  32316. BABYLON.serialize()
  32317. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32318. __decorate([
  32319. BABYLON.serializeAsColor4()
  32320. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32321. __decorate([
  32322. BABYLON.serialize()
  32323. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32324. __decorate([
  32325. BABYLON.serialize()
  32326. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32327. __decorate([
  32328. BABYLON.serialize()
  32329. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32333. return ImageProcessingConfiguration;
  32334. }());
  32335. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32336. })(BABYLON || (BABYLON = {}));
  32337. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32338. var BABYLON;
  32339. (function (BABYLON) {
  32340. /**
  32341. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32342. * It can help converting any input color in a desired output one. This can then be used to create effects
  32343. * from sepia, black and white to sixties or futuristic rendering...
  32344. *
  32345. * The only supported format is currently 3dl.
  32346. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32347. */
  32348. var ColorGradingTexture = /** @class */ (function (_super) {
  32349. __extends(ColorGradingTexture, _super);
  32350. /**
  32351. * Instantiates a ColorGradingTexture from the following parameters.
  32352. *
  32353. * @param url The location of the color gradind data (currently only supporting 3dl)
  32354. * @param scene The scene the texture will be used in
  32355. */
  32356. function ColorGradingTexture(url, scene) {
  32357. var _this = _super.call(this, scene) || this;
  32358. if (!url) {
  32359. return _this;
  32360. }
  32361. _this._engine = scene.getEngine();
  32362. _this._textureMatrix = BABYLON.Matrix.Identity();
  32363. _this.name = url;
  32364. _this.url = url;
  32365. _this.hasAlpha = false;
  32366. _this.isCube = false;
  32367. _this.is3D = _this._engine.webGLVersion > 1;
  32368. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32369. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32370. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32371. _this.anisotropicFilteringLevel = 1;
  32372. _this._texture = _this._getFromCache(url, true);
  32373. if (!_this._texture) {
  32374. if (!scene.useDelayedTextureLoading) {
  32375. _this.loadTexture();
  32376. }
  32377. else {
  32378. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32379. }
  32380. }
  32381. return _this;
  32382. }
  32383. /**
  32384. * Returns the texture matrix used in most of the material.
  32385. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32386. */
  32387. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32388. return this._textureMatrix;
  32389. };
  32390. /**
  32391. * Occurs when the file being loaded is a .3dl LUT file.
  32392. */
  32393. ColorGradingTexture.prototype.load3dlTexture = function () {
  32394. var engine = this._engine;
  32395. var texture;
  32396. if (engine.webGLVersion === 1) {
  32397. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32398. }
  32399. else {
  32400. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32401. }
  32402. this._texture = texture;
  32403. var callback = function (text) {
  32404. var data = null;
  32405. var tempData = null;
  32406. var line;
  32407. var lines = text.split('\n');
  32408. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32409. var maxColor = 0;
  32410. for (var i = 0; i < lines.length; i++) {
  32411. line = lines[i];
  32412. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32413. continue;
  32414. if (line.indexOf('#') === 0)
  32415. continue;
  32416. var words = line.split(" ");
  32417. if (size === 0) {
  32418. // Number of space + one
  32419. size = words.length;
  32420. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32421. tempData = new Float32Array(size * size * size * 4);
  32422. continue;
  32423. }
  32424. if (size != 0) {
  32425. var r = Math.max(parseInt(words[0]), 0);
  32426. var g = Math.max(parseInt(words[1]), 0);
  32427. var b = Math.max(parseInt(words[2]), 0);
  32428. maxColor = Math.max(r, maxColor);
  32429. maxColor = Math.max(g, maxColor);
  32430. maxColor = Math.max(b, maxColor);
  32431. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32432. if (tempData) {
  32433. tempData[pixelStorageIndex + 0] = r;
  32434. tempData[pixelStorageIndex + 1] = g;
  32435. tempData[pixelStorageIndex + 2] = b;
  32436. }
  32437. pixelIndexSlice++;
  32438. if (pixelIndexSlice % size == 0) {
  32439. pixelIndexH++;
  32440. pixelIndexSlice = 0;
  32441. if (pixelIndexH % size == 0) {
  32442. pixelIndexW++;
  32443. pixelIndexH = 0;
  32444. }
  32445. }
  32446. }
  32447. }
  32448. if (tempData && data) {
  32449. for (var i = 0; i < tempData.length; i++) {
  32450. if (i > 0 && (i + 1) % 4 === 0) {
  32451. data[i] = 255;
  32452. }
  32453. else {
  32454. var value = tempData[i];
  32455. data[i] = (value / maxColor * 255);
  32456. }
  32457. }
  32458. }
  32459. if (texture.is3D) {
  32460. texture.updateSize(size, size, size);
  32461. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32462. }
  32463. else {
  32464. texture.updateSize(size * size, size);
  32465. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32466. }
  32467. };
  32468. BABYLON.Tools.LoadFile(this.url, callback);
  32469. return this._texture;
  32470. };
  32471. /**
  32472. * Starts the loading process of the texture.
  32473. */
  32474. ColorGradingTexture.prototype.loadTexture = function () {
  32475. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32476. this.load3dlTexture();
  32477. }
  32478. };
  32479. /**
  32480. * Clones the color gradind texture.
  32481. */
  32482. ColorGradingTexture.prototype.clone = function () {
  32483. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32484. // Base texture
  32485. newTexture.level = this.level;
  32486. return newTexture;
  32487. };
  32488. /**
  32489. * Called during delayed load for textures.
  32490. */
  32491. ColorGradingTexture.prototype.delayLoad = function () {
  32492. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32493. return;
  32494. }
  32495. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32496. this._texture = this._getFromCache(this.url, true);
  32497. if (!this._texture) {
  32498. this.loadTexture();
  32499. }
  32500. };
  32501. /**
  32502. * Parses a color grading texture serialized by Babylon.
  32503. * @param parsedTexture The texture information being parsedTexture
  32504. * @param scene The scene to load the texture in
  32505. * @param rootUrl The root url of the data assets to load
  32506. * @return A color gradind texture
  32507. */
  32508. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32509. var texture = null;
  32510. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32511. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32512. texture.name = parsedTexture.name;
  32513. texture.level = parsedTexture.level;
  32514. }
  32515. return texture;
  32516. };
  32517. /**
  32518. * Serializes the LUT texture to json format.
  32519. */
  32520. ColorGradingTexture.prototype.serialize = function () {
  32521. if (!this.name) {
  32522. return null;
  32523. }
  32524. var serializationObject = {};
  32525. serializationObject.name = this.name;
  32526. serializationObject.level = this.level;
  32527. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32528. return serializationObject;
  32529. };
  32530. /**
  32531. * Empty line regex stored for GC.
  32532. */
  32533. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32534. return ColorGradingTexture;
  32535. }(BABYLON.BaseTexture));
  32536. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32537. })(BABYLON || (BABYLON = {}));
  32538. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32539. var BABYLON;
  32540. (function (BABYLON) {
  32541. /**
  32542. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32543. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32544. * 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;
  32545. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32546. */
  32547. var ColorCurves = /** @class */ (function () {
  32548. function ColorCurves() {
  32549. this._dirty = true;
  32550. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32551. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32552. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32553. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32554. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32555. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32556. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32557. this._globalHue = 30;
  32558. this._globalDensity = 0;
  32559. this._globalSaturation = 0;
  32560. this._globalExposure = 0;
  32561. this._highlightsHue = 30;
  32562. this._highlightsDensity = 0;
  32563. this._highlightsSaturation = 0;
  32564. this._highlightsExposure = 0;
  32565. this._midtonesHue = 30;
  32566. this._midtonesDensity = 0;
  32567. this._midtonesSaturation = 0;
  32568. this._midtonesExposure = 0;
  32569. this._shadowsHue = 30;
  32570. this._shadowsDensity = 0;
  32571. this._shadowsSaturation = 0;
  32572. this._shadowsExposure = 0;
  32573. }
  32574. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32575. /**
  32576. * Gets the global Hue value.
  32577. * 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).
  32578. */
  32579. get: function () {
  32580. return this._globalHue;
  32581. },
  32582. /**
  32583. * Sets the global Hue value.
  32584. * 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).
  32585. */
  32586. set: function (value) {
  32587. this._globalHue = value;
  32588. this._dirty = true;
  32589. },
  32590. enumerable: true,
  32591. configurable: true
  32592. });
  32593. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32594. /**
  32595. * Gets the global Density value.
  32596. * 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.
  32597. * Values less than zero provide a filter of opposite hue.
  32598. */
  32599. get: function () {
  32600. return this._globalDensity;
  32601. },
  32602. /**
  32603. * Sets the global Density value.
  32604. * 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.
  32605. * Values less than zero provide a filter of opposite hue.
  32606. */
  32607. set: function (value) {
  32608. this._globalDensity = value;
  32609. this._dirty = true;
  32610. },
  32611. enumerable: true,
  32612. configurable: true
  32613. });
  32614. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32615. /**
  32616. * Gets the global Saturation value.
  32617. * 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.
  32618. */
  32619. get: function () {
  32620. return this._globalSaturation;
  32621. },
  32622. /**
  32623. * Sets the global Saturation value.
  32624. * 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.
  32625. */
  32626. set: function (value) {
  32627. this._globalSaturation = value;
  32628. this._dirty = true;
  32629. },
  32630. enumerable: true,
  32631. configurable: true
  32632. });
  32633. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32634. /**
  32635. * Gets the highlights Hue value.
  32636. * 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).
  32637. */
  32638. get: function () {
  32639. return this._highlightsHue;
  32640. },
  32641. /**
  32642. * Sets the highlights Hue value.
  32643. * 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).
  32644. */
  32645. set: function (value) {
  32646. this._highlightsHue = value;
  32647. this._dirty = true;
  32648. },
  32649. enumerable: true,
  32650. configurable: true
  32651. });
  32652. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32653. /**
  32654. * Gets the highlights Density value.
  32655. * 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.
  32656. * Values less than zero provide a filter of opposite hue.
  32657. */
  32658. get: function () {
  32659. return this._highlightsDensity;
  32660. },
  32661. /**
  32662. * Sets the highlights Density value.
  32663. * 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.
  32664. * Values less than zero provide a filter of opposite hue.
  32665. */
  32666. set: function (value) {
  32667. this._highlightsDensity = value;
  32668. this._dirty = true;
  32669. },
  32670. enumerable: true,
  32671. configurable: true
  32672. });
  32673. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32674. /**
  32675. * Gets the highlights Saturation value.
  32676. * 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.
  32677. */
  32678. get: function () {
  32679. return this._highlightsSaturation;
  32680. },
  32681. /**
  32682. * Sets the highlights Saturation value.
  32683. * 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.
  32684. */
  32685. set: function (value) {
  32686. this._highlightsSaturation = value;
  32687. this._dirty = true;
  32688. },
  32689. enumerable: true,
  32690. configurable: true
  32691. });
  32692. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32693. /**
  32694. * Gets the highlights Exposure value.
  32695. * 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.
  32696. */
  32697. get: function () {
  32698. return this._highlightsExposure;
  32699. },
  32700. /**
  32701. * Sets the highlights Exposure value.
  32702. * 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.
  32703. */
  32704. set: function (value) {
  32705. this._highlightsExposure = value;
  32706. this._dirty = true;
  32707. },
  32708. enumerable: true,
  32709. configurable: true
  32710. });
  32711. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32712. /**
  32713. * Gets the midtones Hue value.
  32714. * 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).
  32715. */
  32716. get: function () {
  32717. return this._midtonesHue;
  32718. },
  32719. /**
  32720. * Sets the midtones Hue value.
  32721. * 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).
  32722. */
  32723. set: function (value) {
  32724. this._midtonesHue = value;
  32725. this._dirty = true;
  32726. },
  32727. enumerable: true,
  32728. configurable: true
  32729. });
  32730. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32731. /**
  32732. * Gets the midtones Density value.
  32733. * 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.
  32734. * Values less than zero provide a filter of opposite hue.
  32735. */
  32736. get: function () {
  32737. return this._midtonesDensity;
  32738. },
  32739. /**
  32740. * Sets the midtones Density value.
  32741. * 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.
  32742. * Values less than zero provide a filter of opposite hue.
  32743. */
  32744. set: function (value) {
  32745. this._midtonesDensity = value;
  32746. this._dirty = true;
  32747. },
  32748. enumerable: true,
  32749. configurable: true
  32750. });
  32751. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32752. /**
  32753. * Gets the midtones Saturation value.
  32754. * 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.
  32755. */
  32756. get: function () {
  32757. return this._midtonesSaturation;
  32758. },
  32759. /**
  32760. * Sets the midtones Saturation value.
  32761. * 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.
  32762. */
  32763. set: function (value) {
  32764. this._midtonesSaturation = value;
  32765. this._dirty = true;
  32766. },
  32767. enumerable: true,
  32768. configurable: true
  32769. });
  32770. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32771. /**
  32772. * Gets the midtones Exposure value.
  32773. * 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.
  32774. */
  32775. get: function () {
  32776. return this._midtonesExposure;
  32777. },
  32778. /**
  32779. * Sets the midtones Exposure value.
  32780. * 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.
  32781. */
  32782. set: function (value) {
  32783. this._midtonesExposure = value;
  32784. this._dirty = true;
  32785. },
  32786. enumerable: true,
  32787. configurable: true
  32788. });
  32789. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32790. /**
  32791. * Gets the shadows Hue value.
  32792. * 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).
  32793. */
  32794. get: function () {
  32795. return this._shadowsHue;
  32796. },
  32797. /**
  32798. * Sets the shadows Hue value.
  32799. * 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).
  32800. */
  32801. set: function (value) {
  32802. this._shadowsHue = value;
  32803. this._dirty = true;
  32804. },
  32805. enumerable: true,
  32806. configurable: true
  32807. });
  32808. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  32809. /**
  32810. * Gets the shadows Density value.
  32811. * 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.
  32812. * Values less than zero provide a filter of opposite hue.
  32813. */
  32814. get: function () {
  32815. return this._shadowsDensity;
  32816. },
  32817. /**
  32818. * Sets the shadows Density value.
  32819. * 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.
  32820. * Values less than zero provide a filter of opposite hue.
  32821. */
  32822. set: function (value) {
  32823. this._shadowsDensity = value;
  32824. this._dirty = true;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  32830. /**
  32831. * Gets the shadows Saturation value.
  32832. * 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.
  32833. */
  32834. get: function () {
  32835. return this._shadowsSaturation;
  32836. },
  32837. /**
  32838. * Sets the shadows Saturation value.
  32839. * 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.
  32840. */
  32841. set: function (value) {
  32842. this._shadowsSaturation = value;
  32843. this._dirty = true;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  32849. /**
  32850. * Gets the shadows Exposure value.
  32851. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32852. */
  32853. get: function () {
  32854. return this._shadowsExposure;
  32855. },
  32856. /**
  32857. * Sets the shadows Exposure value.
  32858. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  32859. */
  32860. set: function (value) {
  32861. this._shadowsExposure = value;
  32862. this._dirty = true;
  32863. },
  32864. enumerable: true,
  32865. configurable: true
  32866. });
  32867. ColorCurves.prototype.getClassName = function () {
  32868. return "ColorCurves";
  32869. };
  32870. /**
  32871. * Binds the color curves to the shader.
  32872. * @param colorCurves The color curve to bind
  32873. * @param effect The effect to bind to
  32874. */
  32875. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  32876. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  32877. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  32878. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  32879. if (colorCurves._dirty) {
  32880. colorCurves._dirty = false;
  32881. // Fill in global info.
  32882. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  32883. // Compute highlights info.
  32884. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  32885. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  32886. // Compute midtones info.
  32887. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  32888. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  32889. // Compute shadows info.
  32890. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  32891. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  32892. // Compute deltas (neutral is midtones).
  32893. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  32894. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  32895. }
  32896. if (effect) {
  32897. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  32898. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  32899. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  32900. }
  32901. };
  32902. /**
  32903. * Prepare the list of uniforms associated with the ColorCurves effects.
  32904. * @param uniformsList The list of uniforms used in the effect
  32905. */
  32906. ColorCurves.PrepareUniforms = function (uniformsList) {
  32907. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  32908. };
  32909. /**
  32910. * Returns color grading data based on a hue, density, saturation and exposure value.
  32911. * @param filterHue The hue of the color filter.
  32912. * @param filterDensity The density of the color filter.
  32913. * @param saturation The saturation.
  32914. * @param exposure The exposure.
  32915. * @param result The result data container.
  32916. */
  32917. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  32918. if (hue == null) {
  32919. return;
  32920. }
  32921. hue = ColorCurves.clamp(hue, 0, 360);
  32922. density = ColorCurves.clamp(density, -100, 100);
  32923. saturation = ColorCurves.clamp(saturation, -100, 100);
  32924. exposure = ColorCurves.clamp(exposure, -100, 100);
  32925. // Remap the slider/config filter density with non-linear mapping and also scale by half
  32926. // so that the maximum filter density is only 50% control. This provides fine control
  32927. // for small values and reasonable range.
  32928. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  32929. density *= 0.5;
  32930. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  32931. if (density < 0) {
  32932. density *= -1;
  32933. hue = (hue + 180) % 360;
  32934. }
  32935. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  32936. result.scaleToRef(2, result);
  32937. result.a = 1 + 0.01 * saturation;
  32938. };
  32939. /**
  32940. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  32941. * @param value The input slider value in range [-100,100].
  32942. * @returns Adjusted value.
  32943. */
  32944. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  32945. value /= 100;
  32946. var x = Math.abs(value);
  32947. x = Math.pow(x, 2);
  32948. if (value < 0) {
  32949. x *= -1;
  32950. }
  32951. x *= 100;
  32952. return x;
  32953. };
  32954. /**
  32955. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  32956. * @param hue The hue (H) input.
  32957. * @param saturation The saturation (S) input.
  32958. * @param brightness The brightness (B) input.
  32959. * @result An RGBA color represented as Vector4.
  32960. */
  32961. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  32962. var h = ColorCurves.clamp(hue, 0, 360);
  32963. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  32964. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  32965. if (s === 0) {
  32966. result.r = v;
  32967. result.g = v;
  32968. result.b = v;
  32969. }
  32970. else {
  32971. // sector 0 to 5
  32972. h /= 60;
  32973. var i = Math.floor(h);
  32974. // fractional part of h
  32975. var f = h - i;
  32976. var p = v * (1 - s);
  32977. var q = v * (1 - s * f);
  32978. var t = v * (1 - s * (1 - f));
  32979. switch (i) {
  32980. case 0:
  32981. result.r = v;
  32982. result.g = t;
  32983. result.b = p;
  32984. break;
  32985. case 1:
  32986. result.r = q;
  32987. result.g = v;
  32988. result.b = p;
  32989. break;
  32990. case 2:
  32991. result.r = p;
  32992. result.g = v;
  32993. result.b = t;
  32994. break;
  32995. case 3:
  32996. result.r = p;
  32997. result.g = q;
  32998. result.b = v;
  32999. break;
  33000. case 4:
  33001. result.r = t;
  33002. result.g = p;
  33003. result.b = v;
  33004. break;
  33005. default:// case 5:
  33006. result.r = v;
  33007. result.g = p;
  33008. result.b = q;
  33009. break;
  33010. }
  33011. }
  33012. result.a = 1;
  33013. };
  33014. /**
  33015. * Returns a value clamped between min and max
  33016. * @param value The value to clamp
  33017. * @param min The minimum of value
  33018. * @param max The maximum of value
  33019. * @returns The clamped value.
  33020. */
  33021. ColorCurves.clamp = function (value, min, max) {
  33022. return Math.min(Math.max(value, min), max);
  33023. };
  33024. /**
  33025. * Clones the current color curve instance.
  33026. * @return The cloned curves
  33027. */
  33028. ColorCurves.prototype.clone = function () {
  33029. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33030. };
  33031. /**
  33032. * Serializes the current color curve instance to a json representation.
  33033. * @return a JSON representation
  33034. */
  33035. ColorCurves.prototype.serialize = function () {
  33036. return BABYLON.SerializationHelper.Serialize(this);
  33037. };
  33038. /**
  33039. * Parses the color curve from a json representation.
  33040. * @param source the JSON source to parse
  33041. * @return The parsed curves
  33042. */
  33043. ColorCurves.Parse = function (source) {
  33044. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33045. };
  33046. __decorate([
  33047. BABYLON.serialize()
  33048. ], ColorCurves.prototype, "_globalHue", void 0);
  33049. __decorate([
  33050. BABYLON.serialize()
  33051. ], ColorCurves.prototype, "_globalDensity", void 0);
  33052. __decorate([
  33053. BABYLON.serialize()
  33054. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33055. __decorate([
  33056. BABYLON.serialize()
  33057. ], ColorCurves.prototype, "_globalExposure", void 0);
  33058. __decorate([
  33059. BABYLON.serialize()
  33060. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33061. __decorate([
  33062. BABYLON.serialize()
  33063. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33064. __decorate([
  33065. BABYLON.serialize()
  33066. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33067. __decorate([
  33068. BABYLON.serialize()
  33069. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33070. __decorate([
  33071. BABYLON.serialize()
  33072. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33073. __decorate([
  33074. BABYLON.serialize()
  33075. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33076. __decorate([
  33077. BABYLON.serialize()
  33078. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33079. __decorate([
  33080. BABYLON.serialize()
  33081. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33082. return ColorCurves;
  33083. }());
  33084. BABYLON.ColorCurves = ColorCurves;
  33085. })(BABYLON || (BABYLON = {}));
  33086. //# sourceMappingURL=babylon.colorCurves.js.map
  33087. var BABYLON;
  33088. (function (BABYLON) {
  33089. var StandardMaterialDefines = /** @class */ (function (_super) {
  33090. __extends(StandardMaterialDefines, _super);
  33091. function StandardMaterialDefines() {
  33092. var _this = _super.call(this) || this;
  33093. _this.MAINUV1 = false;
  33094. _this.MAINUV2 = false;
  33095. _this.DIFFUSE = false;
  33096. _this.DIFFUSEDIRECTUV = 0;
  33097. _this.AMBIENT = false;
  33098. _this.AMBIENTDIRECTUV = 0;
  33099. _this.OPACITY = false;
  33100. _this.OPACITYDIRECTUV = 0;
  33101. _this.OPACITYRGB = false;
  33102. _this.REFLECTION = false;
  33103. _this.EMISSIVE = false;
  33104. _this.EMISSIVEDIRECTUV = 0;
  33105. _this.SPECULAR = false;
  33106. _this.SPECULARDIRECTUV = 0;
  33107. _this.BUMP = false;
  33108. _this.BUMPDIRECTUV = 0;
  33109. _this.PARALLAX = false;
  33110. _this.PARALLAXOCCLUSION = false;
  33111. _this.SPECULAROVERALPHA = false;
  33112. _this.CLIPPLANE = false;
  33113. _this.ALPHATEST = false;
  33114. _this.DEPTHPREPASS = false;
  33115. _this.ALPHAFROMDIFFUSE = false;
  33116. _this.POINTSIZE = false;
  33117. _this.FOG = false;
  33118. _this.SPECULARTERM = false;
  33119. _this.DIFFUSEFRESNEL = false;
  33120. _this.OPACITYFRESNEL = false;
  33121. _this.REFLECTIONFRESNEL = false;
  33122. _this.REFRACTIONFRESNEL = false;
  33123. _this.EMISSIVEFRESNEL = false;
  33124. _this.FRESNEL = false;
  33125. _this.NORMAL = false;
  33126. _this.UV1 = false;
  33127. _this.UV2 = false;
  33128. _this.VERTEXCOLOR = false;
  33129. _this.VERTEXALPHA = false;
  33130. _this.NUM_BONE_INFLUENCERS = 0;
  33131. _this.BonesPerMesh = 0;
  33132. _this.INSTANCES = false;
  33133. _this.GLOSSINESS = false;
  33134. _this.ROUGHNESS = false;
  33135. _this.EMISSIVEASILLUMINATION = false;
  33136. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33137. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33138. _this.LIGHTMAP = false;
  33139. _this.LIGHTMAPDIRECTUV = 0;
  33140. _this.USELIGHTMAPASSHADOWMAP = false;
  33141. _this.REFLECTIONMAP_3D = false;
  33142. _this.REFLECTIONMAP_SPHERICAL = false;
  33143. _this.REFLECTIONMAP_PLANAR = false;
  33144. _this.REFLECTIONMAP_CUBIC = false;
  33145. _this.REFLECTIONMAP_PROJECTION = false;
  33146. _this.REFLECTIONMAP_SKYBOX = false;
  33147. _this.REFLECTIONMAP_EXPLICIT = false;
  33148. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33149. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33150. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33151. _this.INVERTCUBICMAP = false;
  33152. _this.LOGARITHMICDEPTH = false;
  33153. _this.REFRACTION = false;
  33154. _this.REFRACTIONMAP_3D = false;
  33155. _this.REFLECTIONOVERALPHA = false;
  33156. _this.TWOSIDEDLIGHTING = false;
  33157. _this.SHADOWFLOAT = false;
  33158. _this.MORPHTARGETS = false;
  33159. _this.MORPHTARGETS_NORMAL = false;
  33160. _this.MORPHTARGETS_TANGENT = false;
  33161. _this.NUM_MORPH_INFLUENCERS = 0;
  33162. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33163. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33164. _this.IMAGEPROCESSING = false;
  33165. _this.VIGNETTE = false;
  33166. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33167. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33168. _this.TONEMAPPING = false;
  33169. _this.CONTRAST = false;
  33170. _this.COLORCURVES = false;
  33171. _this.COLORGRADING = false;
  33172. _this.COLORGRADING3D = false;
  33173. _this.SAMPLER3DGREENDEPTH = false;
  33174. _this.SAMPLER3DBGRMAP = false;
  33175. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33176. _this.EXPOSURE = false;
  33177. _this.rebuild();
  33178. return _this;
  33179. }
  33180. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33181. var modes = [
  33182. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33183. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33184. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33185. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33186. ];
  33187. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33188. var mode = modes_1[_i];
  33189. this[mode] = (mode === modeToEnable);
  33190. }
  33191. };
  33192. return StandardMaterialDefines;
  33193. }(BABYLON.MaterialDefines));
  33194. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33195. var StandardMaterial = /** @class */ (function (_super) {
  33196. __extends(StandardMaterial, _super);
  33197. function StandardMaterial(name, scene) {
  33198. var _this = _super.call(this, name, scene) || this;
  33199. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33200. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33201. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33202. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33203. _this.specularPower = 64;
  33204. _this._useAlphaFromDiffuseTexture = false;
  33205. _this._useEmissiveAsIllumination = false;
  33206. _this._linkEmissiveWithDiffuse = false;
  33207. _this._useSpecularOverAlpha = false;
  33208. _this._useReflectionOverAlpha = false;
  33209. _this._disableLighting = false;
  33210. _this._useParallax = false;
  33211. _this._useParallaxOcclusion = false;
  33212. _this.parallaxScaleBias = 0.05;
  33213. _this._roughness = 0;
  33214. _this.indexOfRefraction = 0.98;
  33215. _this.invertRefractionY = true;
  33216. _this._useLightmapAsShadowmap = false;
  33217. _this._useReflectionFresnelFromSpecular = false;
  33218. _this._useGlossinessFromSpecularMapAlpha = false;
  33219. _this._maxSimultaneousLights = 4;
  33220. /**
  33221. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33222. */
  33223. _this._invertNormalMapX = false;
  33224. /**
  33225. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33226. */
  33227. _this._invertNormalMapY = false;
  33228. /**
  33229. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33230. */
  33231. _this._twoSidedLighting = false;
  33232. _this._renderTargets = new BABYLON.SmartArray(16);
  33233. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33234. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33235. // Setup the default processing configuration to the scene.
  33236. _this._attachImageProcessingConfiguration(null);
  33237. _this.getRenderTargetTextures = function () {
  33238. _this._renderTargets.reset();
  33239. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33240. _this._renderTargets.push(_this._reflectionTexture);
  33241. }
  33242. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33243. _this._renderTargets.push(_this._refractionTexture);
  33244. }
  33245. return _this._renderTargets;
  33246. };
  33247. return _this;
  33248. }
  33249. ;
  33250. ;
  33251. ;
  33252. ;
  33253. ;
  33254. ;
  33255. ;
  33256. ;
  33257. ;
  33258. ;
  33259. ;
  33260. ;
  33261. ;
  33262. ;
  33263. ;
  33264. ;
  33265. ;
  33266. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33267. /**
  33268. * Gets the image processing configuration used either in this material.
  33269. */
  33270. get: function () {
  33271. return this._imageProcessingConfiguration;
  33272. },
  33273. /**
  33274. * Sets the Default image processing configuration used either in the this material.
  33275. *
  33276. * If sets to null, the scene one is in use.
  33277. */
  33278. set: function (value) {
  33279. this._attachImageProcessingConfiguration(value);
  33280. // Ensure the effect will be rebuilt.
  33281. this._markAllSubMeshesAsTexturesDirty();
  33282. },
  33283. enumerable: true,
  33284. configurable: true
  33285. });
  33286. /**
  33287. * Attaches a new image processing configuration to the Standard Material.
  33288. * @param configuration
  33289. */
  33290. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33291. var _this = this;
  33292. if (configuration === this._imageProcessingConfiguration) {
  33293. return;
  33294. }
  33295. // Detaches observer.
  33296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33298. }
  33299. // Pick the scene configuration if needed.
  33300. if (!configuration) {
  33301. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33302. }
  33303. else {
  33304. this._imageProcessingConfiguration = configuration;
  33305. }
  33306. // Attaches observer.
  33307. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33308. _this._markAllSubMeshesAsImageProcessingDirty();
  33309. });
  33310. };
  33311. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33312. /**
  33313. * Gets wether the color curves effect is enabled.
  33314. */
  33315. get: function () {
  33316. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33317. },
  33318. /**
  33319. * Sets wether the color curves effect is enabled.
  33320. */
  33321. set: function (value) {
  33322. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33323. },
  33324. enumerable: true,
  33325. configurable: true
  33326. });
  33327. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33328. /**
  33329. * Gets wether the color grading effect is enabled.
  33330. */
  33331. get: function () {
  33332. return this.imageProcessingConfiguration.colorGradingEnabled;
  33333. },
  33334. /**
  33335. * Gets wether the color grading effect is enabled.
  33336. */
  33337. set: function (value) {
  33338. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33339. },
  33340. enumerable: true,
  33341. configurable: true
  33342. });
  33343. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33344. /**
  33345. * Gets wether tonemapping is enabled or not.
  33346. */
  33347. get: function () {
  33348. return this._imageProcessingConfiguration.toneMappingEnabled;
  33349. },
  33350. /**
  33351. * Sets wether tonemapping is enabled or not
  33352. */
  33353. set: function (value) {
  33354. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33355. },
  33356. enumerable: true,
  33357. configurable: true
  33358. });
  33359. ;
  33360. ;
  33361. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33362. /**
  33363. * The camera exposure used on this material.
  33364. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33365. * This corresponds to a photographic exposure.
  33366. */
  33367. get: function () {
  33368. return this._imageProcessingConfiguration.exposure;
  33369. },
  33370. /**
  33371. * The camera exposure used on this material.
  33372. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33373. * This corresponds to a photographic exposure.
  33374. */
  33375. set: function (value) {
  33376. this._imageProcessingConfiguration.exposure = value;
  33377. },
  33378. enumerable: true,
  33379. configurable: true
  33380. });
  33381. ;
  33382. ;
  33383. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33384. /**
  33385. * Gets The camera contrast used on this material.
  33386. */
  33387. get: function () {
  33388. return this._imageProcessingConfiguration.contrast;
  33389. },
  33390. /**
  33391. * Sets The camera contrast used on this material.
  33392. */
  33393. set: function (value) {
  33394. this._imageProcessingConfiguration.contrast = value;
  33395. },
  33396. enumerable: true,
  33397. configurable: true
  33398. });
  33399. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33400. /**
  33401. * Gets the Color Grading 2D Lookup Texture.
  33402. */
  33403. get: function () {
  33404. return this._imageProcessingConfiguration.colorGradingTexture;
  33405. },
  33406. /**
  33407. * Sets the Color Grading 2D Lookup Texture.
  33408. */
  33409. set: function (value) {
  33410. this._imageProcessingConfiguration.colorGradingTexture = value;
  33411. },
  33412. enumerable: true,
  33413. configurable: true
  33414. });
  33415. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33416. /**
  33417. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33418. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33419. * 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;
  33420. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33421. */
  33422. get: function () {
  33423. return this._imageProcessingConfiguration.colorCurves;
  33424. },
  33425. /**
  33426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33428. * 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;
  33429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33430. */
  33431. set: function (value) {
  33432. this._imageProcessingConfiguration.colorCurves = value;
  33433. },
  33434. enumerable: true,
  33435. configurable: true
  33436. });
  33437. StandardMaterial.prototype.getClassName = function () {
  33438. return "StandardMaterial";
  33439. };
  33440. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33441. get: function () {
  33442. return this._useLogarithmicDepth;
  33443. },
  33444. set: function (value) {
  33445. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33446. this._markAllSubMeshesAsMiscDirty();
  33447. },
  33448. enumerable: true,
  33449. configurable: true
  33450. });
  33451. StandardMaterial.prototype.needAlphaBlending = function () {
  33452. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33453. };
  33454. StandardMaterial.prototype.needAlphaTesting = function () {
  33455. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33456. };
  33457. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33458. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33459. };
  33460. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33461. return this._diffuseTexture;
  33462. };
  33463. /**
  33464. * Child classes can use it to update shaders
  33465. */
  33466. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33467. if (useInstances === void 0) { useInstances = false; }
  33468. if (subMesh.effect && this.isFrozen) {
  33469. if (this._wasPreviouslyReady && subMesh.effect) {
  33470. return true;
  33471. }
  33472. }
  33473. if (!subMesh._materialDefines) {
  33474. subMesh._materialDefines = new StandardMaterialDefines();
  33475. }
  33476. var scene = this.getScene();
  33477. var defines = subMesh._materialDefines;
  33478. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33479. if (defines._renderId === scene.getRenderId()) {
  33480. return true;
  33481. }
  33482. }
  33483. var engine = scene.getEngine();
  33484. // Lights
  33485. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33486. // Textures
  33487. if (defines._areTexturesDirty) {
  33488. defines._needUVs = false;
  33489. defines.MAINUV1 = false;
  33490. defines.MAINUV2 = false;
  33491. if (scene.texturesEnabled) {
  33492. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33493. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33494. return false;
  33495. }
  33496. else {
  33497. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33498. }
  33499. }
  33500. else {
  33501. defines.DIFFUSE = false;
  33502. }
  33503. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33504. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33505. return false;
  33506. }
  33507. else {
  33508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33509. }
  33510. }
  33511. else {
  33512. defines.AMBIENT = false;
  33513. }
  33514. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33515. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33516. return false;
  33517. }
  33518. else {
  33519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33520. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33521. }
  33522. }
  33523. else {
  33524. defines.OPACITY = false;
  33525. }
  33526. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33527. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33528. return false;
  33529. }
  33530. else {
  33531. defines._needNormals = true;
  33532. defines.REFLECTION = true;
  33533. defines.ROUGHNESS = (this._roughness > 0);
  33534. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33535. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33536. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33537. switch (this._reflectionTexture.coordinatesMode) {
  33538. case BABYLON.Texture.CUBIC_MODE:
  33539. case BABYLON.Texture.INVCUBIC_MODE:
  33540. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33541. break;
  33542. case BABYLON.Texture.EXPLICIT_MODE:
  33543. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33544. break;
  33545. case BABYLON.Texture.PLANAR_MODE:
  33546. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33547. break;
  33548. case BABYLON.Texture.PROJECTION_MODE:
  33549. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33550. break;
  33551. case BABYLON.Texture.SKYBOX_MODE:
  33552. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33553. break;
  33554. case BABYLON.Texture.SPHERICAL_MODE:
  33555. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33556. break;
  33557. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33558. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33559. break;
  33560. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33561. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33562. break;
  33563. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33564. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33565. break;
  33566. }
  33567. }
  33568. }
  33569. else {
  33570. defines.REFLECTION = false;
  33571. }
  33572. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33573. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33574. return false;
  33575. }
  33576. else {
  33577. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33578. }
  33579. }
  33580. else {
  33581. defines.EMISSIVE = false;
  33582. }
  33583. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33584. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33585. return false;
  33586. }
  33587. else {
  33588. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33589. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33590. }
  33591. }
  33592. else {
  33593. defines.LIGHTMAP = false;
  33594. }
  33595. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33596. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33597. return false;
  33598. }
  33599. else {
  33600. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33601. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33602. }
  33603. }
  33604. else {
  33605. defines.SPECULAR = false;
  33606. }
  33607. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33608. // Bump texure can not be not blocking.
  33609. if (!this._bumpTexture.isReady()) {
  33610. return false;
  33611. }
  33612. else {
  33613. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33614. defines.PARALLAX = this._useParallax;
  33615. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33616. }
  33617. }
  33618. else {
  33619. defines.BUMP = false;
  33620. }
  33621. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33622. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33623. return false;
  33624. }
  33625. else {
  33626. defines._needUVs = true;
  33627. defines.REFRACTION = true;
  33628. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33629. }
  33630. }
  33631. else {
  33632. defines.REFRACTION = false;
  33633. }
  33634. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33635. }
  33636. else {
  33637. defines.DIFFUSE = false;
  33638. defines.AMBIENT = false;
  33639. defines.OPACITY = false;
  33640. defines.REFLECTION = false;
  33641. defines.EMISSIVE = false;
  33642. defines.LIGHTMAP = false;
  33643. defines.BUMP = false;
  33644. defines.REFRACTION = false;
  33645. }
  33646. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33647. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33648. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33649. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33650. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33651. }
  33652. if (defines._areImageProcessingDirty) {
  33653. if (!this._imageProcessingConfiguration.isReady()) {
  33654. return false;
  33655. }
  33656. this._imageProcessingConfiguration.prepareDefines(defines);
  33657. }
  33658. if (defines._areFresnelDirty) {
  33659. if (StandardMaterial.FresnelEnabled) {
  33660. // Fresnel
  33661. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33662. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33663. this._reflectionFresnelParameters) {
  33664. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33665. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33666. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33667. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33668. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33669. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33670. defines._needNormals = true;
  33671. defines.FRESNEL = true;
  33672. }
  33673. }
  33674. else {
  33675. defines.FRESNEL = false;
  33676. }
  33677. }
  33678. // Misc.
  33679. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33680. // Attribs
  33681. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33682. // Values that need to be evaluated on every frame
  33683. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33684. // Get correct effect
  33685. if (defines.isDirty) {
  33686. defines.markAsProcessed();
  33687. scene.resetCachedMaterial();
  33688. // Fallbacks
  33689. var fallbacks = new BABYLON.EffectFallbacks();
  33690. if (defines.REFLECTION) {
  33691. fallbacks.addFallback(0, "REFLECTION");
  33692. }
  33693. if (defines.SPECULAR) {
  33694. fallbacks.addFallback(0, "SPECULAR");
  33695. }
  33696. if (defines.BUMP) {
  33697. fallbacks.addFallback(0, "BUMP");
  33698. }
  33699. if (defines.PARALLAX) {
  33700. fallbacks.addFallback(1, "PARALLAX");
  33701. }
  33702. if (defines.PARALLAXOCCLUSION) {
  33703. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33704. }
  33705. if (defines.SPECULAROVERALPHA) {
  33706. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33707. }
  33708. if (defines.FOG) {
  33709. fallbacks.addFallback(1, "FOG");
  33710. }
  33711. if (defines.POINTSIZE) {
  33712. fallbacks.addFallback(0, "POINTSIZE");
  33713. }
  33714. if (defines.LOGARITHMICDEPTH) {
  33715. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33716. }
  33717. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33718. if (defines.SPECULARTERM) {
  33719. fallbacks.addFallback(0, "SPECULARTERM");
  33720. }
  33721. if (defines.DIFFUSEFRESNEL) {
  33722. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33723. }
  33724. if (defines.OPACITYFRESNEL) {
  33725. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33726. }
  33727. if (defines.REFLECTIONFRESNEL) {
  33728. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33729. }
  33730. if (defines.EMISSIVEFRESNEL) {
  33731. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33732. }
  33733. if (defines.FRESNEL) {
  33734. fallbacks.addFallback(4, "FRESNEL");
  33735. }
  33736. //Attributes
  33737. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33738. if (defines.NORMAL) {
  33739. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33740. }
  33741. if (defines.UV1) {
  33742. attribs.push(BABYLON.VertexBuffer.UVKind);
  33743. }
  33744. if (defines.UV2) {
  33745. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33746. }
  33747. if (defines.VERTEXCOLOR) {
  33748. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33749. }
  33750. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33751. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33752. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33753. var shaderName = "default";
  33754. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33755. "vFogInfos", "vFogColor", "pointSize",
  33756. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33757. "mBones",
  33758. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33759. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33760. "logarithmicDepthConstant", "vTangentSpaceParams"
  33761. ];
  33762. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33763. var uniformBuffers = ["Material", "Scene"];
  33764. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33765. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33766. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33767. uniformsNames: uniforms,
  33768. uniformBuffersNames: uniformBuffers,
  33769. samplers: samplers,
  33770. defines: defines,
  33771. maxSimultaneousLights: this._maxSimultaneousLights
  33772. });
  33773. if (this.customShaderNameResolve) {
  33774. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33775. }
  33776. var join = defines.toString();
  33777. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33778. attributes: attribs,
  33779. uniformsNames: uniforms,
  33780. uniformBuffersNames: uniformBuffers,
  33781. samplers: samplers,
  33782. defines: join,
  33783. fallbacks: fallbacks,
  33784. onCompiled: this.onCompiled,
  33785. onError: this.onError,
  33786. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33787. }, engine), defines);
  33788. this.buildUniformLayout();
  33789. }
  33790. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33791. return false;
  33792. }
  33793. defines._renderId = scene.getRenderId();
  33794. this._wasPreviouslyReady = true;
  33795. return true;
  33796. };
  33797. StandardMaterial.prototype.buildUniformLayout = function () {
  33798. // Order is important !
  33799. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33800. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33801. this._uniformBuffer.addUniform("opacityParts", 4);
  33802. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33803. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  33804. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  33805. this._uniformBuffer.addUniform("refractionRightColor", 4);
  33806. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  33807. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  33808. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  33809. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  33810. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  33811. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  33812. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  33813. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  33814. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  33815. this._uniformBuffer.addUniform("vBumpInfos", 3);
  33816. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  33817. this._uniformBuffer.addUniform("ambientMatrix", 16);
  33818. this._uniformBuffer.addUniform("opacityMatrix", 16);
  33819. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  33820. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  33821. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  33822. this._uniformBuffer.addUniform("specularMatrix", 16);
  33823. this._uniformBuffer.addUniform("bumpMatrix", 16);
  33824. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  33825. this._uniformBuffer.addUniform("refractionMatrix", 16);
  33826. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  33827. this._uniformBuffer.addUniform("vSpecularColor", 4);
  33828. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  33829. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  33830. this._uniformBuffer.addUniform("pointSize", 1);
  33831. this._uniformBuffer.create();
  33832. };
  33833. StandardMaterial.prototype.unbind = function () {
  33834. if (this._activeEffect) {
  33835. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  33836. this._activeEffect.setTexture("reflection2DSampler", null);
  33837. }
  33838. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  33839. this._activeEffect.setTexture("refraction2DSampler", null);
  33840. }
  33841. }
  33842. _super.prototype.unbind.call(this);
  33843. };
  33844. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  33845. var scene = this.getScene();
  33846. var defines = subMesh._materialDefines;
  33847. if (!defines) {
  33848. return;
  33849. }
  33850. var effect = subMesh.effect;
  33851. if (!effect) {
  33852. return;
  33853. }
  33854. this._activeEffect = effect;
  33855. // Matrices
  33856. this.bindOnlyWorldMatrix(world);
  33857. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  33858. // Bones
  33859. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  33860. if (mustRebind) {
  33861. this._uniformBuffer.bindToEffect(effect, "Material");
  33862. this.bindViewProjection(effect);
  33863. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  33864. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  33865. // Fresnel
  33866. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  33867. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  33868. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  33869. }
  33870. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  33871. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  33872. }
  33873. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  33874. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  33875. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  33876. }
  33877. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  33878. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  33879. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  33880. }
  33881. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  33882. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  33883. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  33884. }
  33885. }
  33886. // Textures
  33887. if (scene.texturesEnabled) {
  33888. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33889. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  33890. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  33891. }
  33892. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33893. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  33894. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  33895. }
  33896. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33897. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  33898. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  33899. }
  33900. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33901. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  33902. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  33903. }
  33904. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33905. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  33906. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  33907. }
  33908. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33909. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  33910. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  33911. }
  33912. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33913. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  33914. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  33915. }
  33916. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33917. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  33918. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  33919. if (scene._mirroredCameraPosition) {
  33920. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  33921. }
  33922. else {
  33923. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  33924. }
  33925. }
  33926. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33927. var depth = 1.0;
  33928. if (!this._refractionTexture.isCube) {
  33929. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  33930. if (this._refractionTexture.depth) {
  33931. depth = this._refractionTexture.depth;
  33932. }
  33933. }
  33934. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  33935. }
  33936. }
  33937. // Point size
  33938. if (this.pointsCloud) {
  33939. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  33940. }
  33941. if (defines.SPECULARTERM) {
  33942. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  33943. }
  33944. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  33945. // Diffuse
  33946. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  33947. }
  33948. // Textures
  33949. if (scene.texturesEnabled) {
  33950. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33951. effect.setTexture("diffuseSampler", this._diffuseTexture);
  33952. }
  33953. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33954. effect.setTexture("ambientSampler", this._ambientTexture);
  33955. }
  33956. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33957. effect.setTexture("opacitySampler", this._opacityTexture);
  33958. }
  33959. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33960. if (this._reflectionTexture.isCube) {
  33961. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  33962. }
  33963. else {
  33964. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  33965. }
  33966. }
  33967. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33968. effect.setTexture("emissiveSampler", this._emissiveTexture);
  33969. }
  33970. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33971. effect.setTexture("lightmapSampler", this._lightmapTexture);
  33972. }
  33973. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33974. effect.setTexture("specularSampler", this._specularTexture);
  33975. }
  33976. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  33977. effect.setTexture("bumpSampler", this._bumpTexture);
  33978. }
  33979. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33980. var depth = 1.0;
  33981. if (this._refractionTexture.isCube) {
  33982. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  33983. }
  33984. else {
  33985. effect.setTexture("refraction2DSampler", this._refractionTexture);
  33986. }
  33987. }
  33988. }
  33989. // Clip plane
  33990. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  33991. // Colors
  33992. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  33993. if (scene.activeCamera) {
  33994. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33995. }
  33996. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  33997. }
  33998. if (mustRebind || !this.isFrozen) {
  33999. // Lights
  34000. if (scene.lightsEnabled && !this._disableLighting) {
  34001. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34002. }
  34003. // View
  34004. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34005. this.bindView(effect);
  34006. }
  34007. // Fog
  34008. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34009. // Morph targets
  34010. if (defines.NUM_MORPH_INFLUENCERS) {
  34011. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34012. }
  34013. // Log. depth
  34014. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34015. // image processing
  34016. this._imageProcessingConfiguration.bind(this._activeEffect);
  34017. }
  34018. this._uniformBuffer.update();
  34019. this._afterBind(mesh, this._activeEffect);
  34020. };
  34021. StandardMaterial.prototype.getAnimatables = function () {
  34022. var results = [];
  34023. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34024. results.push(this._diffuseTexture);
  34025. }
  34026. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34027. results.push(this._ambientTexture);
  34028. }
  34029. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34030. results.push(this._opacityTexture);
  34031. }
  34032. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34033. results.push(this._reflectionTexture);
  34034. }
  34035. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34036. results.push(this._emissiveTexture);
  34037. }
  34038. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34039. results.push(this._specularTexture);
  34040. }
  34041. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34042. results.push(this._bumpTexture);
  34043. }
  34044. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34045. results.push(this._lightmapTexture);
  34046. }
  34047. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34048. results.push(this._refractionTexture);
  34049. }
  34050. return results;
  34051. };
  34052. StandardMaterial.prototype.getActiveTextures = function () {
  34053. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34054. if (this._diffuseTexture) {
  34055. activeTextures.push(this._diffuseTexture);
  34056. }
  34057. if (this._ambientTexture) {
  34058. activeTextures.push(this._ambientTexture);
  34059. }
  34060. if (this._opacityTexture) {
  34061. activeTextures.push(this._opacityTexture);
  34062. }
  34063. if (this._reflectionTexture) {
  34064. activeTextures.push(this._reflectionTexture);
  34065. }
  34066. if (this._emissiveTexture) {
  34067. activeTextures.push(this._emissiveTexture);
  34068. }
  34069. if (this._specularTexture) {
  34070. activeTextures.push(this._specularTexture);
  34071. }
  34072. if (this._bumpTexture) {
  34073. activeTextures.push(this._bumpTexture);
  34074. }
  34075. if (this._lightmapTexture) {
  34076. activeTextures.push(this._lightmapTexture);
  34077. }
  34078. if (this._refractionTexture) {
  34079. activeTextures.push(this._refractionTexture);
  34080. }
  34081. return activeTextures;
  34082. };
  34083. StandardMaterial.prototype.hasTexture = function (texture) {
  34084. if (_super.prototype.hasTexture.call(this, texture)) {
  34085. return true;
  34086. }
  34087. if (this._diffuseTexture === texture) {
  34088. return true;
  34089. }
  34090. if (this._ambientTexture === texture) {
  34091. return true;
  34092. }
  34093. if (this._opacityTexture === texture) {
  34094. return true;
  34095. }
  34096. if (this._reflectionTexture === texture) {
  34097. return true;
  34098. }
  34099. if (this._emissiveTexture === texture) {
  34100. return true;
  34101. }
  34102. if (this._specularTexture === texture) {
  34103. return true;
  34104. }
  34105. if (this._bumpTexture === texture) {
  34106. return true;
  34107. }
  34108. if (this._lightmapTexture === texture) {
  34109. return true;
  34110. }
  34111. if (this._refractionTexture === texture) {
  34112. return true;
  34113. }
  34114. return false;
  34115. };
  34116. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34117. if (forceDisposeTextures) {
  34118. if (this._diffuseTexture) {
  34119. this._diffuseTexture.dispose();
  34120. }
  34121. if (this._ambientTexture) {
  34122. this._ambientTexture.dispose();
  34123. }
  34124. if (this._opacityTexture) {
  34125. this._opacityTexture.dispose();
  34126. }
  34127. if (this._reflectionTexture) {
  34128. this._reflectionTexture.dispose();
  34129. }
  34130. if (this._emissiveTexture) {
  34131. this._emissiveTexture.dispose();
  34132. }
  34133. if (this._specularTexture) {
  34134. this._specularTexture.dispose();
  34135. }
  34136. if (this._bumpTexture) {
  34137. this._bumpTexture.dispose();
  34138. }
  34139. if (this._lightmapTexture) {
  34140. this._lightmapTexture.dispose();
  34141. }
  34142. if (this._refractionTexture) {
  34143. this._refractionTexture.dispose();
  34144. }
  34145. }
  34146. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34147. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34148. }
  34149. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34150. };
  34151. StandardMaterial.prototype.clone = function (name) {
  34152. var _this = this;
  34153. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34154. result.name = name;
  34155. result.id = name;
  34156. return result;
  34157. };
  34158. StandardMaterial.prototype.serialize = function () {
  34159. return BABYLON.SerializationHelper.Serialize(this);
  34160. };
  34161. // Statics
  34162. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34163. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34164. };
  34165. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34166. get: function () {
  34167. return StandardMaterial._DiffuseTextureEnabled;
  34168. },
  34169. set: function (value) {
  34170. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34171. return;
  34172. }
  34173. StandardMaterial._DiffuseTextureEnabled = value;
  34174. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34175. },
  34176. enumerable: true,
  34177. configurable: true
  34178. });
  34179. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34180. get: function () {
  34181. return StandardMaterial._AmbientTextureEnabled;
  34182. },
  34183. set: function (value) {
  34184. if (StandardMaterial._AmbientTextureEnabled === value) {
  34185. return;
  34186. }
  34187. StandardMaterial._AmbientTextureEnabled = value;
  34188. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34189. },
  34190. enumerable: true,
  34191. configurable: true
  34192. });
  34193. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34194. get: function () {
  34195. return StandardMaterial._OpacityTextureEnabled;
  34196. },
  34197. set: function (value) {
  34198. if (StandardMaterial._OpacityTextureEnabled === value) {
  34199. return;
  34200. }
  34201. StandardMaterial._OpacityTextureEnabled = value;
  34202. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34203. },
  34204. enumerable: true,
  34205. configurable: true
  34206. });
  34207. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34208. get: function () {
  34209. return StandardMaterial._ReflectionTextureEnabled;
  34210. },
  34211. set: function (value) {
  34212. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34213. return;
  34214. }
  34215. StandardMaterial._ReflectionTextureEnabled = value;
  34216. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34217. },
  34218. enumerable: true,
  34219. configurable: true
  34220. });
  34221. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34222. get: function () {
  34223. return StandardMaterial._EmissiveTextureEnabled;
  34224. },
  34225. set: function (value) {
  34226. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34227. return;
  34228. }
  34229. StandardMaterial._EmissiveTextureEnabled = value;
  34230. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34231. },
  34232. enumerable: true,
  34233. configurable: true
  34234. });
  34235. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34236. get: function () {
  34237. return StandardMaterial._SpecularTextureEnabled;
  34238. },
  34239. set: function (value) {
  34240. if (StandardMaterial._SpecularTextureEnabled === value) {
  34241. return;
  34242. }
  34243. StandardMaterial._SpecularTextureEnabled = value;
  34244. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34245. },
  34246. enumerable: true,
  34247. configurable: true
  34248. });
  34249. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34250. get: function () {
  34251. return StandardMaterial._BumpTextureEnabled;
  34252. },
  34253. set: function (value) {
  34254. if (StandardMaterial._BumpTextureEnabled === value) {
  34255. return;
  34256. }
  34257. StandardMaterial._BumpTextureEnabled = value;
  34258. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34259. },
  34260. enumerable: true,
  34261. configurable: true
  34262. });
  34263. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34264. get: function () {
  34265. return StandardMaterial._LightmapTextureEnabled;
  34266. },
  34267. set: function (value) {
  34268. if (StandardMaterial._LightmapTextureEnabled === value) {
  34269. return;
  34270. }
  34271. StandardMaterial._LightmapTextureEnabled = value;
  34272. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34273. },
  34274. enumerable: true,
  34275. configurable: true
  34276. });
  34277. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34278. get: function () {
  34279. return StandardMaterial._RefractionTextureEnabled;
  34280. },
  34281. set: function (value) {
  34282. if (StandardMaterial._RefractionTextureEnabled === value) {
  34283. return;
  34284. }
  34285. StandardMaterial._RefractionTextureEnabled = value;
  34286. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34287. },
  34288. enumerable: true,
  34289. configurable: true
  34290. });
  34291. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34292. get: function () {
  34293. return StandardMaterial._ColorGradingTextureEnabled;
  34294. },
  34295. set: function (value) {
  34296. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34297. return;
  34298. }
  34299. StandardMaterial._ColorGradingTextureEnabled = value;
  34300. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34301. },
  34302. enumerable: true,
  34303. configurable: true
  34304. });
  34305. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34306. get: function () {
  34307. return StandardMaterial._FresnelEnabled;
  34308. },
  34309. set: function (value) {
  34310. if (StandardMaterial._FresnelEnabled === value) {
  34311. return;
  34312. }
  34313. StandardMaterial._FresnelEnabled = value;
  34314. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34315. },
  34316. enumerable: true,
  34317. configurable: true
  34318. });
  34319. // Flags used to enable or disable a type of texture for all Standard Materials
  34320. StandardMaterial._DiffuseTextureEnabled = true;
  34321. StandardMaterial._AmbientTextureEnabled = true;
  34322. StandardMaterial._OpacityTextureEnabled = true;
  34323. StandardMaterial._ReflectionTextureEnabled = true;
  34324. StandardMaterial._EmissiveTextureEnabled = true;
  34325. StandardMaterial._SpecularTextureEnabled = true;
  34326. StandardMaterial._BumpTextureEnabled = true;
  34327. StandardMaterial._LightmapTextureEnabled = true;
  34328. StandardMaterial._RefractionTextureEnabled = true;
  34329. StandardMaterial._ColorGradingTextureEnabled = true;
  34330. StandardMaterial._FresnelEnabled = true;
  34331. __decorate([
  34332. BABYLON.serializeAsTexture("diffuseTexture")
  34333. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34334. __decorate([
  34335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34336. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34337. __decorate([
  34338. BABYLON.serializeAsTexture("ambientTexture")
  34339. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34340. __decorate([
  34341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34342. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34343. __decorate([
  34344. BABYLON.serializeAsTexture("opacityTexture")
  34345. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34346. __decorate([
  34347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34348. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34349. __decorate([
  34350. BABYLON.serializeAsTexture("reflectionTexture")
  34351. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34352. __decorate([
  34353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34354. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34355. __decorate([
  34356. BABYLON.serializeAsTexture("emissiveTexture")
  34357. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34358. __decorate([
  34359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34360. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34361. __decorate([
  34362. BABYLON.serializeAsTexture("specularTexture")
  34363. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34364. __decorate([
  34365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34366. ], StandardMaterial.prototype, "specularTexture", void 0);
  34367. __decorate([
  34368. BABYLON.serializeAsTexture("bumpTexture")
  34369. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34370. __decorate([
  34371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34372. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34373. __decorate([
  34374. BABYLON.serializeAsTexture("lightmapTexture")
  34375. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34376. __decorate([
  34377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34378. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34379. __decorate([
  34380. BABYLON.serializeAsTexture("refractionTexture")
  34381. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34382. __decorate([
  34383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34384. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34385. __decorate([
  34386. BABYLON.serializeAsColor3("ambient")
  34387. ], StandardMaterial.prototype, "ambientColor", void 0);
  34388. __decorate([
  34389. BABYLON.serializeAsColor3("diffuse")
  34390. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34391. __decorate([
  34392. BABYLON.serializeAsColor3("specular")
  34393. ], StandardMaterial.prototype, "specularColor", void 0);
  34394. __decorate([
  34395. BABYLON.serializeAsColor3("emissive")
  34396. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34397. __decorate([
  34398. BABYLON.serialize()
  34399. ], StandardMaterial.prototype, "specularPower", void 0);
  34400. __decorate([
  34401. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34402. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34403. __decorate([
  34404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34405. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34406. __decorate([
  34407. BABYLON.serialize("useEmissiveAsIllumination")
  34408. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34409. __decorate([
  34410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34411. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34412. __decorate([
  34413. BABYLON.serialize("linkEmissiveWithDiffuse")
  34414. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34415. __decorate([
  34416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34417. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34418. __decorate([
  34419. BABYLON.serialize("useSpecularOverAlpha")
  34420. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34421. __decorate([
  34422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34423. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34424. __decorate([
  34425. BABYLON.serialize("useReflectionOverAlpha")
  34426. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34427. __decorate([
  34428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34429. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34430. __decorate([
  34431. BABYLON.serialize("disableLighting")
  34432. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34433. __decorate([
  34434. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34435. ], StandardMaterial.prototype, "disableLighting", void 0);
  34436. __decorate([
  34437. BABYLON.serialize("useParallax")
  34438. ], StandardMaterial.prototype, "_useParallax", void 0);
  34439. __decorate([
  34440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34441. ], StandardMaterial.prototype, "useParallax", void 0);
  34442. __decorate([
  34443. BABYLON.serialize("useParallaxOcclusion")
  34444. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34445. __decorate([
  34446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34447. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34448. __decorate([
  34449. BABYLON.serialize()
  34450. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34451. __decorate([
  34452. BABYLON.serialize("roughness")
  34453. ], StandardMaterial.prototype, "_roughness", void 0);
  34454. __decorate([
  34455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34456. ], StandardMaterial.prototype, "roughness", void 0);
  34457. __decorate([
  34458. BABYLON.serialize()
  34459. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34460. __decorate([
  34461. BABYLON.serialize()
  34462. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34463. __decorate([
  34464. BABYLON.serialize("useLightmapAsShadowmap")
  34465. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34466. __decorate([
  34467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34468. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34469. __decorate([
  34470. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34471. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34472. __decorate([
  34473. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34474. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34475. __decorate([
  34476. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34477. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34478. __decorate([
  34479. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34480. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34481. __decorate([
  34482. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34483. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34484. __decorate([
  34485. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34486. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34487. __decorate([
  34488. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34489. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34490. __decorate([
  34491. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34492. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34493. __decorate([
  34494. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34495. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34496. __decorate([
  34497. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34498. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34499. __decorate([
  34500. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34501. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34502. __decorate([
  34503. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34504. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34505. __decorate([
  34506. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34507. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34508. __decorate([
  34509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34510. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34511. __decorate([
  34512. BABYLON.serialize("maxSimultaneousLights")
  34513. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34514. __decorate([
  34515. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34516. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34517. __decorate([
  34518. BABYLON.serialize("invertNormalMapX")
  34519. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34520. __decorate([
  34521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34522. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34523. __decorate([
  34524. BABYLON.serialize("invertNormalMapY")
  34525. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34526. __decorate([
  34527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34528. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34529. __decorate([
  34530. BABYLON.serialize("twoSidedLighting")
  34531. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34532. __decorate([
  34533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34534. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34535. __decorate([
  34536. BABYLON.serialize()
  34537. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34538. return StandardMaterial;
  34539. }(BABYLON.PushMaterial));
  34540. BABYLON.StandardMaterial = StandardMaterial;
  34541. })(BABYLON || (BABYLON = {}));
  34542. //# sourceMappingURL=babylon.standardMaterial.js.map
  34543. var BABYLON;
  34544. (function (BABYLON) {
  34545. var PBRMaterialDefines = /** @class */ (function (_super) {
  34546. __extends(PBRMaterialDefines, _super);
  34547. function PBRMaterialDefines() {
  34548. var _this = _super.call(this) || this;
  34549. _this.PBR = true;
  34550. _this.MAINUV1 = false;
  34551. _this.MAINUV2 = false;
  34552. _this.UV1 = false;
  34553. _this.UV2 = false;
  34554. _this.ALBEDO = false;
  34555. _this.ALBEDODIRECTUV = 0;
  34556. _this.VERTEXCOLOR = false;
  34557. _this.AMBIENT = false;
  34558. _this.AMBIENTDIRECTUV = 0;
  34559. _this.AMBIENTINGRAYSCALE = false;
  34560. _this.OPACITY = false;
  34561. _this.VERTEXALPHA = false;
  34562. _this.OPACITYDIRECTUV = 0;
  34563. _this.OPACITYRGB = false;
  34564. _this.ALPHATEST = false;
  34565. _this.DEPTHPREPASS = false;
  34566. _this.ALPHABLEND = false;
  34567. _this.ALPHAFROMALBEDO = false;
  34568. _this.ALPHATESTVALUE = 0.5;
  34569. _this.SPECULAROVERALPHA = false;
  34570. _this.RADIANCEOVERALPHA = false;
  34571. _this.ALPHAFRESNEL = false;
  34572. _this.PREMULTIPLYALPHA = false;
  34573. _this.EMISSIVE = false;
  34574. _this.EMISSIVEDIRECTUV = 0;
  34575. _this.REFLECTIVITY = false;
  34576. _this.REFLECTIVITYDIRECTUV = 0;
  34577. _this.SPECULARTERM = false;
  34578. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34579. _this.MICROSURFACEAUTOMATIC = false;
  34580. _this.LODBASEDMICROSFURACE = false;
  34581. _this.MICROSURFACEMAP = false;
  34582. _this.MICROSURFACEMAPDIRECTUV = 0;
  34583. _this.METALLICWORKFLOW = false;
  34584. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34585. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34586. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34587. _this.AOSTOREINMETALMAPRED = false;
  34588. _this.ENVIRONMENTBRDF = false;
  34589. _this.NORMAL = false;
  34590. _this.TANGENT = false;
  34591. _this.BUMP = false;
  34592. _this.BUMPDIRECTUV = 0;
  34593. _this.PARALLAX = false;
  34594. _this.PARALLAXOCCLUSION = false;
  34595. _this.NORMALXYSCALE = true;
  34596. _this.LIGHTMAP = false;
  34597. _this.LIGHTMAPDIRECTUV = 0;
  34598. _this.USELIGHTMAPASSHADOWMAP = false;
  34599. _this.REFLECTION = false;
  34600. _this.REFLECTIONMAP_3D = false;
  34601. _this.REFLECTIONMAP_SPHERICAL = false;
  34602. _this.REFLECTIONMAP_PLANAR = false;
  34603. _this.REFLECTIONMAP_CUBIC = false;
  34604. _this.REFLECTIONMAP_PROJECTION = false;
  34605. _this.REFLECTIONMAP_SKYBOX = false;
  34606. _this.REFLECTIONMAP_EXPLICIT = false;
  34607. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34608. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34609. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34610. _this.INVERTCUBICMAP = false;
  34611. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34612. _this.USESPHERICALINFRAGMENT = false;
  34613. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34614. _this.LODINREFLECTIONALPHA = false;
  34615. _this.GAMMAREFLECTION = false;
  34616. _this.REFRACTION = false;
  34617. _this.REFRACTIONMAP_3D = false;
  34618. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34619. _this.LODINREFRACTIONALPHA = false;
  34620. _this.GAMMAREFRACTION = false;
  34621. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34622. _this.INSTANCES = false;
  34623. _this.NUM_BONE_INFLUENCERS = 0;
  34624. _this.BonesPerMesh = 0;
  34625. _this.NONUNIFORMSCALING = false;
  34626. _this.MORPHTARGETS = false;
  34627. _this.MORPHTARGETS_NORMAL = false;
  34628. _this.MORPHTARGETS_TANGENT = false;
  34629. _this.NUM_MORPH_INFLUENCERS = 0;
  34630. _this.IMAGEPROCESSING = false;
  34631. _this.VIGNETTE = false;
  34632. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34633. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34634. _this.TONEMAPPING = false;
  34635. _this.CONTRAST = false;
  34636. _this.COLORCURVES = false;
  34637. _this.COLORGRADING = false;
  34638. _this.COLORGRADING3D = false;
  34639. _this.SAMPLER3DGREENDEPTH = false;
  34640. _this.SAMPLER3DBGRMAP = false;
  34641. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34642. _this.EXPOSURE = false;
  34643. _this.USEPHYSICALLIGHTFALLOFF = false;
  34644. _this.TWOSIDEDLIGHTING = false;
  34645. _this.SHADOWFLOAT = false;
  34646. _this.CLIPPLANE = false;
  34647. _this.POINTSIZE = false;
  34648. _this.FOG = false;
  34649. _this.LOGARITHMICDEPTH = false;
  34650. _this.FORCENORMALFORWARD = false;
  34651. _this.rebuild();
  34652. return _this;
  34653. }
  34654. PBRMaterialDefines.prototype.reset = function () {
  34655. _super.prototype.reset.call(this);
  34656. this.ALPHATESTVALUE = 0.5;
  34657. this.PBR = true;
  34658. };
  34659. return PBRMaterialDefines;
  34660. }(BABYLON.MaterialDefines));
  34661. /**
  34662. * The Physically based material base class of BJS.
  34663. *
  34664. * This offers the main features of a standard PBR material.
  34665. * For more information, please refer to the documentation :
  34666. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34667. */
  34668. var PBRBaseMaterial = /** @class */ (function (_super) {
  34669. __extends(PBRBaseMaterial, _super);
  34670. /**
  34671. * Instantiates a new PBRMaterial instance.
  34672. *
  34673. * @param name The material name
  34674. * @param scene The scene the material will be use in.
  34675. */
  34676. function PBRBaseMaterial(name, scene) {
  34677. var _this = _super.call(this, name, scene) || this;
  34678. /**
  34679. * Intensity of the direct lights e.g. the four lights available in your scene.
  34680. * This impacts both the direct diffuse and specular highlights.
  34681. */
  34682. _this._directIntensity = 1.0;
  34683. /**
  34684. * Intensity of the emissive part of the material.
  34685. * This helps controlling the emissive effect without modifying the emissive color.
  34686. */
  34687. _this._emissiveIntensity = 1.0;
  34688. /**
  34689. * Intensity of the environment e.g. how much the environment will light the object
  34690. * either through harmonics for rough material or through the refelction for shiny ones.
  34691. */
  34692. _this._environmentIntensity = 1.0;
  34693. /**
  34694. * This is a special control allowing the reduction of the specular highlights coming from the
  34695. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34696. */
  34697. _this._specularIntensity = 1.0;
  34698. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34699. /**
  34700. * Debug Control allowing disabling the bump map on this material.
  34701. */
  34702. _this._disableBumpMap = false;
  34703. /**
  34704. * AKA Occlusion Texture Intensity in other nomenclature.
  34705. */
  34706. _this._ambientTextureStrength = 1.0;
  34707. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34708. /**
  34709. * AKA Diffuse Color in other nomenclature.
  34710. */
  34711. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34712. /**
  34713. * AKA Specular Color in other nomenclature.
  34714. */
  34715. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34716. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34717. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34718. /**
  34719. * AKA Glossiness in other nomenclature.
  34720. */
  34721. _this._microSurface = 0.9;
  34722. /**
  34723. * source material index of refraction (IOR)' / 'destination material IOR.
  34724. */
  34725. _this._indexOfRefraction = 0.66;
  34726. /**
  34727. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34728. */
  34729. _this._invertRefractionY = false;
  34730. /**
  34731. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34732. * Materials half opaque for instance using refraction could benefit from this control.
  34733. */
  34734. _this._linkRefractionWithTransparency = false;
  34735. _this._useLightmapAsShadowmap = false;
  34736. /**
  34737. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34738. */
  34739. _this._useAlphaFromAlbedoTexture = false;
  34740. /**
  34741. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34742. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34743. */
  34744. _this._useSpecularOverAlpha = true;
  34745. /**
  34746. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34747. */
  34748. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34749. /**
  34750. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34751. */
  34752. _this._useRoughnessFromMetallicTextureAlpha = true;
  34753. /**
  34754. * Specifies if the metallic texture contains the roughness information in its green channel.
  34755. */
  34756. _this._useRoughnessFromMetallicTextureGreen = false;
  34757. /**
  34758. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34759. */
  34760. _this._useMetallnessFromMetallicTextureBlue = false;
  34761. /**
  34762. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34763. */
  34764. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34765. /**
  34766. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34767. */
  34768. _this._useAmbientInGrayScale = false;
  34769. /**
  34770. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34771. * The material will try to infer what glossiness each pixel should be.
  34772. */
  34773. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34774. /**
  34775. * BJS is using an harcoded light falloff based on a manually sets up range.
  34776. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34777. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34778. */
  34779. _this._usePhysicalLightFalloff = true;
  34780. /**
  34781. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34782. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34783. */
  34784. _this._useRadianceOverAlpha = true;
  34785. /**
  34786. * Allows using the bump map in parallax mode.
  34787. */
  34788. _this._useParallax = false;
  34789. /**
  34790. * Allows using the bump map in parallax occlusion mode.
  34791. */
  34792. _this._useParallaxOcclusion = false;
  34793. /**
  34794. * Controls the scale bias of the parallax mode.
  34795. */
  34796. _this._parallaxScaleBias = 0.05;
  34797. /**
  34798. * If sets to true, disables all the lights affecting the material.
  34799. */
  34800. _this._disableLighting = false;
  34801. /**
  34802. * Number of Simultaneous lights allowed on the material.
  34803. */
  34804. _this._maxSimultaneousLights = 4;
  34805. /**
  34806. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  34807. */
  34808. _this._invertNormalMapX = false;
  34809. /**
  34810. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  34811. */
  34812. _this._invertNormalMapY = false;
  34813. /**
  34814. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34815. */
  34816. _this._twoSidedLighting = false;
  34817. /**
  34818. * Defines the alpha limits in alpha test mode.
  34819. */
  34820. _this._alphaCutOff = 0.4;
  34821. /**
  34822. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34823. */
  34824. _this._forceAlphaTest = false;
  34825. /**
  34826. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34827. * And/Or occlude the blended part.
  34828. */
  34829. _this._useAlphaFresnel = false;
  34830. /**
  34831. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  34832. * from cos thetav and roughness:
  34833. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  34834. */
  34835. _this._environmentBRDFTexture = null;
  34836. /**
  34837. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34838. */
  34839. _this._forceIrradianceInFragment = false;
  34840. /**
  34841. * Force normal to face away from face.
  34842. * (Temporary internal fix to remove before 3.1)
  34843. */
  34844. _this._forceNormalForward = false;
  34845. _this._renderTargets = new BABYLON.SmartArray(16);
  34846. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34847. // Setup the default processing configuration to the scene.
  34848. _this._attachImageProcessingConfiguration(null);
  34849. _this.getRenderTargetTextures = function () {
  34850. _this._renderTargets.reset();
  34851. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34852. _this._renderTargets.push(_this._reflectionTexture);
  34853. }
  34854. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34855. _this._renderTargets.push(_this._refractionTexture);
  34856. }
  34857. return _this._renderTargets;
  34858. };
  34859. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34860. return _this;
  34861. }
  34862. /**
  34863. * Attaches a new image processing configuration to the PBR Material.
  34864. * @param configuration
  34865. */
  34866. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34867. var _this = this;
  34868. if (configuration === this._imageProcessingConfiguration) {
  34869. return;
  34870. }
  34871. // Detaches observer.
  34872. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34873. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34874. }
  34875. // Pick the scene configuration if needed.
  34876. if (!configuration) {
  34877. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34878. }
  34879. else {
  34880. this._imageProcessingConfiguration = configuration;
  34881. }
  34882. // Attaches observer.
  34883. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34884. _this._markAllSubMeshesAsImageProcessingDirty();
  34885. });
  34886. };
  34887. PBRBaseMaterial.prototype.getClassName = function () {
  34888. return "PBRBaseMaterial";
  34889. };
  34890. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34891. get: function () {
  34892. return this._useLogarithmicDepth;
  34893. },
  34894. set: function (value) {
  34895. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34896. },
  34897. enumerable: true,
  34898. configurable: true
  34899. });
  34900. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34901. if (this._linkRefractionWithTransparency) {
  34902. return false;
  34903. }
  34904. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34905. };
  34906. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34907. if (this._forceAlphaTest) {
  34908. return true;
  34909. }
  34910. if (this._linkRefractionWithTransparency) {
  34911. return false;
  34912. }
  34913. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34914. };
  34915. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34916. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34917. };
  34918. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34919. return this._albedoTexture;
  34920. };
  34921. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34922. var _this = this;
  34923. if (subMesh.effect && this.isFrozen) {
  34924. if (this._wasPreviouslyReady) {
  34925. return true;
  34926. }
  34927. }
  34928. if (!subMesh._materialDefines) {
  34929. subMesh._materialDefines = new PBRMaterialDefines();
  34930. }
  34931. var scene = this.getScene();
  34932. var defines = subMesh._materialDefines;
  34933. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34934. if (defines._renderId === scene.getRenderId()) {
  34935. return true;
  34936. }
  34937. }
  34938. var engine = scene.getEngine();
  34939. // Lights
  34940. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34941. defines._needNormals = true;
  34942. // Textures
  34943. if (defines._areTexturesDirty) {
  34944. defines._needUVs = false;
  34945. if (scene.texturesEnabled) {
  34946. if (scene.getEngine().getCaps().textureLOD) {
  34947. defines.LODBASEDMICROSFURACE = true;
  34948. }
  34949. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34950. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34951. return false;
  34952. }
  34953. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  34954. }
  34955. else {
  34956. defines.ALBEDO = false;
  34957. }
  34958. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34959. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34960. return false;
  34961. }
  34962. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34963. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34964. }
  34965. else {
  34966. defines.AMBIENT = false;
  34967. }
  34968. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34969. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34970. return false;
  34971. }
  34972. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34973. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34974. }
  34975. else {
  34976. defines.OPACITY = false;
  34977. }
  34978. var reflectionTexture = this._getReflectionTexture();
  34979. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34980. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34981. return false;
  34982. }
  34983. defines.REFLECTION = true;
  34984. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  34985. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  34986. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34987. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34988. defines.INVERTCUBICMAP = true;
  34989. }
  34990. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34991. switch (reflectionTexture.coordinatesMode) {
  34992. case BABYLON.Texture.CUBIC_MODE:
  34993. case BABYLON.Texture.INVCUBIC_MODE:
  34994. defines.REFLECTIONMAP_CUBIC = true;
  34995. break;
  34996. case BABYLON.Texture.EXPLICIT_MODE:
  34997. defines.REFLECTIONMAP_EXPLICIT = true;
  34998. break;
  34999. case BABYLON.Texture.PLANAR_MODE:
  35000. defines.REFLECTIONMAP_PLANAR = true;
  35001. break;
  35002. case BABYLON.Texture.PROJECTION_MODE:
  35003. defines.REFLECTIONMAP_PROJECTION = true;
  35004. break;
  35005. case BABYLON.Texture.SKYBOX_MODE:
  35006. defines.REFLECTIONMAP_SKYBOX = true;
  35007. break;
  35008. case BABYLON.Texture.SPHERICAL_MODE:
  35009. defines.REFLECTIONMAP_SPHERICAL = true;
  35010. break;
  35011. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35012. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35013. break;
  35014. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35015. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35016. break;
  35017. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35018. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35019. break;
  35020. }
  35021. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35022. if (reflectionTexture.sphericalPolynomial) {
  35023. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35024. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35025. defines.USESPHERICALINFRAGMENT = true;
  35026. }
  35027. }
  35028. }
  35029. }
  35030. else {
  35031. defines.REFLECTION = false;
  35032. defines.REFLECTIONMAP_3D = false;
  35033. defines.REFLECTIONMAP_SPHERICAL = false;
  35034. defines.REFLECTIONMAP_PLANAR = false;
  35035. defines.REFLECTIONMAP_CUBIC = false;
  35036. defines.REFLECTIONMAP_PROJECTION = false;
  35037. defines.REFLECTIONMAP_SKYBOX = false;
  35038. defines.REFLECTIONMAP_EXPLICIT = false;
  35039. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35040. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35041. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35042. defines.INVERTCUBICMAP = false;
  35043. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35044. defines.USESPHERICALINFRAGMENT = false;
  35045. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35046. defines.LODINREFLECTIONALPHA = false;
  35047. defines.GAMMAREFLECTION = false;
  35048. }
  35049. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35050. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35051. return false;
  35052. }
  35053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35054. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35055. }
  35056. else {
  35057. defines.LIGHTMAP = false;
  35058. }
  35059. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35060. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35061. return false;
  35062. }
  35063. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35064. }
  35065. else {
  35066. defines.EMISSIVE = false;
  35067. }
  35068. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35069. if (this._metallicTexture) {
  35070. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35071. return false;
  35072. }
  35073. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35074. defines.METALLICWORKFLOW = true;
  35075. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35076. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35077. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35078. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35079. }
  35080. else if (this._reflectivityTexture) {
  35081. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35082. return false;
  35083. }
  35084. defines.METALLICWORKFLOW = false;
  35085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35086. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35087. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35088. }
  35089. else {
  35090. defines.METALLICWORKFLOW = false;
  35091. defines.REFLECTIVITY = false;
  35092. }
  35093. if (this._microSurfaceTexture) {
  35094. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35095. return false;
  35096. }
  35097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35098. }
  35099. else {
  35100. defines.MICROSURFACEMAP = false;
  35101. }
  35102. }
  35103. else {
  35104. defines.REFLECTIVITY = false;
  35105. defines.MICROSURFACEMAP = false;
  35106. }
  35107. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35108. // Bump texure can not be none blocking.
  35109. if (!this._bumpTexture.isReady()) {
  35110. return false;
  35111. }
  35112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35113. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35114. defines.PARALLAX = true;
  35115. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35116. }
  35117. else {
  35118. defines.PARALLAX = false;
  35119. }
  35120. }
  35121. else {
  35122. defines.BUMP = false;
  35123. }
  35124. var refractionTexture = this._getRefractionTexture();
  35125. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35126. if (!refractionTexture.isReadyOrNotBlocking()) {
  35127. return false;
  35128. }
  35129. defines.REFRACTION = true;
  35130. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35131. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35132. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35133. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35134. if (this._linkRefractionWithTransparency) {
  35135. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35136. }
  35137. }
  35138. else {
  35139. defines.REFRACTION = false;
  35140. }
  35141. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35142. // This is blocking.
  35143. if (!this._environmentBRDFTexture.isReady()) {
  35144. return false;
  35145. }
  35146. defines.ENVIRONMENTBRDF = true;
  35147. }
  35148. else {
  35149. defines.ENVIRONMENTBRDF = false;
  35150. }
  35151. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35152. defines.ALPHAFROMALBEDO = true;
  35153. }
  35154. else {
  35155. defines.ALPHAFROMALBEDO = false;
  35156. }
  35157. }
  35158. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35159. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35160. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35161. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35162. defines.METALLICWORKFLOW = true;
  35163. }
  35164. else {
  35165. defines.METALLICWORKFLOW = false;
  35166. }
  35167. if (!this.backFaceCulling && this._twoSidedLighting) {
  35168. defines.TWOSIDEDLIGHTING = true;
  35169. }
  35170. else {
  35171. defines.TWOSIDEDLIGHTING = false;
  35172. }
  35173. defines.ALPHATESTVALUE = this._alphaCutOff;
  35174. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35175. defines.ALPHABLEND = this.needAlphaBlending();
  35176. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35177. }
  35178. if (defines._areImageProcessingDirty) {
  35179. if (!this._imageProcessingConfiguration.isReady()) {
  35180. return false;
  35181. }
  35182. this._imageProcessingConfiguration.prepareDefines(defines);
  35183. }
  35184. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35185. // Misc.
  35186. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35187. // Values that need to be evaluated on every frame
  35188. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35189. // Attribs
  35190. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35191. if (mesh) {
  35192. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35193. mesh.createNormals(true);
  35194. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35195. }
  35196. }
  35197. }
  35198. // Get correct effect
  35199. if (defines.isDirty) {
  35200. defines.markAsProcessed();
  35201. scene.resetCachedMaterial();
  35202. // Fallbacks
  35203. var fallbacks = new BABYLON.EffectFallbacks();
  35204. if (defines.ENVIRONMENTBRDF) {
  35205. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35206. }
  35207. if (defines.REFLECTION) {
  35208. fallbacks.addFallback(0, "REFLECTION");
  35209. }
  35210. if (defines.REFRACTION) {
  35211. fallbacks.addFallback(0, "REFRACTION");
  35212. }
  35213. if (defines.REFLECTIVITY) {
  35214. fallbacks.addFallback(0, "REFLECTIVITY");
  35215. }
  35216. if (defines.BUMP) {
  35217. fallbacks.addFallback(0, "BUMP");
  35218. }
  35219. if (defines.PARALLAX) {
  35220. fallbacks.addFallback(1, "PARALLAX");
  35221. }
  35222. if (defines.PARALLAXOCCLUSION) {
  35223. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35224. }
  35225. if (defines.SPECULAROVERALPHA) {
  35226. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35227. }
  35228. if (defines.FOG) {
  35229. fallbacks.addFallback(1, "FOG");
  35230. }
  35231. if (defines.POINTSIZE) {
  35232. fallbacks.addFallback(0, "POINTSIZE");
  35233. }
  35234. if (defines.LOGARITHMICDEPTH) {
  35235. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35236. }
  35237. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35238. if (defines.SPECULARTERM) {
  35239. fallbacks.addFallback(0, "SPECULARTERM");
  35240. }
  35241. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35242. fallbacks.addCPUSkinningFallback(0, mesh);
  35243. }
  35244. //Attributes
  35245. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35246. if (defines.NORMAL) {
  35247. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35248. }
  35249. if (defines.TANGENT) {
  35250. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35251. }
  35252. if (defines.UV1) {
  35253. attribs.push(BABYLON.VertexBuffer.UVKind);
  35254. }
  35255. if (defines.UV2) {
  35256. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35257. }
  35258. if (defines.VERTEXCOLOR) {
  35259. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35260. }
  35261. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35262. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35263. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35264. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35265. "vFogInfos", "vFogColor", "pointSize",
  35266. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35267. "mBones",
  35268. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35269. "vLightingIntensity",
  35270. "logarithmicDepthConstant",
  35271. "vSphericalX", "vSphericalY", "vSphericalZ",
  35272. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35273. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35274. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35275. "vTangentSpaceParams"
  35276. ];
  35277. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35278. "bumpSampler", "lightmapSampler", "opacitySampler",
  35279. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35280. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35281. "microSurfaceSampler", "environmentBrdfSampler"];
  35282. var uniformBuffers = ["Material", "Scene"];
  35283. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35284. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35285. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35286. uniformsNames: uniforms,
  35287. uniformBuffersNames: uniformBuffers,
  35288. samplers: samplers,
  35289. defines: defines,
  35290. maxSimultaneousLights: this._maxSimultaneousLights
  35291. });
  35292. var onCompiled = function (effect) {
  35293. if (_this.onCompiled) {
  35294. _this.onCompiled(effect);
  35295. }
  35296. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35297. };
  35298. var join = defines.toString();
  35299. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35300. attributes: attribs,
  35301. uniformsNames: uniforms,
  35302. uniformBuffersNames: uniformBuffers,
  35303. samplers: samplers,
  35304. defines: join,
  35305. fallbacks: fallbacks,
  35306. onCompiled: onCompiled,
  35307. onError: this.onError,
  35308. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35309. }, engine), defines);
  35310. this.buildUniformLayout();
  35311. }
  35312. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35313. return false;
  35314. }
  35315. defines._renderId = scene.getRenderId();
  35316. this._wasPreviouslyReady = true;
  35317. return true;
  35318. };
  35319. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35320. // Order is important !
  35321. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35322. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35323. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35324. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35325. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35326. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35327. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35328. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35329. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35330. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35331. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35332. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35333. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35334. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35335. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35336. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35337. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35338. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35339. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35340. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35341. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35342. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35343. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35344. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35345. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35346. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35347. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35348. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35349. this._uniformBuffer.addUniform("pointSize", 1);
  35350. this._uniformBuffer.create();
  35351. };
  35352. PBRBaseMaterial.prototype.unbind = function () {
  35353. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35354. this._uniformBuffer.setTexture("reflectionSampler", null);
  35355. }
  35356. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35357. this._uniformBuffer.setTexture("refractionSampler", null);
  35358. }
  35359. _super.prototype.unbind.call(this);
  35360. };
  35361. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35362. this._activeEffect.setMatrix("world", world);
  35363. };
  35364. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35365. var scene = this.getScene();
  35366. var defines = subMesh._materialDefines;
  35367. if (!defines) {
  35368. return;
  35369. }
  35370. var effect = subMesh.effect;
  35371. if (!effect) {
  35372. return;
  35373. }
  35374. this._activeEffect = effect;
  35375. // Matrices
  35376. this.bindOnlyWorldMatrix(world);
  35377. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35378. // Bones
  35379. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35380. var reflectionTexture = null;
  35381. if (mustRebind) {
  35382. this._uniformBuffer.bindToEffect(effect, "Material");
  35383. this.bindViewProjection(effect);
  35384. reflectionTexture = this._getReflectionTexture();
  35385. var refractionTexture = this._getRefractionTexture();
  35386. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35387. // Texture uniforms
  35388. if (scene.texturesEnabled) {
  35389. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35390. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35391. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35392. }
  35393. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35394. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35395. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35396. }
  35397. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35398. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35399. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35400. }
  35401. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35402. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35403. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35404. var polynomials = reflectionTexture.sphericalPolynomial;
  35405. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35406. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35407. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35408. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35409. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35410. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35411. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35412. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35413. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35414. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35415. }
  35416. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35417. }
  35418. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35419. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35420. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35421. }
  35422. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35423. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35424. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35425. }
  35426. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35427. if (this._metallicTexture) {
  35428. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35429. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35430. }
  35431. else if (this._reflectivityTexture) {
  35432. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35433. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35434. }
  35435. if (this._microSurfaceTexture) {
  35436. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35437. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35438. }
  35439. }
  35440. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35441. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35442. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35443. if (scene._mirroredCameraPosition) {
  35444. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35445. }
  35446. else {
  35447. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35448. }
  35449. }
  35450. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35451. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35452. var depth = 1.0;
  35453. if (!refractionTexture.isCube) {
  35454. if (refractionTexture.depth) {
  35455. depth = refractionTexture.depth;
  35456. }
  35457. }
  35458. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35459. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35460. }
  35461. }
  35462. // Point size
  35463. if (this.pointsCloud) {
  35464. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35465. }
  35466. // Colors
  35467. if (defines.METALLICWORKFLOW) {
  35468. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35469. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35470. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35471. }
  35472. else {
  35473. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35474. }
  35475. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35476. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35477. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35478. // Misc
  35479. this._lightingInfos.x = this._directIntensity;
  35480. this._lightingInfos.y = this._emissiveIntensity;
  35481. this._lightingInfos.z = this._environmentIntensity;
  35482. this._lightingInfos.w = this._specularIntensity;
  35483. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35484. }
  35485. // Textures
  35486. if (scene.texturesEnabled) {
  35487. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35488. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35489. }
  35490. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35491. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35492. }
  35493. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35494. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35495. }
  35496. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35497. if (defines.LODBASEDMICROSFURACE) {
  35498. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35499. }
  35500. else {
  35501. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35502. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35503. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35504. }
  35505. }
  35506. if (defines.ENVIRONMENTBRDF) {
  35507. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35508. }
  35509. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35510. if (defines.LODBASEDMICROSFURACE) {
  35511. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35512. }
  35513. else {
  35514. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35515. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35516. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35517. }
  35518. }
  35519. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35520. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35521. }
  35522. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35523. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35524. }
  35525. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35526. if (this._metallicTexture) {
  35527. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35528. }
  35529. else if (this._reflectivityTexture) {
  35530. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35531. }
  35532. if (this._microSurfaceTexture) {
  35533. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35534. }
  35535. }
  35536. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35537. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35538. }
  35539. }
  35540. // Clip plane
  35541. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35542. // Colors
  35543. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35544. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  35545. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35546. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35547. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35548. }
  35549. if (mustRebind || !this.isFrozen) {
  35550. // Lights
  35551. if (scene.lightsEnabled && !this._disableLighting) {
  35552. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35553. }
  35554. // View
  35555. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35556. this.bindView(effect);
  35557. }
  35558. // Fog
  35559. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35560. // Morph targets
  35561. if (defines.NUM_MORPH_INFLUENCERS) {
  35562. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35563. }
  35564. // image processing
  35565. this._imageProcessingConfiguration.bind(this._activeEffect);
  35566. // Log. depth
  35567. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35568. }
  35569. this._uniformBuffer.update();
  35570. this._afterBind(mesh);
  35571. };
  35572. PBRBaseMaterial.prototype.getAnimatables = function () {
  35573. var results = [];
  35574. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35575. results.push(this._albedoTexture);
  35576. }
  35577. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35578. results.push(this._ambientTexture);
  35579. }
  35580. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35581. results.push(this._opacityTexture);
  35582. }
  35583. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35584. results.push(this._reflectionTexture);
  35585. }
  35586. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35587. results.push(this._emissiveTexture);
  35588. }
  35589. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35590. results.push(this._metallicTexture);
  35591. }
  35592. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35593. results.push(this._reflectivityTexture);
  35594. }
  35595. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35596. results.push(this._bumpTexture);
  35597. }
  35598. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35599. results.push(this._lightmapTexture);
  35600. }
  35601. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35602. results.push(this._refractionTexture);
  35603. }
  35604. return results;
  35605. };
  35606. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35607. if (this._reflectionTexture) {
  35608. return this._reflectionTexture;
  35609. }
  35610. return this.getScene().environmentTexture;
  35611. };
  35612. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35613. if (this._refractionTexture) {
  35614. return this._refractionTexture;
  35615. }
  35616. if (this._linkRefractionWithTransparency) {
  35617. return this.getScene().environmentTexture;
  35618. }
  35619. return null;
  35620. };
  35621. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35622. if (forceDisposeTextures) {
  35623. if (this._albedoTexture) {
  35624. this._albedoTexture.dispose();
  35625. }
  35626. if (this._ambientTexture) {
  35627. this._ambientTexture.dispose();
  35628. }
  35629. if (this._opacityTexture) {
  35630. this._opacityTexture.dispose();
  35631. }
  35632. if (this._reflectionTexture) {
  35633. this._reflectionTexture.dispose();
  35634. }
  35635. if (this._environmentBRDFTexture) {
  35636. this._environmentBRDFTexture.dispose();
  35637. }
  35638. if (this._emissiveTexture) {
  35639. this._emissiveTexture.dispose();
  35640. }
  35641. if (this._metallicTexture) {
  35642. this._metallicTexture.dispose();
  35643. }
  35644. if (this._reflectivityTexture) {
  35645. this._reflectivityTexture.dispose();
  35646. }
  35647. if (this._bumpTexture) {
  35648. this._bumpTexture.dispose();
  35649. }
  35650. if (this._lightmapTexture) {
  35651. this._lightmapTexture.dispose();
  35652. }
  35653. if (this._refractionTexture) {
  35654. this._refractionTexture.dispose();
  35655. }
  35656. }
  35657. this._renderTargets.dispose();
  35658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35660. }
  35661. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35662. };
  35663. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35664. __decorate([
  35665. BABYLON.serializeAsImageProcessingConfiguration()
  35666. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35667. __decorate([
  35668. BABYLON.serialize()
  35669. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35670. return PBRBaseMaterial;
  35671. }(BABYLON.PushMaterial));
  35672. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35673. })(BABYLON || (BABYLON = {}));
  35674. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35675. var BABYLON;
  35676. (function (BABYLON) {
  35677. var Internals;
  35678. (function (Internals) {
  35679. /**
  35680. * The Physically based simple base material of BJS.
  35681. *
  35682. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35683. * It is used as the base class for both the specGloss and metalRough conventions.
  35684. */
  35685. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35686. __extends(PBRBaseSimpleMaterial, _super);
  35687. /**
  35688. * Instantiates a new PBRMaterial instance.
  35689. *
  35690. * @param name The material name
  35691. * @param scene The scene the material will be use in.
  35692. */
  35693. function PBRBaseSimpleMaterial(name, scene) {
  35694. var _this = _super.call(this, name, scene) || this;
  35695. /**
  35696. * Number of Simultaneous lights allowed on the material.
  35697. */
  35698. _this.maxSimultaneousLights = 4;
  35699. /**
  35700. * If sets to true, disables all the lights affecting the material.
  35701. */
  35702. _this.disableLighting = false;
  35703. /**
  35704. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35705. */
  35706. _this.invertNormalMapX = false;
  35707. /**
  35708. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35709. */
  35710. _this.invertNormalMapY = false;
  35711. /**
  35712. * Emissivie color used to self-illuminate the model.
  35713. */
  35714. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35715. /**
  35716. * Occlusion Channel Strenght.
  35717. */
  35718. _this.occlusionStrength = 1.0;
  35719. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35720. _this._useAmbientInGrayScale = true;
  35721. return _this;
  35722. }
  35723. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35724. /**
  35725. * Gets the current transparency mode.
  35726. */
  35727. get: function () {
  35728. return this._transparencyMode;
  35729. },
  35730. /**
  35731. * Sets the transparency mode of the material.
  35732. */
  35733. set: function (value) {
  35734. if (this._transparencyMode === value) {
  35735. return;
  35736. }
  35737. this._transparencyMode = value;
  35738. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35739. this._forceAlphaTest = true;
  35740. }
  35741. else {
  35742. this._forceAlphaTest = false;
  35743. }
  35744. this._markAllSubMeshesAsTexturesDirty();
  35745. },
  35746. enumerable: true,
  35747. configurable: true
  35748. });
  35749. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35750. /**
  35751. * Gets the current double sided mode.
  35752. */
  35753. get: function () {
  35754. return this._twoSidedLighting;
  35755. },
  35756. /**
  35757. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35758. */
  35759. set: function (value) {
  35760. if (this._twoSidedLighting === value) {
  35761. return;
  35762. }
  35763. this._twoSidedLighting = value;
  35764. this.backFaceCulling = !value;
  35765. this._markAllSubMeshesAsTexturesDirty();
  35766. },
  35767. enumerable: true,
  35768. configurable: true
  35769. });
  35770. /**
  35771. * Specifies wether or not the alpha value of the albedo texture should be used.
  35772. */
  35773. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35774. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35775. };
  35776. /**
  35777. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35778. */
  35779. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35780. if (this._linkRefractionWithTransparency) {
  35781. return false;
  35782. }
  35783. return (this.alpha < 1.0) ||
  35784. (this._shouldUseAlphaFromAlbedoTexture() &&
  35785. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35786. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35787. };
  35788. /**
  35789. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35790. */
  35791. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35792. if (this._linkRefractionWithTransparency) {
  35793. return false;
  35794. }
  35795. return this._shouldUseAlphaFromAlbedoTexture() &&
  35796. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35797. };
  35798. /**
  35799. * Return the active textures of the material.
  35800. */
  35801. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  35802. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35803. if (this.environmentTexture) {
  35804. activeTextures.push(this.environmentTexture);
  35805. }
  35806. if (this.normalTexture) {
  35807. activeTextures.push(this.normalTexture);
  35808. }
  35809. if (this.emissiveTexture) {
  35810. activeTextures.push(this.emissiveTexture);
  35811. }
  35812. if (this.occlusionTexture) {
  35813. activeTextures.push(this.occlusionTexture);
  35814. }
  35815. return activeTextures;
  35816. };
  35817. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  35818. return "PBRBaseSimpleMaterial";
  35819. };
  35820. __decorate([
  35821. BABYLON.serialize(),
  35822. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35823. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35824. __decorate([
  35825. BABYLON.serialize(),
  35826. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35827. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35828. __decorate([
  35829. BABYLON.serializeAsTexture(),
  35830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35831. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35832. __decorate([
  35833. BABYLON.serialize(),
  35834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35835. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35836. __decorate([
  35837. BABYLON.serialize(),
  35838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35839. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35840. __decorate([
  35841. BABYLON.serializeAsTexture(),
  35842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35843. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35844. __decorate([
  35845. BABYLON.serializeAsColor3("emissive"),
  35846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35847. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35848. __decorate([
  35849. BABYLON.serializeAsTexture(),
  35850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35851. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35852. __decorate([
  35853. BABYLON.serialize(),
  35854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35855. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35856. __decorate([
  35857. BABYLON.serializeAsTexture(),
  35858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35859. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35860. __decorate([
  35861. BABYLON.serialize(),
  35862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35863. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35864. __decorate([
  35865. BABYLON.serialize()
  35866. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35867. __decorate([
  35868. BABYLON.serialize()
  35869. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35870. return PBRBaseSimpleMaterial;
  35871. }(BABYLON.PBRBaseMaterial));
  35872. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35873. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35874. })(BABYLON || (BABYLON = {}));
  35875. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35876. var BABYLON;
  35877. (function (BABYLON) {
  35878. /**
  35879. * The Physically based material of BJS.
  35880. *
  35881. * This offers the main features of a standard PBR material.
  35882. * For more information, please refer to the documentation :
  35883. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35884. */
  35885. var PBRMaterial = /** @class */ (function (_super) {
  35886. __extends(PBRMaterial, _super);
  35887. /**
  35888. * Instantiates a new PBRMaterial instance.
  35889. *
  35890. * @param name The material name
  35891. * @param scene The scene the material will be use in.
  35892. */
  35893. function PBRMaterial(name, scene) {
  35894. var _this = _super.call(this, name, scene) || this;
  35895. /**
  35896. * Intensity of the direct lights e.g. the four lights available in your scene.
  35897. * This impacts both the direct diffuse and specular highlights.
  35898. */
  35899. _this.directIntensity = 1.0;
  35900. /**
  35901. * Intensity of the emissive part of the material.
  35902. * This helps controlling the emissive effect without modifying the emissive color.
  35903. */
  35904. _this.emissiveIntensity = 1.0;
  35905. /**
  35906. * Intensity of the environment e.g. how much the environment will light the object
  35907. * either through harmonics for rough material or through the refelction for shiny ones.
  35908. */
  35909. _this.environmentIntensity = 1.0;
  35910. /**
  35911. * This is a special control allowing the reduction of the specular highlights coming from the
  35912. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35913. */
  35914. _this.specularIntensity = 1.0;
  35915. /**
  35916. * Debug Control allowing disabling the bump map on this material.
  35917. */
  35918. _this.disableBumpMap = false;
  35919. /**
  35920. * AKA Occlusion Texture Intensity in other nomenclature.
  35921. */
  35922. _this.ambientTextureStrength = 1.0;
  35923. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35924. /**
  35925. * AKA Diffuse Color in other nomenclature.
  35926. */
  35927. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35928. /**
  35929. * AKA Specular Color in other nomenclature.
  35930. */
  35931. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35932. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  35933. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35934. /**
  35935. * AKA Glossiness in other nomenclature.
  35936. */
  35937. _this.microSurface = 1.0;
  35938. /**
  35939. * source material index of refraction (IOR)' / 'destination material IOR.
  35940. */
  35941. _this.indexOfRefraction = 0.66;
  35942. /**
  35943. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35944. */
  35945. _this.invertRefractionY = false;
  35946. /**
  35947. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35948. * Materials half opaque for instance using refraction could benefit from this control.
  35949. */
  35950. _this.linkRefractionWithTransparency = false;
  35951. _this.useLightmapAsShadowmap = false;
  35952. /**
  35953. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35954. */
  35955. _this.useAlphaFromAlbedoTexture = false;
  35956. /**
  35957. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35958. */
  35959. _this.forceAlphaTest = false;
  35960. /**
  35961. * Defines the alpha limits in alpha test mode.
  35962. */
  35963. _this.alphaCutOff = 0.4;
  35964. /**
  35965. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35966. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35967. */
  35968. _this.useSpecularOverAlpha = true;
  35969. /**
  35970. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35971. */
  35972. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35973. /**
  35974. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35975. */
  35976. _this.useRoughnessFromMetallicTextureAlpha = true;
  35977. /**
  35978. * Specifies if the metallic texture contains the roughness information in its green channel.
  35979. */
  35980. _this.useRoughnessFromMetallicTextureGreen = false;
  35981. /**
  35982. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35983. */
  35984. _this.useMetallnessFromMetallicTextureBlue = false;
  35985. /**
  35986. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35987. */
  35988. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35989. /**
  35990. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35991. */
  35992. _this.useAmbientInGrayScale = false;
  35993. /**
  35994. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35995. * The material will try to infer what glossiness each pixel should be.
  35996. */
  35997. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35998. /**
  35999. * BJS is using an harcoded light falloff based on a manually sets up range.
  36000. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36001. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36002. */
  36003. _this.usePhysicalLightFalloff = true;
  36004. /**
  36005. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36006. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36007. */
  36008. _this.useRadianceOverAlpha = true;
  36009. /**
  36010. * Allows using the bump map in parallax mode.
  36011. */
  36012. _this.useParallax = false;
  36013. /**
  36014. * Allows using the bump map in parallax occlusion mode.
  36015. */
  36016. _this.useParallaxOcclusion = false;
  36017. /**
  36018. * Controls the scale bias of the parallax mode.
  36019. */
  36020. _this.parallaxScaleBias = 0.05;
  36021. /**
  36022. * If sets to true, disables all the lights affecting the material.
  36023. */
  36024. _this.disableLighting = false;
  36025. /**
  36026. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36027. */
  36028. _this.forceIrradianceInFragment = false;
  36029. /**
  36030. * Number of Simultaneous lights allowed on the material.
  36031. */
  36032. _this.maxSimultaneousLights = 4;
  36033. /**
  36034. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36035. */
  36036. _this.invertNormalMapX = false;
  36037. /**
  36038. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36039. */
  36040. _this.invertNormalMapY = false;
  36041. /**
  36042. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36043. */
  36044. _this.twoSidedLighting = false;
  36045. /**
  36046. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36047. * And/Or occlude the blended part.
  36048. */
  36049. _this.useAlphaFresnel = false;
  36050. /**
  36051. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36052. * And/Or occlude the blended part.
  36053. */
  36054. _this.environmentBRDFTexture = null;
  36055. /**
  36056. * Force normal to face away from face.
  36057. * (Temporary internal fix to remove before 3.1)
  36058. */
  36059. _this.forceNormalForward = false;
  36060. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36061. return _this;
  36062. }
  36063. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36064. /**
  36065. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36066. */
  36067. get: function () {
  36068. return this._PBRMATERIAL_OPAQUE;
  36069. },
  36070. enumerable: true,
  36071. configurable: true
  36072. });
  36073. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36074. /**
  36075. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36076. */
  36077. get: function () {
  36078. return this._PBRMATERIAL_ALPHATEST;
  36079. },
  36080. enumerable: true,
  36081. configurable: true
  36082. });
  36083. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36084. /**
  36085. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36086. */
  36087. get: function () {
  36088. return this._PBRMATERIAL_ALPHABLEND;
  36089. },
  36090. enumerable: true,
  36091. configurable: true
  36092. });
  36093. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36094. /**
  36095. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36096. * They are also discarded below the alpha cutoff threshold to improve performances.
  36097. */
  36098. get: function () {
  36099. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36100. },
  36101. enumerable: true,
  36102. configurable: true
  36103. });
  36104. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36105. /**
  36106. * Gets the image processing configuration used either in this material.
  36107. */
  36108. get: function () {
  36109. return this._imageProcessingConfiguration;
  36110. },
  36111. /**
  36112. * Sets the Default image processing configuration used either in the this material.
  36113. *
  36114. * If sets to null, the scene one is in use.
  36115. */
  36116. set: function (value) {
  36117. this._attachImageProcessingConfiguration(value);
  36118. // Ensure the effect will be rebuilt.
  36119. this._markAllSubMeshesAsTexturesDirty();
  36120. },
  36121. enumerable: true,
  36122. configurable: true
  36123. });
  36124. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36125. /**
  36126. * Gets wether the color curves effect is enabled.
  36127. */
  36128. get: function () {
  36129. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36130. },
  36131. /**
  36132. * Sets wether the color curves effect is enabled.
  36133. */
  36134. set: function (value) {
  36135. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36136. },
  36137. enumerable: true,
  36138. configurable: true
  36139. });
  36140. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36141. /**
  36142. * Gets wether the color grading effect is enabled.
  36143. */
  36144. get: function () {
  36145. return this.imageProcessingConfiguration.colorGradingEnabled;
  36146. },
  36147. /**
  36148. * Gets wether the color grading effect is enabled.
  36149. */
  36150. set: function (value) {
  36151. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36152. },
  36153. enumerable: true,
  36154. configurable: true
  36155. });
  36156. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36157. /**
  36158. * Gets wether tonemapping is enabled or not.
  36159. */
  36160. get: function () {
  36161. return this._imageProcessingConfiguration.toneMappingEnabled;
  36162. },
  36163. /**
  36164. * Sets wether tonemapping is enabled or not
  36165. */
  36166. set: function (value) {
  36167. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. ;
  36173. ;
  36174. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36175. /**
  36176. * The camera exposure used on this material.
  36177. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36178. * This corresponds to a photographic exposure.
  36179. */
  36180. get: function () {
  36181. return this._imageProcessingConfiguration.exposure;
  36182. },
  36183. /**
  36184. * The camera exposure used on this material.
  36185. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36186. * This corresponds to a photographic exposure.
  36187. */
  36188. set: function (value) {
  36189. this._imageProcessingConfiguration.exposure = value;
  36190. },
  36191. enumerable: true,
  36192. configurable: true
  36193. });
  36194. ;
  36195. ;
  36196. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36197. /**
  36198. * Gets The camera contrast used on this material.
  36199. */
  36200. get: function () {
  36201. return this._imageProcessingConfiguration.contrast;
  36202. },
  36203. /**
  36204. * Sets The camera contrast used on this material.
  36205. */
  36206. set: function (value) {
  36207. this._imageProcessingConfiguration.contrast = value;
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36213. /**
  36214. * Gets the Color Grading 2D Lookup Texture.
  36215. */
  36216. get: function () {
  36217. return this._imageProcessingConfiguration.colorGradingTexture;
  36218. },
  36219. /**
  36220. * Sets the Color Grading 2D Lookup Texture.
  36221. */
  36222. set: function (value) {
  36223. this._imageProcessingConfiguration.colorGradingTexture = value;
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36229. /**
  36230. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36231. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36232. * 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;
  36233. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36234. */
  36235. get: function () {
  36236. return this._imageProcessingConfiguration.colorCurves;
  36237. },
  36238. /**
  36239. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36240. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36241. * 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;
  36242. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36243. */
  36244. set: function (value) {
  36245. this._imageProcessingConfiguration.colorCurves = value;
  36246. },
  36247. enumerable: true,
  36248. configurable: true
  36249. });
  36250. PBRMaterial.prototype.getClassName = function () {
  36251. return "PBRMaterial";
  36252. };
  36253. PBRMaterial.prototype.getActiveTextures = function () {
  36254. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36255. if (this._albedoTexture) {
  36256. activeTextures.push(this._albedoTexture);
  36257. }
  36258. if (this._ambientTexture) {
  36259. activeTextures.push(this._ambientTexture);
  36260. }
  36261. if (this._opacityTexture) {
  36262. activeTextures.push(this._opacityTexture);
  36263. }
  36264. if (this._reflectionTexture) {
  36265. activeTextures.push(this._reflectionTexture);
  36266. }
  36267. if (this._emissiveTexture) {
  36268. activeTextures.push(this._emissiveTexture);
  36269. }
  36270. if (this._reflectivityTexture) {
  36271. activeTextures.push(this._reflectivityTexture);
  36272. }
  36273. if (this._metallicTexture) {
  36274. activeTextures.push(this._metallicTexture);
  36275. }
  36276. if (this._microSurfaceTexture) {
  36277. activeTextures.push(this._microSurfaceTexture);
  36278. }
  36279. if (this._bumpTexture) {
  36280. activeTextures.push(this._bumpTexture);
  36281. }
  36282. if (this._lightmapTexture) {
  36283. activeTextures.push(this._lightmapTexture);
  36284. }
  36285. if (this._refractionTexture) {
  36286. activeTextures.push(this._refractionTexture);
  36287. }
  36288. return activeTextures;
  36289. };
  36290. PBRMaterial.prototype.hasTexture = function (texture) {
  36291. if (_super.prototype.hasTexture.call(this, texture)) {
  36292. return true;
  36293. }
  36294. if (this._albedoTexture === texture) {
  36295. return true;
  36296. }
  36297. if (this._ambientTexture === texture) {
  36298. return true;
  36299. }
  36300. if (this._opacityTexture === texture) {
  36301. return true;
  36302. }
  36303. if (this._reflectionTexture === texture) {
  36304. return true;
  36305. }
  36306. if (this._reflectivityTexture === texture) {
  36307. return true;
  36308. }
  36309. if (this._metallicTexture === texture) {
  36310. return true;
  36311. }
  36312. if (this._microSurfaceTexture === texture) {
  36313. return true;
  36314. }
  36315. if (this._bumpTexture === texture) {
  36316. return true;
  36317. }
  36318. if (this._lightmapTexture === texture) {
  36319. return true;
  36320. }
  36321. if (this._refractionTexture === texture) {
  36322. return true;
  36323. }
  36324. return false;
  36325. };
  36326. PBRMaterial.prototype.clone = function (name) {
  36327. var _this = this;
  36328. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36329. clone.id = name;
  36330. clone.name = name;
  36331. return clone;
  36332. };
  36333. PBRMaterial.prototype.serialize = function () {
  36334. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36335. serializationObject.customType = "BABYLON.PBRMaterial";
  36336. return serializationObject;
  36337. };
  36338. // Statics
  36339. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36340. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36341. };
  36342. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36343. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36344. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36345. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36346. __decorate([
  36347. BABYLON.serialize(),
  36348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36349. ], PBRMaterial.prototype, "directIntensity", void 0);
  36350. __decorate([
  36351. BABYLON.serialize(),
  36352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36353. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36354. __decorate([
  36355. BABYLON.serialize(),
  36356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36357. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36358. __decorate([
  36359. BABYLON.serialize(),
  36360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36361. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36362. __decorate([
  36363. BABYLON.serialize(),
  36364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36365. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36366. __decorate([
  36367. BABYLON.serializeAsTexture(),
  36368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36369. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36370. __decorate([
  36371. BABYLON.serializeAsTexture(),
  36372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36373. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36374. __decorate([
  36375. BABYLON.serialize(),
  36376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36377. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36378. __decorate([
  36379. BABYLON.serializeAsTexture(),
  36380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36381. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36382. __decorate([
  36383. BABYLON.serializeAsTexture(),
  36384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36385. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36386. __decorate([
  36387. BABYLON.serializeAsTexture(),
  36388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36389. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36390. __decorate([
  36391. BABYLON.serializeAsTexture(),
  36392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36393. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36394. __decorate([
  36395. BABYLON.serializeAsTexture(),
  36396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36397. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36398. __decorate([
  36399. BABYLON.serialize(),
  36400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36401. ], PBRMaterial.prototype, "metallic", void 0);
  36402. __decorate([
  36403. BABYLON.serialize(),
  36404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36405. ], PBRMaterial.prototype, "roughness", void 0);
  36406. __decorate([
  36407. BABYLON.serializeAsTexture(),
  36408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36409. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36410. __decorate([
  36411. BABYLON.serializeAsTexture(),
  36412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36413. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36414. __decorate([
  36415. BABYLON.serializeAsTexture(),
  36416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36417. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36418. __decorate([
  36419. BABYLON.serializeAsTexture(),
  36420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36421. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36422. __decorate([
  36423. BABYLON.serializeAsColor3("ambient"),
  36424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36425. ], PBRMaterial.prototype, "ambientColor", void 0);
  36426. __decorate([
  36427. BABYLON.serializeAsColor3("albedo"),
  36428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36429. ], PBRMaterial.prototype, "albedoColor", void 0);
  36430. __decorate([
  36431. BABYLON.serializeAsColor3("reflectivity"),
  36432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36433. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36434. __decorate([
  36435. BABYLON.serializeAsColor3("reflection"),
  36436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36437. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36438. __decorate([
  36439. BABYLON.serializeAsColor3("emissive"),
  36440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36441. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36442. __decorate([
  36443. BABYLON.serialize(),
  36444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36445. ], PBRMaterial.prototype, "microSurface", void 0);
  36446. __decorate([
  36447. BABYLON.serialize(),
  36448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36449. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36450. __decorate([
  36451. BABYLON.serialize(),
  36452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36453. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36454. __decorate([
  36455. BABYLON.serialize(),
  36456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36457. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36458. __decorate([
  36459. BABYLON.serialize(),
  36460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36461. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36462. __decorate([
  36463. BABYLON.serialize(),
  36464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36465. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36466. __decorate([
  36467. BABYLON.serialize(),
  36468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36469. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36470. __decorate([
  36471. BABYLON.serialize(),
  36472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36473. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36474. __decorate([
  36475. BABYLON.serialize(),
  36476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36477. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36478. __decorate([
  36479. BABYLON.serialize(),
  36480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36481. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36482. __decorate([
  36483. BABYLON.serialize(),
  36484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36485. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36486. __decorate([
  36487. BABYLON.serialize(),
  36488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36489. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36490. __decorate([
  36491. BABYLON.serialize(),
  36492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36493. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36494. __decorate([
  36495. BABYLON.serialize(),
  36496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36497. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36498. __decorate([
  36499. BABYLON.serialize(),
  36500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36501. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36502. __decorate([
  36503. BABYLON.serialize(),
  36504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36505. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36506. __decorate([
  36507. BABYLON.serialize(),
  36508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36509. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36510. __decorate([
  36511. BABYLON.serialize(),
  36512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36513. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36514. __decorate([
  36515. BABYLON.serialize(),
  36516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36517. ], PBRMaterial.prototype, "useParallax", void 0);
  36518. __decorate([
  36519. BABYLON.serialize(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36521. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36522. __decorate([
  36523. BABYLON.serialize(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36525. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36526. __decorate([
  36527. BABYLON.serialize(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36529. ], PBRMaterial.prototype, "disableLighting", void 0);
  36530. __decorate([
  36531. BABYLON.serialize(),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36533. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36534. __decorate([
  36535. BABYLON.serialize(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36537. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36538. __decorate([
  36539. BABYLON.serialize(),
  36540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36541. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36542. __decorate([
  36543. BABYLON.serialize(),
  36544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36545. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36546. __decorate([
  36547. BABYLON.serialize(),
  36548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36549. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36550. __decorate([
  36551. BABYLON.serialize(),
  36552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36553. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36554. __decorate([
  36555. BABYLON.serializeAsTexture(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36558. __decorate([
  36559. BABYLON.serialize(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36562. return PBRMaterial;
  36563. }(BABYLON.PBRBaseMaterial));
  36564. BABYLON.PBRMaterial = PBRMaterial;
  36565. })(BABYLON || (BABYLON = {}));
  36566. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36567. var BABYLON;
  36568. (function (BABYLON) {
  36569. /**
  36570. * The PBR material of BJS following the metal roughness convention.
  36571. *
  36572. * This fits to the PBR convention in the GLTF definition:
  36573. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36574. */
  36575. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36576. __extends(PBRMetallicRoughnessMaterial, _super);
  36577. /**
  36578. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36579. *
  36580. * @param name The material name
  36581. * @param scene The scene the material will be use in.
  36582. */
  36583. function PBRMetallicRoughnessMaterial(name, scene) {
  36584. var _this = _super.call(this, name, scene) || this;
  36585. _this._useRoughnessFromMetallicTextureAlpha = false;
  36586. _this._useRoughnessFromMetallicTextureGreen = true;
  36587. _this._useMetallnessFromMetallicTextureBlue = true;
  36588. return _this;
  36589. }
  36590. /**
  36591. * Return the currrent class name of the material.
  36592. */
  36593. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36594. return "PBRMetallicRoughnessMaterial";
  36595. };
  36596. /**
  36597. * Return the active textures of the material.
  36598. */
  36599. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36600. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36601. if (this.baseTexture) {
  36602. activeTextures.push(this.baseTexture);
  36603. }
  36604. if (this.metallicRoughnessTexture) {
  36605. activeTextures.push(this.metallicRoughnessTexture);
  36606. }
  36607. return activeTextures;
  36608. };
  36609. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36610. if (_super.prototype.hasTexture.call(this, texture)) {
  36611. return true;
  36612. }
  36613. if (this.baseTexture === texture) {
  36614. return true;
  36615. }
  36616. if (this.metallicRoughnessTexture === texture) {
  36617. return true;
  36618. }
  36619. return false;
  36620. };
  36621. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36622. var _this = this;
  36623. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36624. clone.id = name;
  36625. clone.name = name;
  36626. return clone;
  36627. };
  36628. /**
  36629. * Serialize the material to a parsable JSON object.
  36630. */
  36631. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36632. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36633. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36634. return serializationObject;
  36635. };
  36636. /**
  36637. * Parses a JSON object correponding to the serialize function.
  36638. */
  36639. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36640. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36641. };
  36642. __decorate([
  36643. BABYLON.serializeAsColor3(),
  36644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36645. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36646. __decorate([
  36647. BABYLON.serializeAsTexture(),
  36648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36649. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36650. __decorate([
  36651. BABYLON.serialize(),
  36652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36653. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36654. __decorate([
  36655. BABYLON.serialize(),
  36656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36657. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36658. __decorate([
  36659. BABYLON.serializeAsTexture(),
  36660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36661. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36662. return PBRMetallicRoughnessMaterial;
  36663. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36664. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36665. })(BABYLON || (BABYLON = {}));
  36666. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36667. var BABYLON;
  36668. (function (BABYLON) {
  36669. /**
  36670. * The PBR material of BJS following the specular glossiness convention.
  36671. *
  36672. * This fits to the PBR convention in the GLTF definition:
  36673. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36674. */
  36675. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36676. __extends(PBRSpecularGlossinessMaterial, _super);
  36677. /**
  36678. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36679. *
  36680. * @param name The material name
  36681. * @param scene The scene the material will be use in.
  36682. */
  36683. function PBRSpecularGlossinessMaterial(name, scene) {
  36684. var _this = _super.call(this, name, scene) || this;
  36685. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36686. return _this;
  36687. }
  36688. /**
  36689. * Return the currrent class name of the material.
  36690. */
  36691. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36692. return "PBRSpecularGlossinessMaterial";
  36693. };
  36694. /**
  36695. * Return the active textures of the material.
  36696. */
  36697. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36698. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36699. if (this.diffuseTexture) {
  36700. activeTextures.push(this.diffuseTexture);
  36701. }
  36702. if (this.specularGlossinessTexture) {
  36703. activeTextures.push(this.specularGlossinessTexture);
  36704. }
  36705. return activeTextures;
  36706. };
  36707. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36708. if (_super.prototype.hasTexture.call(this, texture)) {
  36709. return true;
  36710. }
  36711. if (this.diffuseTexture === texture) {
  36712. return true;
  36713. }
  36714. if (this.specularGlossinessTexture === texture) {
  36715. return true;
  36716. }
  36717. return false;
  36718. };
  36719. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36720. var _this = this;
  36721. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36722. clone.id = name;
  36723. clone.name = name;
  36724. return clone;
  36725. };
  36726. /**
  36727. * Serialize the material to a parsable JSON object.
  36728. */
  36729. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36730. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36731. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36732. return serializationObject;
  36733. };
  36734. /**
  36735. * Parses a JSON object correponding to the serialize function.
  36736. */
  36737. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36738. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36739. };
  36740. __decorate([
  36741. BABYLON.serializeAsColor3("diffuse"),
  36742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36743. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36744. __decorate([
  36745. BABYLON.serializeAsTexture(),
  36746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36747. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36748. __decorate([
  36749. BABYLON.serializeAsColor3("specular"),
  36750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36751. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36752. __decorate([
  36753. BABYLON.serialize(),
  36754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36755. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36756. __decorate([
  36757. BABYLON.serializeAsTexture(),
  36758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36759. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36760. return PBRSpecularGlossinessMaterial;
  36761. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36762. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36763. })(BABYLON || (BABYLON = {}));
  36764. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36765. var BABYLON;
  36766. (function (BABYLON) {
  36767. BABYLON.CameraInputTypes = {};
  36768. var CameraInputsManager = /** @class */ (function () {
  36769. function CameraInputsManager(camera) {
  36770. this.attached = {};
  36771. this.camera = camera;
  36772. this.checkInputs = function () { };
  36773. }
  36774. CameraInputsManager.prototype.add = function (input) {
  36775. var type = input.getSimpleName();
  36776. if (this.attached[type]) {
  36777. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36778. return;
  36779. }
  36780. this.attached[type] = input;
  36781. input.camera = this.camera;
  36782. //for checkInputs, we are dynamically creating a function
  36783. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36784. if (input.checkInputs) {
  36785. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36786. }
  36787. if (this.attachedElement) {
  36788. input.attachControl(this.attachedElement);
  36789. }
  36790. };
  36791. CameraInputsManager.prototype.remove = function (inputToRemove) {
  36792. for (var cam in this.attached) {
  36793. var input = this.attached[cam];
  36794. if (input === inputToRemove) {
  36795. input.detachControl(this.attachedElement);
  36796. input.camera = null;
  36797. delete this.attached[cam];
  36798. this.rebuildInputCheck();
  36799. }
  36800. }
  36801. };
  36802. CameraInputsManager.prototype.removeByType = function (inputType) {
  36803. for (var cam in this.attached) {
  36804. var input = this.attached[cam];
  36805. if (input.getClassName() === inputType) {
  36806. input.detachControl(this.attachedElement);
  36807. input.camera = null;
  36808. delete this.attached[cam];
  36809. this.rebuildInputCheck();
  36810. }
  36811. }
  36812. };
  36813. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  36814. var current = this.checkInputs;
  36815. return function () {
  36816. current();
  36817. fn();
  36818. };
  36819. };
  36820. CameraInputsManager.prototype.attachInput = function (input) {
  36821. if (this.attachedElement) {
  36822. input.attachControl(this.attachedElement, this.noPreventDefault);
  36823. }
  36824. };
  36825. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  36826. if (noPreventDefault === void 0) { noPreventDefault = false; }
  36827. if (this.attachedElement) {
  36828. return;
  36829. }
  36830. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  36831. this.attachedElement = element;
  36832. this.noPreventDefault = noPreventDefault;
  36833. for (var cam in this.attached) {
  36834. this.attached[cam].attachControl(element, noPreventDefault);
  36835. }
  36836. };
  36837. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  36838. if (disconnect === void 0) { disconnect = false; }
  36839. if (this.attachedElement !== element) {
  36840. return;
  36841. }
  36842. for (var cam in this.attached) {
  36843. this.attached[cam].detachControl(element);
  36844. if (disconnect) {
  36845. this.attached[cam].camera = null;
  36846. }
  36847. }
  36848. this.attachedElement = null;
  36849. };
  36850. CameraInputsManager.prototype.rebuildInputCheck = function () {
  36851. this.checkInputs = function () { };
  36852. for (var cam in this.attached) {
  36853. var input = this.attached[cam];
  36854. if (input.checkInputs) {
  36855. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36856. }
  36857. }
  36858. };
  36859. CameraInputsManager.prototype.clear = function () {
  36860. if (this.attachedElement) {
  36861. this.detachElement(this.attachedElement, true);
  36862. }
  36863. this.attached = {};
  36864. this.attachedElement = null;
  36865. this.checkInputs = function () { };
  36866. };
  36867. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  36868. var inputs = {};
  36869. for (var cam in this.attached) {
  36870. var input = this.attached[cam];
  36871. var res = BABYLON.SerializationHelper.Serialize(input);
  36872. inputs[input.getClassName()] = res;
  36873. }
  36874. serializedCamera.inputsmgr = inputs;
  36875. };
  36876. CameraInputsManager.prototype.parse = function (parsedCamera) {
  36877. var parsedInputs = parsedCamera.inputsmgr;
  36878. if (parsedInputs) {
  36879. this.clear();
  36880. for (var n in parsedInputs) {
  36881. var construct = BABYLON.CameraInputTypes[n];
  36882. if (construct) {
  36883. var parsedinput = parsedInputs[n];
  36884. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  36885. this.add(input);
  36886. }
  36887. }
  36888. }
  36889. else {
  36890. //2016-03-08 this part is for managing backward compatibility
  36891. for (var n in this.attached) {
  36892. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  36893. if (construct) {
  36894. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  36895. this.remove(this.attached[n]);
  36896. this.add(input);
  36897. }
  36898. }
  36899. }
  36900. };
  36901. return CameraInputsManager;
  36902. }());
  36903. BABYLON.CameraInputsManager = CameraInputsManager;
  36904. })(BABYLON || (BABYLON = {}));
  36905. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  36906. var BABYLON;
  36907. (function (BABYLON) {
  36908. var FreeCameraMouseInput = /** @class */ (function () {
  36909. function FreeCameraMouseInput(touchEnabled) {
  36910. if (touchEnabled === void 0) { touchEnabled = true; }
  36911. this.touchEnabled = touchEnabled;
  36912. this.buttons = [0, 1, 2];
  36913. this.angularSensibility = 2000.0;
  36914. this.previousPosition = null;
  36915. }
  36916. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  36917. var _this = this;
  36918. var engine = this.camera.getEngine();
  36919. if (!this._pointerInput) {
  36920. this._pointerInput = function (p, s) {
  36921. var evt = p.event;
  36922. if (engine.isInVRExclusivePointerMode) {
  36923. return;
  36924. }
  36925. if (!_this.touchEnabled && evt.pointerType === "touch") {
  36926. return;
  36927. }
  36928. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36929. return;
  36930. }
  36931. var srcElement = (evt.srcElement || evt.target);
  36932. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  36933. try {
  36934. srcElement.setPointerCapture(evt.pointerId);
  36935. }
  36936. catch (e) {
  36937. //Nothing to do with the error. Execution will continue.
  36938. }
  36939. _this.previousPosition = {
  36940. x: evt.clientX,
  36941. y: evt.clientY
  36942. };
  36943. if (!noPreventDefault) {
  36944. evt.preventDefault();
  36945. element.focus();
  36946. }
  36947. }
  36948. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  36949. try {
  36950. srcElement.releasePointerCapture(evt.pointerId);
  36951. }
  36952. catch (e) {
  36953. //Nothing to do with the error.
  36954. }
  36955. _this.previousPosition = null;
  36956. if (!noPreventDefault) {
  36957. evt.preventDefault();
  36958. }
  36959. }
  36960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36961. if (!_this.previousPosition || engine.isPointerLock) {
  36962. return;
  36963. }
  36964. var offsetX = evt.clientX - _this.previousPosition.x;
  36965. var offsetY = evt.clientY - _this.previousPosition.y;
  36966. if (_this.camera.getScene().useRightHandedSystem) {
  36967. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36968. }
  36969. else {
  36970. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36971. }
  36972. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36973. _this.previousPosition = {
  36974. x: evt.clientX,
  36975. y: evt.clientY
  36976. };
  36977. if (!noPreventDefault) {
  36978. evt.preventDefault();
  36979. }
  36980. }
  36981. };
  36982. }
  36983. this._onMouseMove = function (evt) {
  36984. if (!engine.isPointerLock) {
  36985. return;
  36986. }
  36987. if (engine.isInVRExclusivePointerMode) {
  36988. return;
  36989. }
  36990. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36991. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36992. if (_this.camera.getScene().useRightHandedSystem) {
  36993. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  36994. }
  36995. else {
  36996. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  36997. }
  36998. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  36999. _this.previousPosition = null;
  37000. if (!noPreventDefault) {
  37001. evt.preventDefault();
  37002. }
  37003. };
  37004. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37005. element.addEventListener("mousemove", this._onMouseMove, false);
  37006. };
  37007. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37008. if (this._observer && element) {
  37009. this.camera.getScene().onPointerObservable.remove(this._observer);
  37010. if (this._onMouseMove) {
  37011. element.removeEventListener("mousemove", this._onMouseMove);
  37012. }
  37013. this._observer = null;
  37014. this._onMouseMove = null;
  37015. this.previousPosition = null;
  37016. }
  37017. };
  37018. FreeCameraMouseInput.prototype.getClassName = function () {
  37019. return "FreeCameraMouseInput";
  37020. };
  37021. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37022. return "mouse";
  37023. };
  37024. __decorate([
  37025. BABYLON.serialize()
  37026. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37027. __decorate([
  37028. BABYLON.serialize()
  37029. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37030. return FreeCameraMouseInput;
  37031. }());
  37032. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37033. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37034. })(BABYLON || (BABYLON = {}));
  37035. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37036. var BABYLON;
  37037. (function (BABYLON) {
  37038. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37039. function FreeCameraKeyboardMoveInput() {
  37040. this._keys = new Array();
  37041. this.keysUp = [38];
  37042. this.keysDown = [40];
  37043. this.keysLeft = [37];
  37044. this.keysRight = [39];
  37045. }
  37046. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37047. var _this = this;
  37048. if (this._onCanvasBlurObserver) {
  37049. return;
  37050. }
  37051. this._scene = this.camera.getScene();
  37052. this._engine = this._scene.getEngine();
  37053. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37054. _this._keys = [];
  37055. });
  37056. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37057. var evt = info.event;
  37058. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37059. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37060. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37061. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37062. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37063. var index = _this._keys.indexOf(evt.keyCode);
  37064. if (index === -1) {
  37065. _this._keys.push(evt.keyCode);
  37066. }
  37067. if (!noPreventDefault) {
  37068. evt.preventDefault();
  37069. }
  37070. }
  37071. }
  37072. else {
  37073. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37074. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37075. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37076. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37077. var index = _this._keys.indexOf(evt.keyCode);
  37078. if (index >= 0) {
  37079. _this._keys.splice(index, 1);
  37080. }
  37081. if (!noPreventDefault) {
  37082. evt.preventDefault();
  37083. }
  37084. }
  37085. }
  37086. });
  37087. };
  37088. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37089. if (this._scene) {
  37090. if (this._onKeyboardObserver) {
  37091. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37092. }
  37093. if (this._onCanvasBlurObserver) {
  37094. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37095. }
  37096. this._onKeyboardObserver = null;
  37097. this._onCanvasBlurObserver = null;
  37098. }
  37099. this._keys = [];
  37100. };
  37101. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37102. if (this._onKeyboardObserver) {
  37103. var camera = this.camera;
  37104. // Keyboard
  37105. for (var index = 0; index < this._keys.length; index++) {
  37106. var keyCode = this._keys[index];
  37107. var speed = camera._computeLocalCameraSpeed();
  37108. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37109. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37110. }
  37111. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37112. camera._localDirection.copyFromFloats(0, 0, speed);
  37113. }
  37114. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37115. camera._localDirection.copyFromFloats(speed, 0, 0);
  37116. }
  37117. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37118. camera._localDirection.copyFromFloats(0, 0, -speed);
  37119. }
  37120. if (camera.getScene().useRightHandedSystem) {
  37121. camera._localDirection.z *= -1;
  37122. }
  37123. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37124. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37125. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37126. }
  37127. }
  37128. };
  37129. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37130. return "FreeCameraKeyboardMoveInput";
  37131. };
  37132. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37133. this._keys = [];
  37134. };
  37135. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37136. return "keyboard";
  37137. };
  37138. __decorate([
  37139. BABYLON.serialize()
  37140. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37141. __decorate([
  37142. BABYLON.serialize()
  37143. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37144. __decorate([
  37145. BABYLON.serialize()
  37146. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37147. __decorate([
  37148. BABYLON.serialize()
  37149. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37150. return FreeCameraKeyboardMoveInput;
  37151. }());
  37152. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37153. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37154. })(BABYLON || (BABYLON = {}));
  37155. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37156. var BABYLON;
  37157. (function (BABYLON) {
  37158. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37159. __extends(FreeCameraInputsManager, _super);
  37160. function FreeCameraInputsManager(camera) {
  37161. return _super.call(this, camera) || this;
  37162. }
  37163. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37164. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37165. return this;
  37166. };
  37167. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37168. if (touchEnabled === void 0) { touchEnabled = true; }
  37169. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37170. return this;
  37171. };
  37172. FreeCameraInputsManager.prototype.addGamepad = function () {
  37173. this.add(new BABYLON.FreeCameraGamepadInput());
  37174. return this;
  37175. };
  37176. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37177. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37178. return this;
  37179. };
  37180. FreeCameraInputsManager.prototype.addTouch = function () {
  37181. this.add(new BABYLON.FreeCameraTouchInput());
  37182. return this;
  37183. };
  37184. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37185. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37186. return this;
  37187. };
  37188. return FreeCameraInputsManager;
  37189. }(BABYLON.CameraInputsManager));
  37190. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37191. })(BABYLON || (BABYLON = {}));
  37192. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37193. var BABYLON;
  37194. (function (BABYLON) {
  37195. var TargetCamera = /** @class */ (function (_super) {
  37196. __extends(TargetCamera, _super);
  37197. function TargetCamera(name, position, scene) {
  37198. var _this = _super.call(this, name, position, scene) || this;
  37199. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37200. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37201. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37202. _this.speed = 2.0;
  37203. _this.noRotationConstraint = false;
  37204. _this.lockedTarget = null;
  37205. _this._currentTarget = BABYLON.Vector3.Zero();
  37206. _this._viewMatrix = BABYLON.Matrix.Zero();
  37207. _this._camMatrix = BABYLON.Matrix.Zero();
  37208. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37209. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37210. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37211. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37212. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37213. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37214. _this._tempMatrix = BABYLON.Matrix.Zero();
  37215. return _this;
  37216. }
  37217. TargetCamera.prototype.getFrontPosition = function (distance) {
  37218. var direction = this.getTarget().subtract(this.position);
  37219. direction.normalize();
  37220. direction.scaleInPlace(distance);
  37221. return this.globalPosition.add(direction);
  37222. };
  37223. TargetCamera.prototype._getLockedTargetPosition = function () {
  37224. if (!this.lockedTarget) {
  37225. return null;
  37226. }
  37227. if (this.lockedTarget.absolutePosition) {
  37228. this.lockedTarget.computeWorldMatrix();
  37229. }
  37230. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37231. };
  37232. TargetCamera.prototype.storeState = function () {
  37233. this._storedPosition = this.position.clone();
  37234. this._storedRotation = this.rotation.clone();
  37235. if (this.rotationQuaternion) {
  37236. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37237. }
  37238. return _super.prototype.storeState.call(this);
  37239. };
  37240. /**
  37241. * Restored camera state. You must call storeState() first
  37242. */
  37243. TargetCamera.prototype._restoreStateValues = function () {
  37244. if (!_super.prototype._restoreStateValues.call(this)) {
  37245. return false;
  37246. }
  37247. this.position = this._storedPosition.clone();
  37248. this.rotation = this._storedRotation.clone();
  37249. if (this.rotationQuaternion) {
  37250. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37251. }
  37252. this.cameraDirection.copyFromFloats(0, 0, 0);
  37253. this.cameraRotation.copyFromFloats(0, 0);
  37254. return true;
  37255. };
  37256. // Cache
  37257. TargetCamera.prototype._initCache = function () {
  37258. _super.prototype._initCache.call(this);
  37259. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37260. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37261. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37262. };
  37263. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37264. if (!ignoreParentClass) {
  37265. _super.prototype._updateCache.call(this);
  37266. }
  37267. var lockedTargetPosition = this._getLockedTargetPosition();
  37268. if (!lockedTargetPosition) {
  37269. this._cache.lockedTarget = null;
  37270. }
  37271. else {
  37272. if (!this._cache.lockedTarget) {
  37273. this._cache.lockedTarget = lockedTargetPosition.clone();
  37274. }
  37275. else {
  37276. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37277. }
  37278. }
  37279. this._cache.rotation.copyFrom(this.rotation);
  37280. if (this.rotationQuaternion)
  37281. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37282. };
  37283. // Synchronized
  37284. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37285. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37286. return false;
  37287. }
  37288. var lockedTargetPosition = this._getLockedTargetPosition();
  37289. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37290. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37291. };
  37292. // Methods
  37293. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37294. var engine = this.getEngine();
  37295. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37296. };
  37297. // Target
  37298. TargetCamera.prototype.setTarget = function (target) {
  37299. this.upVector.normalize();
  37300. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37301. this._camMatrix.invert();
  37302. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37303. var vDir = target.subtract(this.position);
  37304. if (vDir.x >= 0.0) {
  37305. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37306. }
  37307. else {
  37308. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37309. }
  37310. this.rotation.z = 0;
  37311. if (isNaN(this.rotation.x)) {
  37312. this.rotation.x = 0;
  37313. }
  37314. if (isNaN(this.rotation.y)) {
  37315. this.rotation.y = 0;
  37316. }
  37317. if (isNaN(this.rotation.z)) {
  37318. this.rotation.z = 0;
  37319. }
  37320. if (this.rotationQuaternion) {
  37321. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37322. }
  37323. };
  37324. /**
  37325. * Return the current target position of the camera. This value is expressed in local space.
  37326. */
  37327. TargetCamera.prototype.getTarget = function () {
  37328. return this._currentTarget;
  37329. };
  37330. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37331. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37332. };
  37333. TargetCamera.prototype._updatePosition = function () {
  37334. if (this.parent) {
  37335. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37336. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37337. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37338. return;
  37339. }
  37340. this.position.addInPlace(this.cameraDirection);
  37341. };
  37342. TargetCamera.prototype._checkInputs = function () {
  37343. var needToMove = this._decideIfNeedsToMove();
  37344. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37345. // Move
  37346. if (needToMove) {
  37347. this._updatePosition();
  37348. }
  37349. // Rotate
  37350. if (needToRotate) {
  37351. this.rotation.x += this.cameraRotation.x;
  37352. this.rotation.y += this.cameraRotation.y;
  37353. //rotate, if quaternion is set and rotation was used
  37354. if (this.rotationQuaternion) {
  37355. var len = this.rotation.lengthSquared();
  37356. if (len) {
  37357. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37358. }
  37359. }
  37360. if (!this.noRotationConstraint) {
  37361. var limit = (Math.PI / 2) * 0.95;
  37362. if (this.rotation.x > limit)
  37363. this.rotation.x = limit;
  37364. if (this.rotation.x < -limit)
  37365. this.rotation.x = -limit;
  37366. }
  37367. }
  37368. // Inertia
  37369. if (needToMove) {
  37370. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37371. this.cameraDirection.x = 0;
  37372. }
  37373. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37374. this.cameraDirection.y = 0;
  37375. }
  37376. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37377. this.cameraDirection.z = 0;
  37378. }
  37379. this.cameraDirection.scaleInPlace(this.inertia);
  37380. }
  37381. if (needToRotate) {
  37382. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37383. this.cameraRotation.x = 0;
  37384. }
  37385. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37386. this.cameraRotation.y = 0;
  37387. }
  37388. this.cameraRotation.scaleInPlace(this.inertia);
  37389. }
  37390. _super.prototype._checkInputs.call(this);
  37391. };
  37392. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37393. if (this.rotationQuaternion) {
  37394. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37395. }
  37396. else {
  37397. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37398. }
  37399. //update the up vector!
  37400. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37401. };
  37402. TargetCamera.prototype._getViewMatrix = function () {
  37403. if (!this.lockedTarget) {
  37404. // Compute
  37405. this._updateCameraRotationMatrix();
  37406. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37407. // Computing target and final matrix
  37408. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37409. }
  37410. else {
  37411. var targetPosition = this._getLockedTargetPosition();
  37412. if (targetPosition) {
  37413. this._currentTarget.copyFrom(targetPosition);
  37414. }
  37415. }
  37416. if (this.getScene().useRightHandedSystem) {
  37417. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37418. }
  37419. else {
  37420. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37421. }
  37422. return this._viewMatrix;
  37423. };
  37424. /**
  37425. * @override
  37426. * Override Camera.createRigCamera
  37427. */
  37428. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37429. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37430. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37431. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37432. if (!this.rotationQuaternion) {
  37433. this.rotationQuaternion = new BABYLON.Quaternion();
  37434. }
  37435. rigCamera._cameraRigParams = {};
  37436. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37437. }
  37438. return rigCamera;
  37439. }
  37440. return null;
  37441. };
  37442. /**
  37443. * @override
  37444. * Override Camera._updateRigCameras
  37445. */
  37446. TargetCamera.prototype._updateRigCameras = function () {
  37447. var camLeft = this._rigCameras[0];
  37448. var camRight = this._rigCameras[1];
  37449. switch (this.cameraRigMode) {
  37450. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37451. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37452. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37453. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37454. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37455. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37456. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37457. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37458. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37459. camLeft.setTarget(this.getTarget());
  37460. camRight.setTarget(this.getTarget());
  37461. break;
  37462. case BABYLON.Camera.RIG_MODE_VR:
  37463. if (camLeft.rotationQuaternion) {
  37464. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37465. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37466. }
  37467. else {
  37468. camLeft.rotation.copyFrom(this.rotation);
  37469. camRight.rotation.copyFrom(this.rotation);
  37470. }
  37471. camLeft.position.copyFrom(this.position);
  37472. camRight.position.copyFrom(this.position);
  37473. break;
  37474. }
  37475. _super.prototype._updateRigCameras.call(this);
  37476. };
  37477. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37478. if (!this._rigCamTransformMatrix) {
  37479. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37480. }
  37481. var target = this.getTarget();
  37482. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37483. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37484. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37485. };
  37486. TargetCamera.prototype.getClassName = function () {
  37487. return "TargetCamera";
  37488. };
  37489. __decorate([
  37490. BABYLON.serializeAsVector3()
  37491. ], TargetCamera.prototype, "rotation", void 0);
  37492. __decorate([
  37493. BABYLON.serialize()
  37494. ], TargetCamera.prototype, "speed", void 0);
  37495. __decorate([
  37496. BABYLON.serializeAsMeshReference("lockedTargetId")
  37497. ], TargetCamera.prototype, "lockedTarget", void 0);
  37498. return TargetCamera;
  37499. }(BABYLON.Camera));
  37500. BABYLON.TargetCamera = TargetCamera;
  37501. })(BABYLON || (BABYLON = {}));
  37502. //# sourceMappingURL=babylon.targetCamera.js.map
  37503. var BABYLON;
  37504. (function (BABYLON) {
  37505. var FreeCamera = /** @class */ (function (_super) {
  37506. __extends(FreeCamera, _super);
  37507. function FreeCamera(name, position, scene) {
  37508. var _this = _super.call(this, name, position, scene) || this;
  37509. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37510. _this.checkCollisions = false;
  37511. _this.applyGravity = false;
  37512. _this._needMoveForGravity = false;
  37513. _this._oldPosition = BABYLON.Vector3.Zero();
  37514. _this._diffPosition = BABYLON.Vector3.Zero();
  37515. _this._newPosition = BABYLON.Vector3.Zero();
  37516. // Collisions
  37517. _this._collisionMask = -1;
  37518. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37519. if (collidedMesh === void 0) { collidedMesh = null; }
  37520. //TODO move this to the collision coordinator!
  37521. if (_this.getScene().workerCollisions)
  37522. newPosition.multiplyInPlace(_this._collider.radius);
  37523. var updatePosition = function (newPos) {
  37524. _this._newPosition.copyFrom(newPos);
  37525. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37526. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37527. _this.position.addInPlace(_this._diffPosition);
  37528. if (_this.onCollide && collidedMesh) {
  37529. _this.onCollide(collidedMesh);
  37530. }
  37531. }
  37532. };
  37533. updatePosition(newPosition);
  37534. };
  37535. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37536. _this.inputs.addKeyboard().addMouse();
  37537. return _this;
  37538. }
  37539. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37540. //-- begin properties for backward compatibility for inputs
  37541. get: function () {
  37542. var mouse = this.inputs.attached["mouse"];
  37543. if (mouse)
  37544. return mouse.angularSensibility;
  37545. return 0;
  37546. },
  37547. set: function (value) {
  37548. var mouse = this.inputs.attached["mouse"];
  37549. if (mouse)
  37550. mouse.angularSensibility = value;
  37551. },
  37552. enumerable: true,
  37553. configurable: true
  37554. });
  37555. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37556. get: function () {
  37557. var keyboard = this.inputs.attached["keyboard"];
  37558. if (keyboard)
  37559. return keyboard.keysUp;
  37560. return [];
  37561. },
  37562. set: function (value) {
  37563. var keyboard = this.inputs.attached["keyboard"];
  37564. if (keyboard)
  37565. keyboard.keysUp = value;
  37566. },
  37567. enumerable: true,
  37568. configurable: true
  37569. });
  37570. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37571. get: function () {
  37572. var keyboard = this.inputs.attached["keyboard"];
  37573. if (keyboard)
  37574. return keyboard.keysDown;
  37575. return [];
  37576. },
  37577. set: function (value) {
  37578. var keyboard = this.inputs.attached["keyboard"];
  37579. if (keyboard)
  37580. keyboard.keysDown = value;
  37581. },
  37582. enumerable: true,
  37583. configurable: true
  37584. });
  37585. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37586. get: function () {
  37587. var keyboard = this.inputs.attached["keyboard"];
  37588. if (keyboard)
  37589. return keyboard.keysLeft;
  37590. return [];
  37591. },
  37592. set: function (value) {
  37593. var keyboard = this.inputs.attached["keyboard"];
  37594. if (keyboard)
  37595. keyboard.keysLeft = value;
  37596. },
  37597. enumerable: true,
  37598. configurable: true
  37599. });
  37600. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37601. get: function () {
  37602. var keyboard = this.inputs.attached["keyboard"];
  37603. if (keyboard)
  37604. return keyboard.keysRight;
  37605. return [];
  37606. },
  37607. set: function (value) {
  37608. var keyboard = this.inputs.attached["keyboard"];
  37609. if (keyboard)
  37610. keyboard.keysRight = value;
  37611. },
  37612. enumerable: true,
  37613. configurable: true
  37614. });
  37615. // Controls
  37616. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37617. this.inputs.attachElement(element, noPreventDefault);
  37618. };
  37619. FreeCamera.prototype.detachControl = function (element) {
  37620. this.inputs.detachElement(element);
  37621. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37622. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37623. };
  37624. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37625. get: function () {
  37626. return this._collisionMask;
  37627. },
  37628. set: function (mask) {
  37629. this._collisionMask = !isNaN(mask) ? mask : -1;
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37635. var globalPosition;
  37636. if (this.parent) {
  37637. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37638. }
  37639. else {
  37640. globalPosition = this.position;
  37641. }
  37642. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37643. if (!this._collider) {
  37644. this._collider = new BABYLON.Collider();
  37645. }
  37646. this._collider.radius = this.ellipsoid;
  37647. this._collider.collisionMask = this._collisionMask;
  37648. //no need for clone, as long as gravity is not on.
  37649. var actualDisplacement = displacement;
  37650. //add gravity to the direction to prevent the dual-collision checking
  37651. if (this.applyGravity) {
  37652. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37653. actualDisplacement = displacement.add(this.getScene().gravity);
  37654. }
  37655. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37656. };
  37657. FreeCamera.prototype._checkInputs = function () {
  37658. if (!this._localDirection) {
  37659. this._localDirection = BABYLON.Vector3.Zero();
  37660. this._transformedDirection = BABYLON.Vector3.Zero();
  37661. }
  37662. this.inputs.checkInputs();
  37663. _super.prototype._checkInputs.call(this);
  37664. };
  37665. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37666. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37667. };
  37668. FreeCamera.prototype._updatePosition = function () {
  37669. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37670. this._collideWithWorld(this.cameraDirection);
  37671. }
  37672. else {
  37673. _super.prototype._updatePosition.call(this);
  37674. }
  37675. };
  37676. FreeCamera.prototype.dispose = function () {
  37677. this.inputs.clear();
  37678. _super.prototype.dispose.call(this);
  37679. };
  37680. FreeCamera.prototype.getClassName = function () {
  37681. return "FreeCamera";
  37682. };
  37683. __decorate([
  37684. BABYLON.serializeAsVector3()
  37685. ], FreeCamera.prototype, "ellipsoid", void 0);
  37686. __decorate([
  37687. BABYLON.serialize()
  37688. ], FreeCamera.prototype, "checkCollisions", void 0);
  37689. __decorate([
  37690. BABYLON.serialize()
  37691. ], FreeCamera.prototype, "applyGravity", void 0);
  37692. return FreeCamera;
  37693. }(BABYLON.TargetCamera));
  37694. BABYLON.FreeCamera = FreeCamera;
  37695. })(BABYLON || (BABYLON = {}));
  37696. //# sourceMappingURL=babylon.freeCamera.js.map
  37697. var BABYLON;
  37698. (function (BABYLON) {
  37699. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37700. function ArcRotateCameraKeyboardMoveInput() {
  37701. this._keys = new Array();
  37702. this.keysUp = [38];
  37703. this.keysDown = [40];
  37704. this.keysLeft = [37];
  37705. this.keysRight = [39];
  37706. this.keysReset = [220];
  37707. this.panningSensibility = 50.0;
  37708. this.zoomingSensibility = 25.0;
  37709. this.useAltToZoom = true;
  37710. }
  37711. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37712. var _this = this;
  37713. if (this._onCanvasBlurObserver) {
  37714. return;
  37715. }
  37716. this._scene = this.camera.getScene();
  37717. this._engine = this._scene.getEngine();
  37718. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37719. _this._keys = [];
  37720. });
  37721. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37722. var evt = info.event;
  37723. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37724. _this._ctrlPressed = evt.ctrlKey;
  37725. _this._altPressed = evt.altKey;
  37726. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37727. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37728. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37729. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37730. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37731. var index = _this._keys.indexOf(evt.keyCode);
  37732. if (index === -1) {
  37733. _this._keys.push(evt.keyCode);
  37734. }
  37735. if (evt.preventDefault) {
  37736. if (!noPreventDefault) {
  37737. evt.preventDefault();
  37738. }
  37739. }
  37740. }
  37741. }
  37742. else {
  37743. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37744. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37745. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37746. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37747. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37748. var index = _this._keys.indexOf(evt.keyCode);
  37749. if (index >= 0) {
  37750. _this._keys.splice(index, 1);
  37751. }
  37752. if (evt.preventDefault) {
  37753. if (!noPreventDefault) {
  37754. evt.preventDefault();
  37755. }
  37756. }
  37757. }
  37758. }
  37759. });
  37760. };
  37761. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37762. if (this._scene) {
  37763. if (this._onKeyboardObserver) {
  37764. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37765. }
  37766. if (this._onCanvasBlurObserver) {
  37767. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37768. }
  37769. this._onKeyboardObserver = null;
  37770. this._onCanvasBlurObserver = null;
  37771. }
  37772. this._keys = [];
  37773. };
  37774. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37775. if (this._onKeyboardObserver) {
  37776. var camera = this.camera;
  37777. for (var index = 0; index < this._keys.length; index++) {
  37778. var keyCode = this._keys[index];
  37779. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37780. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37781. camera.inertialPanningX -= 1 / this.panningSensibility;
  37782. }
  37783. else {
  37784. camera.inertialAlphaOffset -= 0.01;
  37785. }
  37786. }
  37787. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37788. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37789. camera.inertialPanningY += 1 / this.panningSensibility;
  37790. }
  37791. else if (this._altPressed && this.useAltToZoom) {
  37792. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  37793. }
  37794. else {
  37795. camera.inertialBetaOffset -= 0.01;
  37796. }
  37797. }
  37798. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37799. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37800. camera.inertialPanningX += 1 / this.panningSensibility;
  37801. }
  37802. else {
  37803. camera.inertialAlphaOffset += 0.01;
  37804. }
  37805. }
  37806. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37807. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37808. camera.inertialPanningY -= 1 / this.panningSensibility;
  37809. }
  37810. else if (this._altPressed && this.useAltToZoom) {
  37811. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  37812. }
  37813. else {
  37814. camera.inertialBetaOffset += 0.01;
  37815. }
  37816. }
  37817. else if (this.keysReset.indexOf(keyCode) !== -1) {
  37818. camera.restoreState();
  37819. }
  37820. }
  37821. }
  37822. };
  37823. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  37824. return "ArcRotateCameraKeyboardMoveInput";
  37825. };
  37826. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37827. return "keyboard";
  37828. };
  37829. __decorate([
  37830. BABYLON.serialize()
  37831. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37832. __decorate([
  37833. BABYLON.serialize()
  37834. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37835. __decorate([
  37836. BABYLON.serialize()
  37837. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37838. __decorate([
  37839. BABYLON.serialize()
  37840. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37841. __decorate([
  37842. BABYLON.serialize()
  37843. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  37844. __decorate([
  37845. BABYLON.serialize()
  37846. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  37847. __decorate([
  37848. BABYLON.serialize()
  37849. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  37850. __decorate([
  37851. BABYLON.serialize()
  37852. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  37853. return ArcRotateCameraKeyboardMoveInput;
  37854. }());
  37855. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  37856. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  37857. })(BABYLON || (BABYLON = {}));
  37858. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  37859. var BABYLON;
  37860. (function (BABYLON) {
  37861. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  37862. function ArcRotateCameraMouseWheelInput() {
  37863. this.wheelPrecision = 3.0;
  37864. /**
  37865. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  37866. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  37867. */
  37868. this.wheelDeltaPercentage = 0;
  37869. }
  37870. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  37871. var _this = this;
  37872. this._wheel = function (p, s) {
  37873. //sanity check - this should be a PointerWheel event.
  37874. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  37875. return;
  37876. var event = p.event;
  37877. var delta = 0;
  37878. if (event.wheelDelta) {
  37879. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  37880. }
  37881. else if (event.detail) {
  37882. delta = -event.detail / _this.wheelPrecision;
  37883. }
  37884. if (delta)
  37885. _this.camera.inertialRadiusOffset += delta;
  37886. if (event.preventDefault) {
  37887. if (!noPreventDefault) {
  37888. event.preventDefault();
  37889. }
  37890. }
  37891. };
  37892. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  37893. };
  37894. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  37895. if (this._observer && element) {
  37896. this.camera.getScene().onPointerObservable.remove(this._observer);
  37897. this._observer = null;
  37898. this._wheel = null;
  37899. }
  37900. };
  37901. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  37902. return "ArcRotateCameraMouseWheelInput";
  37903. };
  37904. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  37905. return "mousewheel";
  37906. };
  37907. __decorate([
  37908. BABYLON.serialize()
  37909. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  37910. __decorate([
  37911. BABYLON.serialize()
  37912. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  37913. return ArcRotateCameraMouseWheelInput;
  37914. }());
  37915. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  37916. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  37917. })(BABYLON || (BABYLON = {}));
  37918. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  37919. var BABYLON;
  37920. (function (BABYLON) {
  37921. var ArcRotateCameraPointersInput = /** @class */ (function () {
  37922. function ArcRotateCameraPointersInput() {
  37923. this.buttons = [0, 1, 2];
  37924. this.angularSensibilityX = 1000.0;
  37925. this.angularSensibilityY = 1000.0;
  37926. this.pinchPrecision = 12.0;
  37927. /**
  37928. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  37929. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  37930. */
  37931. this.pinchDeltaPercentage = 0;
  37932. this.panningSensibility = 1000.0;
  37933. this.multiTouchPanning = true;
  37934. this.multiTouchPanAndZoom = true;
  37935. this._isPanClick = false;
  37936. this.pinchInwards = true;
  37937. }
  37938. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  37939. var _this = this;
  37940. var engine = this.camera.getEngine();
  37941. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  37942. var pointA = null;
  37943. var pointB = null;
  37944. var previousPinchSquaredDistance = 0;
  37945. var initialDistance = 0;
  37946. var twoFingerActivityCount = 0;
  37947. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  37948. this._pointerInput = function (p, s) {
  37949. var evt = p.event;
  37950. if (engine.isInVRExclusivePointerMode) {
  37951. return;
  37952. }
  37953. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37954. return;
  37955. }
  37956. var srcElement = (evt.srcElement || evt.target);
  37957. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37958. try {
  37959. srcElement.setPointerCapture(evt.pointerId);
  37960. }
  37961. catch (e) {
  37962. //Nothing to do with the error. Execution will continue.
  37963. }
  37964. // Manage panning with pan button click
  37965. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  37966. // manage pointers
  37967. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  37968. if (pointA === null) {
  37969. pointA = cacheSoloPointer;
  37970. }
  37971. else if (pointB === null) {
  37972. pointB = cacheSoloPointer;
  37973. }
  37974. if (!noPreventDefault) {
  37975. evt.preventDefault();
  37976. element.focus();
  37977. }
  37978. }
  37979. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  37980. _this.camera.restoreState();
  37981. }
  37982. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37983. try {
  37984. srcElement.releasePointerCapture(evt.pointerId);
  37985. }
  37986. catch (e) {
  37987. //Nothing to do with the error.
  37988. }
  37989. cacheSoloPointer = null;
  37990. previousPinchSquaredDistance = 0;
  37991. previousMultiTouchPanPosition.isPaning = false;
  37992. previousMultiTouchPanPosition.isPinching = false;
  37993. twoFingerActivityCount = 0;
  37994. initialDistance = 0;
  37995. if (p.event.pointerType !== "touch") {
  37996. pointB = null; // Mouse and pen are mono pointer
  37997. }
  37998. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  37999. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38000. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38001. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38002. if (engine.badOS) {
  38003. pointA = pointB = null;
  38004. }
  38005. else {
  38006. //only remove the impacted pointer in case of multitouch allowing on most
  38007. //platforms switching from rotate to zoom and pan seamlessly.
  38008. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38009. pointA = pointB;
  38010. pointB = null;
  38011. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38012. }
  38013. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38014. pointB = null;
  38015. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38016. }
  38017. else {
  38018. pointA = pointB = null;
  38019. }
  38020. }
  38021. if (!noPreventDefault) {
  38022. evt.preventDefault();
  38023. }
  38024. }
  38025. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38026. if (!noPreventDefault) {
  38027. evt.preventDefault();
  38028. }
  38029. // One button down
  38030. if (pointA && pointB === null && cacheSoloPointer) {
  38031. if (_this.panningSensibility !== 0 &&
  38032. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38033. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38034. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38035. }
  38036. else {
  38037. var offsetX = evt.clientX - cacheSoloPointer.x;
  38038. var offsetY = evt.clientY - cacheSoloPointer.y;
  38039. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38040. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38041. }
  38042. cacheSoloPointer.x = evt.clientX;
  38043. cacheSoloPointer.y = evt.clientY;
  38044. }
  38045. else if (pointA && pointB) {
  38046. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38047. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38048. ed.x = evt.clientX;
  38049. ed.y = evt.clientY;
  38050. var direction = _this.pinchInwards ? 1 : -1;
  38051. var distX = pointA.x - pointB.x;
  38052. var distY = pointA.y - pointB.y;
  38053. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38054. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38055. if (previousPinchSquaredDistance === 0) {
  38056. initialDistance = pinchDistance;
  38057. previousPinchSquaredDistance = pinchSquaredDistance;
  38058. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38059. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38060. return;
  38061. }
  38062. if (_this.multiTouchPanAndZoom) {
  38063. if (_this.pinchDeltaPercentage) {
  38064. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38065. }
  38066. else {
  38067. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38068. (_this.pinchPrecision *
  38069. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38070. direction);
  38071. }
  38072. if (_this.panningSensibility !== 0) {
  38073. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38074. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38075. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38076. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38077. previousMultiTouchPanPosition.x = pointersCenterX;
  38078. previousMultiTouchPanPosition.y = pointersCenterY;
  38079. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38080. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38081. }
  38082. }
  38083. else {
  38084. twoFingerActivityCount++;
  38085. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38086. if (_this.pinchDeltaPercentage) {
  38087. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38088. }
  38089. else {
  38090. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38091. (_this.pinchPrecision *
  38092. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38093. direction);
  38094. }
  38095. previousMultiTouchPanPosition.isPaning = false;
  38096. previousMultiTouchPanPosition.isPinching = true;
  38097. }
  38098. else {
  38099. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38100. if (!previousMultiTouchPanPosition.isPaning) {
  38101. previousMultiTouchPanPosition.isPaning = true;
  38102. previousMultiTouchPanPosition.isPinching = false;
  38103. previousMultiTouchPanPosition.x = ed.x;
  38104. previousMultiTouchPanPosition.y = ed.y;
  38105. return;
  38106. }
  38107. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38108. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38109. }
  38110. }
  38111. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38112. previousMultiTouchPanPosition.x = ed.x;
  38113. previousMultiTouchPanPosition.y = ed.y;
  38114. }
  38115. }
  38116. previousPinchSquaredDistance = pinchSquaredDistance;
  38117. }
  38118. }
  38119. };
  38120. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38121. this._onContextMenu = function (evt) {
  38122. evt.preventDefault();
  38123. };
  38124. if (!this.camera._useCtrlForPanning) {
  38125. element.addEventListener("contextmenu", this._onContextMenu, false);
  38126. }
  38127. this._onLostFocus = function () {
  38128. //this._keys = [];
  38129. pointA = pointB = null;
  38130. previousPinchSquaredDistance = 0;
  38131. previousMultiTouchPanPosition.isPaning = false;
  38132. previousMultiTouchPanPosition.isPinching = false;
  38133. twoFingerActivityCount = 0;
  38134. cacheSoloPointer = null;
  38135. initialDistance = 0;
  38136. };
  38137. this._onMouseMove = function (evt) {
  38138. if (!engine.isPointerLock) {
  38139. return;
  38140. }
  38141. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38142. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38143. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38144. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38145. if (!noPreventDefault) {
  38146. evt.preventDefault();
  38147. }
  38148. };
  38149. this._onGestureStart = function (e) {
  38150. if (window.MSGesture === undefined) {
  38151. return;
  38152. }
  38153. if (!_this._MSGestureHandler) {
  38154. _this._MSGestureHandler = new MSGesture();
  38155. _this._MSGestureHandler.target = element;
  38156. }
  38157. _this._MSGestureHandler.addPointer(e.pointerId);
  38158. };
  38159. this._onGesture = function (e) {
  38160. _this.camera.radius *= e.scale;
  38161. if (e.preventDefault) {
  38162. if (!noPreventDefault) {
  38163. e.stopPropagation();
  38164. e.preventDefault();
  38165. }
  38166. }
  38167. };
  38168. element.addEventListener("mousemove", this._onMouseMove, false);
  38169. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38170. element.addEventListener("MSGestureChange", this._onGesture, false);
  38171. BABYLON.Tools.RegisterTopRootEvents([
  38172. { name: "blur", handler: this._onLostFocus }
  38173. ]);
  38174. };
  38175. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38176. if (this._onLostFocus) {
  38177. BABYLON.Tools.UnregisterTopRootEvents([
  38178. { name: "blur", handler: this._onLostFocus }
  38179. ]);
  38180. }
  38181. if (element && this._observer) {
  38182. this.camera.getScene().onPointerObservable.remove(this._observer);
  38183. this._observer = null;
  38184. if (this._onContextMenu) {
  38185. element.removeEventListener("contextmenu", this._onContextMenu);
  38186. }
  38187. if (this._onMouseMove) {
  38188. element.removeEventListener("mousemove", this._onMouseMove);
  38189. }
  38190. if (this._onGestureStart) {
  38191. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38192. }
  38193. if (this._onGesture) {
  38194. element.removeEventListener("MSGestureChange", this._onGesture);
  38195. }
  38196. this._isPanClick = false;
  38197. this.pinchInwards = true;
  38198. this._onMouseMove = null;
  38199. this._onGestureStart = null;
  38200. this._onGesture = null;
  38201. this._MSGestureHandler = null;
  38202. this._onLostFocus = null;
  38203. this._onContextMenu = null;
  38204. }
  38205. };
  38206. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38207. return "ArcRotateCameraPointersInput";
  38208. };
  38209. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38210. return "pointers";
  38211. };
  38212. __decorate([
  38213. BABYLON.serialize()
  38214. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38215. __decorate([
  38216. BABYLON.serialize()
  38217. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38218. __decorate([
  38219. BABYLON.serialize()
  38220. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38221. __decorate([
  38222. BABYLON.serialize()
  38223. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38224. __decorate([
  38225. BABYLON.serialize()
  38226. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38227. __decorate([
  38228. BABYLON.serialize()
  38229. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38230. __decorate([
  38231. BABYLON.serialize()
  38232. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38233. __decorate([
  38234. BABYLON.serialize()
  38235. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38236. return ArcRotateCameraPointersInput;
  38237. }());
  38238. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38239. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38240. })(BABYLON || (BABYLON = {}));
  38241. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38242. var BABYLON;
  38243. (function (BABYLON) {
  38244. var ArcRotateCamera = /** @class */ (function (_super) {
  38245. __extends(ArcRotateCamera, _super);
  38246. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38247. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38248. _this.inertialAlphaOffset = 0;
  38249. _this.inertialBetaOffset = 0;
  38250. _this.inertialRadiusOffset = 0;
  38251. _this.lowerAlphaLimit = null;
  38252. _this.upperAlphaLimit = null;
  38253. _this.lowerBetaLimit = 0.01;
  38254. _this.upperBetaLimit = Math.PI;
  38255. _this.lowerRadiusLimit = null;
  38256. _this.upperRadiusLimit = null;
  38257. _this.inertialPanningX = 0;
  38258. _this.inertialPanningY = 0;
  38259. _this.pinchToPanMaxDistance = 20;
  38260. _this.panningDistanceLimit = null;
  38261. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38262. _this.panningInertia = 0.9;
  38263. //-- end properties for backward compatibility for inputs
  38264. _this.zoomOnFactor = 1;
  38265. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38266. _this.allowUpsideDown = true;
  38267. _this._viewMatrix = new BABYLON.Matrix();
  38268. // Panning
  38269. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38270. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38271. _this.checkCollisions = false;
  38272. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38273. _this._previousPosition = BABYLON.Vector3.Zero();
  38274. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38275. _this._newPosition = BABYLON.Vector3.Zero();
  38276. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38277. if (collidedMesh === void 0) { collidedMesh = null; }
  38278. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38279. newPosition.multiplyInPlace(_this._collider.radius);
  38280. }
  38281. if (!collidedMesh) {
  38282. _this._previousPosition.copyFrom(_this.position);
  38283. }
  38284. else {
  38285. _this.setPosition(newPosition);
  38286. if (_this.onCollide) {
  38287. _this.onCollide(collidedMesh);
  38288. }
  38289. }
  38290. // Recompute because of constraints
  38291. var cosa = Math.cos(_this.alpha);
  38292. var sina = Math.sin(_this.alpha);
  38293. var cosb = Math.cos(_this.beta);
  38294. var sinb = Math.sin(_this.beta);
  38295. if (sinb === 0) {
  38296. sinb = 0.0001;
  38297. }
  38298. var target = _this._getTargetPosition();
  38299. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38300. _this.position.copyFrom(_this._newPosition);
  38301. var up = _this.upVector;
  38302. if (_this.allowUpsideDown && _this.beta < 0) {
  38303. up = up.clone();
  38304. up = up.negate();
  38305. }
  38306. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38307. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38308. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38309. _this._collisionTriggered = false;
  38310. };
  38311. _this._target = BABYLON.Vector3.Zero();
  38312. if (target) {
  38313. _this.setTarget(target);
  38314. }
  38315. _this.alpha = alpha;
  38316. _this.beta = beta;
  38317. _this.radius = radius;
  38318. _this.getViewMatrix();
  38319. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38320. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38321. return _this;
  38322. }
  38323. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38324. get: function () {
  38325. return this._target;
  38326. },
  38327. set: function (value) {
  38328. this.setTarget(value);
  38329. },
  38330. enumerable: true,
  38331. configurable: true
  38332. });
  38333. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38334. //-- begin properties for backward compatibility for inputs
  38335. get: function () {
  38336. var pointers = this.inputs.attached["pointers"];
  38337. if (pointers)
  38338. return pointers.angularSensibilityX;
  38339. return 0;
  38340. },
  38341. set: function (value) {
  38342. var pointers = this.inputs.attached["pointers"];
  38343. if (pointers) {
  38344. pointers.angularSensibilityX = value;
  38345. }
  38346. },
  38347. enumerable: true,
  38348. configurable: true
  38349. });
  38350. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38351. get: function () {
  38352. var pointers = this.inputs.attached["pointers"];
  38353. if (pointers)
  38354. return pointers.angularSensibilityY;
  38355. return 0;
  38356. },
  38357. set: function (value) {
  38358. var pointers = this.inputs.attached["pointers"];
  38359. if (pointers) {
  38360. pointers.angularSensibilityY = value;
  38361. }
  38362. },
  38363. enumerable: true,
  38364. configurable: true
  38365. });
  38366. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38367. get: function () {
  38368. var pointers = this.inputs.attached["pointers"];
  38369. if (pointers)
  38370. return pointers.pinchPrecision;
  38371. return 0;
  38372. },
  38373. set: function (value) {
  38374. var pointers = this.inputs.attached["pointers"];
  38375. if (pointers) {
  38376. pointers.pinchPrecision = value;
  38377. }
  38378. },
  38379. enumerable: true,
  38380. configurable: true
  38381. });
  38382. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38383. get: function () {
  38384. var pointers = this.inputs.attached["pointers"];
  38385. if (pointers)
  38386. return pointers.pinchDeltaPercentage;
  38387. return 0;
  38388. },
  38389. set: function (value) {
  38390. var pointers = this.inputs.attached["pointers"];
  38391. if (pointers) {
  38392. pointers.pinchDeltaPercentage = value;
  38393. }
  38394. },
  38395. enumerable: true,
  38396. configurable: true
  38397. });
  38398. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38399. get: function () {
  38400. var pointers = this.inputs.attached["pointers"];
  38401. if (pointers)
  38402. return pointers.panningSensibility;
  38403. return 0;
  38404. },
  38405. set: function (value) {
  38406. var pointers = this.inputs.attached["pointers"];
  38407. if (pointers) {
  38408. pointers.panningSensibility = value;
  38409. }
  38410. },
  38411. enumerable: true,
  38412. configurable: true
  38413. });
  38414. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38415. get: function () {
  38416. var keyboard = this.inputs.attached["keyboard"];
  38417. if (keyboard)
  38418. return keyboard.keysUp;
  38419. return [];
  38420. },
  38421. set: function (value) {
  38422. var keyboard = this.inputs.attached["keyboard"];
  38423. if (keyboard)
  38424. keyboard.keysUp = value;
  38425. },
  38426. enumerable: true,
  38427. configurable: true
  38428. });
  38429. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38430. get: function () {
  38431. var keyboard = this.inputs.attached["keyboard"];
  38432. if (keyboard)
  38433. return keyboard.keysDown;
  38434. return [];
  38435. },
  38436. set: function (value) {
  38437. var keyboard = this.inputs.attached["keyboard"];
  38438. if (keyboard)
  38439. keyboard.keysDown = value;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38445. get: function () {
  38446. var keyboard = this.inputs.attached["keyboard"];
  38447. if (keyboard)
  38448. return keyboard.keysLeft;
  38449. return [];
  38450. },
  38451. set: function (value) {
  38452. var keyboard = this.inputs.attached["keyboard"];
  38453. if (keyboard)
  38454. keyboard.keysLeft = value;
  38455. },
  38456. enumerable: true,
  38457. configurable: true
  38458. });
  38459. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38460. get: function () {
  38461. var keyboard = this.inputs.attached["keyboard"];
  38462. if (keyboard)
  38463. return keyboard.keysRight;
  38464. return [];
  38465. },
  38466. set: function (value) {
  38467. var keyboard = this.inputs.attached["keyboard"];
  38468. if (keyboard)
  38469. keyboard.keysRight = value;
  38470. },
  38471. enumerable: true,
  38472. configurable: true
  38473. });
  38474. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38475. get: function () {
  38476. var mousewheel = this.inputs.attached["mousewheel"];
  38477. if (mousewheel)
  38478. return mousewheel.wheelPrecision;
  38479. return 0;
  38480. },
  38481. set: function (value) {
  38482. var mousewheel = this.inputs.attached["mousewheel"];
  38483. if (mousewheel)
  38484. mousewheel.wheelPrecision = value;
  38485. },
  38486. enumerable: true,
  38487. configurable: true
  38488. });
  38489. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38490. get: function () {
  38491. var mousewheel = this.inputs.attached["mousewheel"];
  38492. if (mousewheel)
  38493. return mousewheel.wheelDeltaPercentage;
  38494. return 0;
  38495. },
  38496. set: function (value) {
  38497. var mousewheel = this.inputs.attached["mousewheel"];
  38498. if (mousewheel)
  38499. mousewheel.wheelDeltaPercentage = value;
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38505. get: function () {
  38506. return this._bouncingBehavior;
  38507. },
  38508. enumerable: true,
  38509. configurable: true
  38510. });
  38511. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38512. get: function () {
  38513. return this._bouncingBehavior != null;
  38514. },
  38515. set: function (value) {
  38516. if (value === this.useBouncingBehavior) {
  38517. return;
  38518. }
  38519. if (value) {
  38520. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38521. this.addBehavior(this._bouncingBehavior);
  38522. }
  38523. else if (this._bouncingBehavior) {
  38524. this.removeBehavior(this._bouncingBehavior);
  38525. this._bouncingBehavior = null;
  38526. }
  38527. },
  38528. enumerable: true,
  38529. configurable: true
  38530. });
  38531. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38532. get: function () {
  38533. return this._framingBehavior;
  38534. },
  38535. enumerable: true,
  38536. configurable: true
  38537. });
  38538. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38539. get: function () {
  38540. return this._framingBehavior != null;
  38541. },
  38542. set: function (value) {
  38543. if (value === this.useFramingBehavior) {
  38544. return;
  38545. }
  38546. if (value) {
  38547. this._framingBehavior = new BABYLON.FramingBehavior();
  38548. this.addBehavior(this._framingBehavior);
  38549. }
  38550. else if (this._framingBehavior) {
  38551. this.removeBehavior(this._framingBehavior);
  38552. this._framingBehavior = null;
  38553. }
  38554. },
  38555. enumerable: true,
  38556. configurable: true
  38557. });
  38558. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38559. get: function () {
  38560. return this._autoRotationBehavior;
  38561. },
  38562. enumerable: true,
  38563. configurable: true
  38564. });
  38565. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38566. get: function () {
  38567. return this._autoRotationBehavior != null;
  38568. },
  38569. set: function (value) {
  38570. if (value === this.useAutoRotationBehavior) {
  38571. return;
  38572. }
  38573. if (value) {
  38574. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38575. this.addBehavior(this._autoRotationBehavior);
  38576. }
  38577. else if (this._autoRotationBehavior) {
  38578. this.removeBehavior(this._autoRotationBehavior);
  38579. this._autoRotationBehavior = null;
  38580. }
  38581. },
  38582. enumerable: true,
  38583. configurable: true
  38584. });
  38585. // Cache
  38586. ArcRotateCamera.prototype._initCache = function () {
  38587. _super.prototype._initCache.call(this);
  38588. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38589. this._cache.alpha = undefined;
  38590. this._cache.beta = undefined;
  38591. this._cache.radius = undefined;
  38592. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38593. };
  38594. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38595. if (!ignoreParentClass) {
  38596. _super.prototype._updateCache.call(this);
  38597. }
  38598. this._cache._target.copyFrom(this._getTargetPosition());
  38599. this._cache.alpha = this.alpha;
  38600. this._cache.beta = this.beta;
  38601. this._cache.radius = this.radius;
  38602. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38603. };
  38604. ArcRotateCamera.prototype._getTargetPosition = function () {
  38605. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38606. var pos = this._targetHost.getAbsolutePosition();
  38607. if (this._targetBoundingCenter) {
  38608. pos.addToRef(this._targetBoundingCenter, this._target);
  38609. }
  38610. else {
  38611. this._target.copyFrom(pos);
  38612. }
  38613. }
  38614. var lockedTargetPosition = this._getLockedTargetPosition();
  38615. if (lockedTargetPosition) {
  38616. return lockedTargetPosition;
  38617. }
  38618. return this._target;
  38619. };
  38620. ArcRotateCamera.prototype.storeState = function () {
  38621. this._storedAlpha = this.alpha;
  38622. this._storedBeta = this.beta;
  38623. this._storedRadius = this.radius;
  38624. this._storedTarget = this._getTargetPosition().clone();
  38625. return _super.prototype.storeState.call(this);
  38626. };
  38627. /**
  38628. * Restored camera state. You must call storeState() first
  38629. */
  38630. ArcRotateCamera.prototype._restoreStateValues = function () {
  38631. if (!_super.prototype._restoreStateValues.call(this)) {
  38632. return false;
  38633. }
  38634. this.alpha = this._storedAlpha;
  38635. this.beta = this._storedBeta;
  38636. this.radius = this._storedRadius;
  38637. this.setTarget(this._storedTarget.clone());
  38638. this.inertialAlphaOffset = 0;
  38639. this.inertialBetaOffset = 0;
  38640. this.inertialRadiusOffset = 0;
  38641. this.inertialPanningX = 0;
  38642. this.inertialPanningY = 0;
  38643. return true;
  38644. };
  38645. // Synchronized
  38646. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38647. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38648. return false;
  38649. return this._cache._target.equals(this._getTargetPosition())
  38650. && this._cache.alpha === this.alpha
  38651. && this._cache.beta === this.beta
  38652. && this._cache.radius === this.radius
  38653. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38654. };
  38655. // Methods
  38656. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38657. var _this = this;
  38658. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38659. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38660. this._useCtrlForPanning = useCtrlForPanning;
  38661. this._panningMouseButton = panningMouseButton;
  38662. this.inputs.attachElement(element, noPreventDefault);
  38663. this._reset = function () {
  38664. _this.inertialAlphaOffset = 0;
  38665. _this.inertialBetaOffset = 0;
  38666. _this.inertialRadiusOffset = 0;
  38667. _this.inertialPanningX = 0;
  38668. _this.inertialPanningY = 0;
  38669. };
  38670. };
  38671. ArcRotateCamera.prototype.detachControl = function (element) {
  38672. this.inputs.detachElement(element);
  38673. if (this._reset) {
  38674. this._reset();
  38675. }
  38676. };
  38677. ArcRotateCamera.prototype._checkInputs = function () {
  38678. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38679. if (this._collisionTriggered) {
  38680. return;
  38681. }
  38682. this.inputs.checkInputs();
  38683. // Inertia
  38684. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38685. if (this.getScene().useRightHandedSystem) {
  38686. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38687. }
  38688. else {
  38689. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38690. }
  38691. this.beta += this.inertialBetaOffset;
  38692. this.radius -= this.inertialRadiusOffset;
  38693. this.inertialAlphaOffset *= this.inertia;
  38694. this.inertialBetaOffset *= this.inertia;
  38695. this.inertialRadiusOffset *= this.inertia;
  38696. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38697. this.inertialAlphaOffset = 0;
  38698. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38699. this.inertialBetaOffset = 0;
  38700. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38701. this.inertialRadiusOffset = 0;
  38702. }
  38703. // Panning inertia
  38704. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38705. if (!this._localDirection) {
  38706. this._localDirection = BABYLON.Vector3.Zero();
  38707. this._transformedDirection = BABYLON.Vector3.Zero();
  38708. }
  38709. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38710. this._localDirection.multiplyInPlace(this.panningAxis);
  38711. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38712. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38713. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38714. if (!this.panningAxis.y) {
  38715. this._transformedDirection.y = 0;
  38716. }
  38717. if (!this._targetHost) {
  38718. if (this.panningDistanceLimit) {
  38719. this._transformedDirection.addInPlace(this._target);
  38720. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38721. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38722. this._target.copyFrom(this._transformedDirection);
  38723. }
  38724. }
  38725. else {
  38726. this._target.addInPlace(this._transformedDirection);
  38727. }
  38728. }
  38729. this.inertialPanningX *= this.panningInertia;
  38730. this.inertialPanningY *= this.panningInertia;
  38731. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38732. this.inertialPanningX = 0;
  38733. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38734. this.inertialPanningY = 0;
  38735. }
  38736. // Limits
  38737. this._checkLimits();
  38738. _super.prototype._checkInputs.call(this);
  38739. };
  38740. ArcRotateCamera.prototype._checkLimits = function () {
  38741. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38742. if (this.allowUpsideDown && this.beta > Math.PI) {
  38743. this.beta = this.beta - (2 * Math.PI);
  38744. }
  38745. }
  38746. else {
  38747. if (this.beta < this.lowerBetaLimit) {
  38748. this.beta = this.lowerBetaLimit;
  38749. }
  38750. }
  38751. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38752. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38753. this.beta = this.beta + (2 * Math.PI);
  38754. }
  38755. }
  38756. else {
  38757. if (this.beta > this.upperBetaLimit) {
  38758. this.beta = this.upperBetaLimit;
  38759. }
  38760. }
  38761. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38762. this.alpha = this.lowerAlphaLimit;
  38763. }
  38764. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38765. this.alpha = this.upperAlphaLimit;
  38766. }
  38767. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38768. this.radius = this.lowerRadiusLimit;
  38769. }
  38770. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38771. this.radius = this.upperRadiusLimit;
  38772. }
  38773. };
  38774. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38775. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38776. this.radius = radiusv3.length();
  38777. if (this.radius === 0) {
  38778. this.radius = 0.0001; // Just to avoid division by zero
  38779. }
  38780. // Alpha
  38781. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38782. if (radiusv3.z < 0) {
  38783. this.alpha = 2 * Math.PI - this.alpha;
  38784. }
  38785. // Beta
  38786. this.beta = Math.acos(radiusv3.y / this.radius);
  38787. this._checkLimits();
  38788. };
  38789. ArcRotateCamera.prototype.setPosition = function (position) {
  38790. if (this.position.equals(position)) {
  38791. return;
  38792. }
  38793. this.position.copyFrom(position);
  38794. this.rebuildAnglesAndRadius();
  38795. };
  38796. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  38797. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  38798. if (allowSamePosition === void 0) { allowSamePosition = false; }
  38799. if (target.getBoundingInfo) {
  38800. if (toBoundingCenter) {
  38801. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  38802. }
  38803. else {
  38804. this._targetBoundingCenter = null;
  38805. }
  38806. this._targetHost = target;
  38807. this._target = this._getTargetPosition();
  38808. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  38809. }
  38810. else {
  38811. var newTarget = target;
  38812. var currentTarget = this._getTargetPosition();
  38813. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  38814. return;
  38815. }
  38816. this._targetHost = null;
  38817. this._target = newTarget;
  38818. this._targetBoundingCenter = null;
  38819. this.onMeshTargetChangedObservable.notifyObservers(null);
  38820. }
  38821. this.rebuildAnglesAndRadius();
  38822. };
  38823. ArcRotateCamera.prototype._getViewMatrix = function () {
  38824. // Compute
  38825. var cosa = Math.cos(this.alpha);
  38826. var sina = Math.sin(this.alpha);
  38827. var cosb = Math.cos(this.beta);
  38828. var sinb = Math.sin(this.beta);
  38829. if (sinb === 0) {
  38830. sinb = 0.0001;
  38831. }
  38832. var target = this._getTargetPosition();
  38833. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  38834. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  38835. if (!this._collider) {
  38836. this._collider = new BABYLON.Collider();
  38837. }
  38838. this._collider.radius = this.collisionRadius;
  38839. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  38840. this._collisionTriggered = true;
  38841. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38842. }
  38843. else {
  38844. this.position.copyFrom(this._newPosition);
  38845. var up = this.upVector;
  38846. if (this.allowUpsideDown && sinb < 0) {
  38847. up = up.clone();
  38848. up = up.negate();
  38849. }
  38850. if (this.getScene().useRightHandedSystem) {
  38851. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  38852. }
  38853. else {
  38854. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  38855. }
  38856. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  38857. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  38858. }
  38859. this._currentTarget = target;
  38860. return this._viewMatrix;
  38861. };
  38862. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  38863. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38864. meshes = meshes || this.getScene().meshes;
  38865. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  38866. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  38867. this.radius = distance * this.zoomOnFactor;
  38868. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  38869. };
  38870. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  38871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  38872. var meshesOrMinMaxVector;
  38873. var distance;
  38874. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  38875. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  38876. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  38877. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  38878. }
  38879. else {
  38880. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  38881. meshesOrMinMaxVector = minMaxVectorAndDistance;
  38882. distance = minMaxVectorAndDistance.distance;
  38883. }
  38884. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  38885. if (!doNotUpdateMaxZ) {
  38886. this.maxZ = distance * 2;
  38887. }
  38888. };
  38889. /**
  38890. * @override
  38891. * Override Camera.createRigCamera
  38892. */
  38893. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38894. var alphaShift = 0;
  38895. switch (this.cameraRigMode) {
  38896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38899. case BABYLON.Camera.RIG_MODE_VR:
  38900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  38901. break;
  38902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38903. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  38904. break;
  38905. }
  38906. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  38907. rigCam._cameraRigParams = {};
  38908. return rigCam;
  38909. };
  38910. /**
  38911. * @override
  38912. * Override Camera._updateRigCameras
  38913. */
  38914. ArcRotateCamera.prototype._updateRigCameras = function () {
  38915. var camLeft = this._rigCameras[0];
  38916. var camRight = this._rigCameras[1];
  38917. camLeft.beta = camRight.beta = this.beta;
  38918. camLeft.radius = camRight.radius = this.radius;
  38919. switch (this.cameraRigMode) {
  38920. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38922. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38923. case BABYLON.Camera.RIG_MODE_VR:
  38924. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38925. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38926. break;
  38927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38928. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  38929. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  38930. break;
  38931. }
  38932. _super.prototype._updateRigCameras.call(this);
  38933. };
  38934. ArcRotateCamera.prototype.dispose = function () {
  38935. this.inputs.clear();
  38936. _super.prototype.dispose.call(this);
  38937. };
  38938. ArcRotateCamera.prototype.getClassName = function () {
  38939. return "ArcRotateCamera";
  38940. };
  38941. __decorate([
  38942. BABYLON.serialize()
  38943. ], ArcRotateCamera.prototype, "alpha", void 0);
  38944. __decorate([
  38945. BABYLON.serialize()
  38946. ], ArcRotateCamera.prototype, "beta", void 0);
  38947. __decorate([
  38948. BABYLON.serialize()
  38949. ], ArcRotateCamera.prototype, "radius", void 0);
  38950. __decorate([
  38951. BABYLON.serializeAsVector3("target")
  38952. ], ArcRotateCamera.prototype, "_target", void 0);
  38953. __decorate([
  38954. BABYLON.serialize()
  38955. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  38956. __decorate([
  38957. BABYLON.serialize()
  38958. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  38959. __decorate([
  38960. BABYLON.serialize()
  38961. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  38962. __decorate([
  38963. BABYLON.serialize()
  38964. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  38965. __decorate([
  38966. BABYLON.serialize()
  38967. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  38968. __decorate([
  38969. BABYLON.serialize()
  38970. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  38971. __decorate([
  38972. BABYLON.serialize()
  38973. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  38974. __decorate([
  38975. BABYLON.serialize()
  38976. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  38977. __decorate([
  38978. BABYLON.serialize()
  38979. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  38980. __decorate([
  38981. BABYLON.serialize()
  38982. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  38983. __decorate([
  38984. BABYLON.serialize()
  38985. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  38986. __decorate([
  38987. BABYLON.serialize()
  38988. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  38989. __decorate([
  38990. BABYLON.serialize()
  38991. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  38992. __decorate([
  38993. BABYLON.serializeAsVector3()
  38994. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  38995. __decorate([
  38996. BABYLON.serialize()
  38997. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  38998. __decorate([
  38999. BABYLON.serialize()
  39000. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39001. __decorate([
  39002. BABYLON.serialize()
  39003. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39004. return ArcRotateCamera;
  39005. }(BABYLON.TargetCamera));
  39006. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39007. })(BABYLON || (BABYLON = {}));
  39008. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39009. var BABYLON;
  39010. (function (BABYLON) {
  39011. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39012. __extends(ArcRotateCameraInputsManager, _super);
  39013. function ArcRotateCameraInputsManager(camera) {
  39014. return _super.call(this, camera) || this;
  39015. }
  39016. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39017. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39018. return this;
  39019. };
  39020. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39021. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39022. return this;
  39023. };
  39024. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39025. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39026. return this;
  39027. };
  39028. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39029. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39030. return this;
  39031. };
  39032. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39033. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39034. return this;
  39035. };
  39036. return ArcRotateCameraInputsManager;
  39037. }(BABYLON.CameraInputsManager));
  39038. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39039. })(BABYLON || (BABYLON = {}));
  39040. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39041. var BABYLON;
  39042. (function (BABYLON) {
  39043. var HemisphericLight = /** @class */ (function (_super) {
  39044. __extends(HemisphericLight, _super);
  39045. /**
  39046. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39047. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39048. * The HemisphericLight can't cast shadows.
  39049. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39050. */
  39051. function HemisphericLight(name, direction, scene) {
  39052. var _this = _super.call(this, name, scene) || this;
  39053. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39054. _this.direction = direction || BABYLON.Vector3.Up();
  39055. return _this;
  39056. }
  39057. HemisphericLight.prototype._buildUniformLayout = function () {
  39058. this._uniformBuffer.addUniform("vLightData", 4);
  39059. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39060. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39061. this._uniformBuffer.addUniform("vLightGround", 3);
  39062. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39063. this._uniformBuffer.addUniform("depthValues", 2);
  39064. this._uniformBuffer.create();
  39065. };
  39066. /**
  39067. * Returns the string "HemisphericLight".
  39068. */
  39069. HemisphericLight.prototype.getClassName = function () {
  39070. return "HemisphericLight";
  39071. };
  39072. /**
  39073. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39074. * Returns the updated direction.
  39075. */
  39076. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39077. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39078. return this.direction;
  39079. };
  39080. HemisphericLight.prototype.getShadowGenerator = function () {
  39081. return null;
  39082. };
  39083. /**
  39084. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39085. * Returns the HemisphericLight.
  39086. */
  39087. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39088. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39089. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39090. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39091. return this;
  39092. };
  39093. HemisphericLight.prototype._getWorldMatrix = function () {
  39094. if (!this._worldMatrix) {
  39095. this._worldMatrix = BABYLON.Matrix.Identity();
  39096. }
  39097. return this._worldMatrix;
  39098. };
  39099. /**
  39100. * Returns the integer 3.
  39101. */
  39102. HemisphericLight.prototype.getTypeID = function () {
  39103. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39104. };
  39105. __decorate([
  39106. BABYLON.serializeAsColor3()
  39107. ], HemisphericLight.prototype, "groundColor", void 0);
  39108. __decorate([
  39109. BABYLON.serializeAsVector3()
  39110. ], HemisphericLight.prototype, "direction", void 0);
  39111. return HemisphericLight;
  39112. }(BABYLON.Light));
  39113. BABYLON.HemisphericLight = HemisphericLight;
  39114. })(BABYLON || (BABYLON = {}));
  39115. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39116. var BABYLON;
  39117. (function (BABYLON) {
  39118. var ShadowLight = /** @class */ (function (_super) {
  39119. __extends(ShadowLight, _super);
  39120. function ShadowLight() {
  39121. var _this = _super !== null && _super.apply(this, arguments) || this;
  39122. _this._needProjectionMatrixCompute = true;
  39123. return _this;
  39124. }
  39125. Object.defineProperty(ShadowLight.prototype, "direction", {
  39126. get: function () {
  39127. return this._direction;
  39128. },
  39129. set: function (value) {
  39130. this._direction = value;
  39131. },
  39132. enumerable: true,
  39133. configurable: true
  39134. });
  39135. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39136. get: function () {
  39137. return this._shadowMinZ;
  39138. },
  39139. set: function (value) {
  39140. this._shadowMinZ = value;
  39141. this.forceProjectionMatrixCompute();
  39142. },
  39143. enumerable: true,
  39144. configurable: true
  39145. });
  39146. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39147. get: function () {
  39148. return this._shadowMaxZ;
  39149. },
  39150. set: function (value) {
  39151. this._shadowMaxZ = value;
  39152. this.forceProjectionMatrixCompute();
  39153. },
  39154. enumerable: true,
  39155. configurable: true
  39156. });
  39157. /**
  39158. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39159. */
  39160. ShadowLight.prototype.computeTransformedInformation = function () {
  39161. if (this.parent && this.parent.getWorldMatrix) {
  39162. if (!this.transformedPosition) {
  39163. this.transformedPosition = BABYLON.Vector3.Zero();
  39164. }
  39165. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39166. // In case the direction is present.
  39167. if (this.direction) {
  39168. if (!this.transformedDirection) {
  39169. this.transformedDirection = BABYLON.Vector3.Zero();
  39170. }
  39171. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39172. }
  39173. return true;
  39174. }
  39175. return false;
  39176. };
  39177. /**
  39178. * Return the depth scale used for the shadow map.
  39179. */
  39180. ShadowLight.prototype.getDepthScale = function () {
  39181. return 50.0;
  39182. };
  39183. /**
  39184. * Returns the light direction (Vector3) for any passed face index.
  39185. */
  39186. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39187. return this.transformedDirection ? this.transformedDirection : this.direction;
  39188. };
  39189. /**
  39190. * Returns the DirectionalLight absolute position in the World.
  39191. */
  39192. ShadowLight.prototype.getAbsolutePosition = function () {
  39193. return this.transformedPosition ? this.transformedPosition : this.position;
  39194. };
  39195. /**
  39196. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39197. * Returns the updated DirectionalLight direction (Vector3).
  39198. */
  39199. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39200. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39201. return this.direction;
  39202. };
  39203. /**
  39204. * Returns the light rotation (Vector3).
  39205. */
  39206. ShadowLight.prototype.getRotation = function () {
  39207. this.direction.normalize();
  39208. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39209. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39210. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39211. };
  39212. /**
  39213. * Boolean : false by default.
  39214. */
  39215. ShadowLight.prototype.needCube = function () {
  39216. return false;
  39217. };
  39218. /**
  39219. * Specifies wether or not the projection matrix should be recomputed this frame.
  39220. */
  39221. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39222. return this._needProjectionMatrixCompute;
  39223. };
  39224. /**
  39225. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39226. */
  39227. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39228. this._needProjectionMatrixCompute = true;
  39229. };
  39230. /**
  39231. * Get the world matrix of the sahdow lights.
  39232. */
  39233. ShadowLight.prototype._getWorldMatrix = function () {
  39234. if (!this._worldMatrix) {
  39235. this._worldMatrix = BABYLON.Matrix.Identity();
  39236. }
  39237. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39238. return this._worldMatrix;
  39239. };
  39240. /**
  39241. * Gets the minZ used for shadow according to both the scene and the light.
  39242. * @param activeCamera
  39243. */
  39244. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39245. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39246. };
  39247. /**
  39248. * Gets the maxZ used for shadow according to both the scene and the light.
  39249. * @param activeCamera
  39250. */
  39251. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39252. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39253. };
  39254. /**
  39255. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39256. * Returns the light.
  39257. */
  39258. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39259. if (this.customProjectionMatrixBuilder) {
  39260. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39261. }
  39262. else {
  39263. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39264. }
  39265. return this;
  39266. };
  39267. __decorate([
  39268. BABYLON.serializeAsVector3()
  39269. ], ShadowLight.prototype, "position", void 0);
  39270. __decorate([
  39271. BABYLON.serializeAsVector3()
  39272. ], ShadowLight.prototype, "direction", null);
  39273. __decorate([
  39274. BABYLON.serialize()
  39275. ], ShadowLight.prototype, "shadowMinZ", null);
  39276. __decorate([
  39277. BABYLON.serialize()
  39278. ], ShadowLight.prototype, "shadowMaxZ", null);
  39279. return ShadowLight;
  39280. }(BABYLON.Light));
  39281. BABYLON.ShadowLight = ShadowLight;
  39282. })(BABYLON || (BABYLON = {}));
  39283. //# sourceMappingURL=babylon.shadowLight.js.map
  39284. var BABYLON;
  39285. (function (BABYLON) {
  39286. var PointLight = /** @class */ (function (_super) {
  39287. __extends(PointLight, _super);
  39288. /**
  39289. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39290. * A PointLight emits the light in every direction.
  39291. * It can cast shadows.
  39292. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39293. * ```javascript
  39294. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39295. * ```
  39296. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39297. */
  39298. function PointLight(name, position, scene) {
  39299. var _this = _super.call(this, name, scene) || this;
  39300. _this._shadowAngle = Math.PI / 2;
  39301. _this.position = position;
  39302. return _this;
  39303. }
  39304. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39305. /**
  39306. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39307. * This specifies what angle the shadow will use to be created.
  39308. *
  39309. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39310. */
  39311. get: function () {
  39312. return this._shadowAngle;
  39313. },
  39314. /**
  39315. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39316. * This specifies what angle the shadow will use to be created.
  39317. *
  39318. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39319. */
  39320. set: function (value) {
  39321. this._shadowAngle = value;
  39322. this.forceProjectionMatrixCompute();
  39323. },
  39324. enumerable: true,
  39325. configurable: true
  39326. });
  39327. Object.defineProperty(PointLight.prototype, "direction", {
  39328. get: function () {
  39329. return this._direction;
  39330. },
  39331. /**
  39332. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39333. */
  39334. set: function (value) {
  39335. var previousNeedCube = this.needCube();
  39336. this._direction = value;
  39337. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39338. this._shadowGenerator.recreateShadowMap();
  39339. }
  39340. },
  39341. enumerable: true,
  39342. configurable: true
  39343. });
  39344. /**
  39345. * Returns the string "PointLight"
  39346. */
  39347. PointLight.prototype.getClassName = function () {
  39348. return "PointLight";
  39349. };
  39350. /**
  39351. * Returns the integer 0.
  39352. */
  39353. PointLight.prototype.getTypeID = function () {
  39354. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39355. };
  39356. /**
  39357. * Specifies wether or not the shadowmap should be a cube texture.
  39358. */
  39359. PointLight.prototype.needCube = function () {
  39360. return !this.direction;
  39361. };
  39362. /**
  39363. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39364. */
  39365. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39366. if (this.direction) {
  39367. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39368. }
  39369. else {
  39370. switch (faceIndex) {
  39371. case 0:
  39372. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39373. case 1:
  39374. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39375. case 2:
  39376. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39377. case 3:
  39378. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39379. case 4:
  39380. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39381. case 5:
  39382. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39383. }
  39384. }
  39385. return BABYLON.Vector3.Zero();
  39386. };
  39387. /**
  39388. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39389. * - fov = PI / 2
  39390. * - aspect ratio : 1.0
  39391. * - z-near and far equal to the active camera minZ and maxZ.
  39392. * Returns the PointLight.
  39393. */
  39394. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39395. var activeCamera = this.getScene().activeCamera;
  39396. if (!activeCamera) {
  39397. return;
  39398. }
  39399. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39400. };
  39401. PointLight.prototype._buildUniformLayout = function () {
  39402. this._uniformBuffer.addUniform("vLightData", 4);
  39403. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39404. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39405. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39406. this._uniformBuffer.addUniform("depthValues", 2);
  39407. this._uniformBuffer.create();
  39408. };
  39409. /**
  39410. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39411. * Returns the PointLight.
  39412. */
  39413. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39414. if (this.computeTransformedInformation()) {
  39415. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39416. return this;
  39417. }
  39418. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39419. return this;
  39420. };
  39421. __decorate([
  39422. BABYLON.serialize()
  39423. ], PointLight.prototype, "shadowAngle", null);
  39424. return PointLight;
  39425. }(BABYLON.ShadowLight));
  39426. BABYLON.PointLight = PointLight;
  39427. })(BABYLON || (BABYLON = {}));
  39428. //# sourceMappingURL=babylon.pointLight.js.map
  39429. var BABYLON;
  39430. (function (BABYLON) {
  39431. var DirectionalLight = /** @class */ (function (_super) {
  39432. __extends(DirectionalLight, _super);
  39433. /**
  39434. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39435. * The directional light is emitted from everywhere in the given direction.
  39436. * It can cast shawdows.
  39437. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39438. */
  39439. function DirectionalLight(name, direction, scene) {
  39440. var _this = _super.call(this, name, scene) || this;
  39441. _this._shadowFrustumSize = 0;
  39442. _this._shadowOrthoScale = 0.5;
  39443. _this.autoUpdateExtends = true;
  39444. // Cache
  39445. _this._orthoLeft = Number.MAX_VALUE;
  39446. _this._orthoRight = Number.MIN_VALUE;
  39447. _this._orthoTop = Number.MIN_VALUE;
  39448. _this._orthoBottom = Number.MAX_VALUE;
  39449. _this.position = direction.scale(-1.0);
  39450. _this.direction = direction;
  39451. return _this;
  39452. }
  39453. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39454. /**
  39455. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39456. */
  39457. get: function () {
  39458. return this._shadowFrustumSize;
  39459. },
  39460. /**
  39461. * Specifies a fix frustum size for the shadow generation.
  39462. */
  39463. set: function (value) {
  39464. this._shadowFrustumSize = value;
  39465. this.forceProjectionMatrixCompute();
  39466. },
  39467. enumerable: true,
  39468. configurable: true
  39469. });
  39470. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39471. get: function () {
  39472. return this._shadowOrthoScale;
  39473. },
  39474. set: function (value) {
  39475. this._shadowOrthoScale = value;
  39476. this.forceProjectionMatrixCompute();
  39477. },
  39478. enumerable: true,
  39479. configurable: true
  39480. });
  39481. /**
  39482. * Returns the string "DirectionalLight".
  39483. */
  39484. DirectionalLight.prototype.getClassName = function () {
  39485. return "DirectionalLight";
  39486. };
  39487. /**
  39488. * Returns the integer 1.
  39489. */
  39490. DirectionalLight.prototype.getTypeID = function () {
  39491. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39492. };
  39493. /**
  39494. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39495. * Returns the DirectionalLight Shadow projection matrix.
  39496. */
  39497. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39498. if (this.shadowFrustumSize > 0) {
  39499. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39500. }
  39501. else {
  39502. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39503. }
  39504. };
  39505. /**
  39506. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39507. * Returns the DirectionalLight Shadow projection matrix.
  39508. */
  39509. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39510. var activeCamera = this.getScene().activeCamera;
  39511. if (!activeCamera) {
  39512. return;
  39513. }
  39514. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39515. };
  39516. /**
  39517. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39518. * Returns the DirectionalLight Shadow projection matrix.
  39519. */
  39520. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39521. var activeCamera = this.getScene().activeCamera;
  39522. if (!activeCamera) {
  39523. return;
  39524. }
  39525. // Check extends
  39526. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39527. var tempVector3 = BABYLON.Vector3.Zero();
  39528. this._orthoLeft = Number.MAX_VALUE;
  39529. this._orthoRight = Number.MIN_VALUE;
  39530. this._orthoTop = Number.MIN_VALUE;
  39531. this._orthoBottom = Number.MAX_VALUE;
  39532. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39533. var mesh = renderList[meshIndex];
  39534. if (!mesh) {
  39535. continue;
  39536. }
  39537. var boundingInfo = mesh.getBoundingInfo();
  39538. if (!boundingInfo) {
  39539. continue;
  39540. }
  39541. var boundingBox = boundingInfo.boundingBox;
  39542. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39543. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39544. if (tempVector3.x < this._orthoLeft)
  39545. this._orthoLeft = tempVector3.x;
  39546. if (tempVector3.y < this._orthoBottom)
  39547. this._orthoBottom = tempVector3.y;
  39548. if (tempVector3.x > this._orthoRight)
  39549. this._orthoRight = tempVector3.x;
  39550. if (tempVector3.y > this._orthoTop)
  39551. this._orthoTop = tempVector3.y;
  39552. }
  39553. }
  39554. }
  39555. var xOffset = this._orthoRight - this._orthoLeft;
  39556. var yOffset = this._orthoTop - this._orthoBottom;
  39557. 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);
  39558. };
  39559. DirectionalLight.prototype._buildUniformLayout = function () {
  39560. this._uniformBuffer.addUniform("vLightData", 4);
  39561. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39562. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39563. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39564. this._uniformBuffer.addUniform("depthValues", 2);
  39565. this._uniformBuffer.create();
  39566. };
  39567. /**
  39568. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39569. * Returns the DirectionalLight.
  39570. */
  39571. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39572. if (this.computeTransformedInformation()) {
  39573. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39574. return this;
  39575. }
  39576. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39577. return this;
  39578. };
  39579. /**
  39580. * Gets the minZ used for shadow according to both the scene and the light.
  39581. *
  39582. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39583. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39584. * @param activeCamera
  39585. */
  39586. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39587. return 1;
  39588. };
  39589. /**
  39590. * Gets the maxZ used for shadow according to both the scene and the light.
  39591. *
  39592. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39593. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39594. * @param activeCamera
  39595. */
  39596. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39597. return 1;
  39598. };
  39599. __decorate([
  39600. BABYLON.serialize()
  39601. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39602. __decorate([
  39603. BABYLON.serialize()
  39604. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39605. __decorate([
  39606. BABYLON.serialize()
  39607. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39608. return DirectionalLight;
  39609. }(BABYLON.ShadowLight));
  39610. BABYLON.DirectionalLight = DirectionalLight;
  39611. })(BABYLON || (BABYLON = {}));
  39612. //# sourceMappingURL=babylon.directionalLight.js.map
  39613. var BABYLON;
  39614. (function (BABYLON) {
  39615. var SpotLight = /** @class */ (function (_super) {
  39616. __extends(SpotLight, _super);
  39617. /**
  39618. * Creates a SpotLight object in the scene with the passed parameters :
  39619. * - `position` (Vector3) is the initial SpotLight position,
  39620. * - `direction` (Vector3) is the initial SpotLight direction,
  39621. * - `angle` (float, in radians) is the spot light cone angle,
  39622. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39623. * A spot light is a simply light oriented cone.
  39624. * It can cast shadows.
  39625. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39626. */
  39627. function SpotLight(name, position, direction, angle, exponent, scene) {
  39628. var _this = _super.call(this, name, scene) || this;
  39629. _this.position = position;
  39630. _this.direction = direction;
  39631. _this.angle = angle;
  39632. _this.exponent = exponent;
  39633. return _this;
  39634. }
  39635. Object.defineProperty(SpotLight.prototype, "angle", {
  39636. get: function () {
  39637. return this._angle;
  39638. },
  39639. set: function (value) {
  39640. this._angle = value;
  39641. this.forceProjectionMatrixCompute();
  39642. },
  39643. enumerable: true,
  39644. configurable: true
  39645. });
  39646. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39647. get: function () {
  39648. return this._shadowAngleScale;
  39649. },
  39650. /**
  39651. * Allows scaling the angle of the light for shadow generation only.
  39652. */
  39653. set: function (value) {
  39654. this._shadowAngleScale = value;
  39655. this.forceProjectionMatrixCompute();
  39656. },
  39657. enumerable: true,
  39658. configurable: true
  39659. });
  39660. /**
  39661. * Returns the string "SpotLight".
  39662. */
  39663. SpotLight.prototype.getClassName = function () {
  39664. return "SpotLight";
  39665. };
  39666. /**
  39667. * Returns the integer 2.
  39668. */
  39669. SpotLight.prototype.getTypeID = function () {
  39670. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39671. };
  39672. /**
  39673. * 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.
  39674. * Returns the SpotLight.
  39675. */
  39676. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39677. var activeCamera = this.getScene().activeCamera;
  39678. if (!activeCamera) {
  39679. return;
  39680. }
  39681. this._shadowAngleScale = this._shadowAngleScale || 1;
  39682. var angle = this._shadowAngleScale * this._angle;
  39683. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39684. };
  39685. SpotLight.prototype._buildUniformLayout = function () {
  39686. this._uniformBuffer.addUniform("vLightData", 4);
  39687. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39688. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39689. this._uniformBuffer.addUniform("vLightDirection", 3);
  39690. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39691. this._uniformBuffer.addUniform("depthValues", 2);
  39692. this._uniformBuffer.create();
  39693. };
  39694. /**
  39695. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39696. * Return the SpotLight.
  39697. */
  39698. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39699. var normalizeDirection;
  39700. if (this.computeTransformedInformation()) {
  39701. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39702. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39703. }
  39704. else {
  39705. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39706. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39707. }
  39708. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39709. return this;
  39710. };
  39711. __decorate([
  39712. BABYLON.serialize()
  39713. ], SpotLight.prototype, "angle", null);
  39714. __decorate([
  39715. BABYLON.serialize()
  39716. /**
  39717. * Allows scaling the angle of the light for shadow generation only.
  39718. */
  39719. ], SpotLight.prototype, "shadowAngleScale", null);
  39720. __decorate([
  39721. BABYLON.serialize()
  39722. ], SpotLight.prototype, "exponent", void 0);
  39723. return SpotLight;
  39724. }(BABYLON.ShadowLight));
  39725. BABYLON.SpotLight = SpotLight;
  39726. })(BABYLON || (BABYLON = {}));
  39727. //# sourceMappingURL=babylon.spotLight.js.map
  39728. var BABYLON;
  39729. (function (BABYLON) {
  39730. var AnimationRange = /** @class */ (function () {
  39731. function AnimationRange(name, from, to) {
  39732. this.name = name;
  39733. this.from = from;
  39734. this.to = to;
  39735. }
  39736. AnimationRange.prototype.clone = function () {
  39737. return new AnimationRange(this.name, this.from, this.to);
  39738. };
  39739. return AnimationRange;
  39740. }());
  39741. BABYLON.AnimationRange = AnimationRange;
  39742. /**
  39743. * Composed of a frame, and an action function
  39744. */
  39745. var AnimationEvent = /** @class */ (function () {
  39746. function AnimationEvent(frame, action, onlyOnce) {
  39747. this.frame = frame;
  39748. this.action = action;
  39749. this.onlyOnce = onlyOnce;
  39750. this.isDone = false;
  39751. }
  39752. return AnimationEvent;
  39753. }());
  39754. BABYLON.AnimationEvent = AnimationEvent;
  39755. var PathCursor = /** @class */ (function () {
  39756. function PathCursor(path) {
  39757. this.path = path;
  39758. this._onchange = new Array();
  39759. this.value = 0;
  39760. this.animations = new Array();
  39761. }
  39762. PathCursor.prototype.getPoint = function () {
  39763. var point = this.path.getPointAtLengthPosition(this.value);
  39764. return new BABYLON.Vector3(point.x, 0, point.y);
  39765. };
  39766. PathCursor.prototype.moveAhead = function (step) {
  39767. if (step === void 0) { step = 0.002; }
  39768. this.move(step);
  39769. return this;
  39770. };
  39771. PathCursor.prototype.moveBack = function (step) {
  39772. if (step === void 0) { step = 0.002; }
  39773. this.move(-step);
  39774. return this;
  39775. };
  39776. PathCursor.prototype.move = function (step) {
  39777. if (Math.abs(step) > 1) {
  39778. throw "step size should be less than 1.";
  39779. }
  39780. this.value += step;
  39781. this.ensureLimits();
  39782. this.raiseOnChange();
  39783. return this;
  39784. };
  39785. PathCursor.prototype.ensureLimits = function () {
  39786. while (this.value > 1) {
  39787. this.value -= 1;
  39788. }
  39789. while (this.value < 0) {
  39790. this.value += 1;
  39791. }
  39792. return this;
  39793. };
  39794. // used by animation engine
  39795. PathCursor.prototype.raiseOnChange = function () {
  39796. var _this = this;
  39797. this._onchange.forEach(function (f) { return f(_this); });
  39798. return this;
  39799. };
  39800. PathCursor.prototype.onchange = function (f) {
  39801. this._onchange.push(f);
  39802. return this;
  39803. };
  39804. return PathCursor;
  39805. }());
  39806. BABYLON.PathCursor = PathCursor;
  39807. var Animation = /** @class */ (function () {
  39808. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  39809. this.name = name;
  39810. this.targetProperty = targetProperty;
  39811. this.framePerSecond = framePerSecond;
  39812. this.dataType = dataType;
  39813. this.loopMode = loopMode;
  39814. this.enableBlending = enableBlending;
  39815. this._runtimeAnimations = new Array();
  39816. // The set of event that will be linked to this animation
  39817. this._events = new Array();
  39818. this.blendingSpeed = 0.01;
  39819. this._ranges = {};
  39820. this.targetPropertyPath = targetProperty.split(".");
  39821. this.dataType = dataType;
  39822. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  39823. }
  39824. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  39825. var dataType = undefined;
  39826. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  39827. dataType = Animation.ANIMATIONTYPE_FLOAT;
  39828. }
  39829. else if (from instanceof BABYLON.Quaternion) {
  39830. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  39831. }
  39832. else if (from instanceof BABYLON.Vector3) {
  39833. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  39834. }
  39835. else if (from instanceof BABYLON.Vector2) {
  39836. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  39837. }
  39838. else if (from instanceof BABYLON.Color3) {
  39839. dataType = Animation.ANIMATIONTYPE_COLOR3;
  39840. }
  39841. else if (from instanceof BABYLON.Size) {
  39842. dataType = Animation.ANIMATIONTYPE_SIZE;
  39843. }
  39844. if (dataType == undefined) {
  39845. return null;
  39846. }
  39847. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  39848. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  39849. animation.setKeys(keys);
  39850. if (easingFunction !== undefined) {
  39851. animation.setEasingFunction(easingFunction);
  39852. }
  39853. return animation;
  39854. };
  39855. /**
  39856. * Sets up an animation.
  39857. * @param property the property to animate
  39858. * @param animationType the animation type to apply
  39859. * @param easingFunction the easing function used in the animation
  39860. * @returns The created animation
  39861. */
  39862. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  39863. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39864. animation.setEasingFunction(easingFunction);
  39865. return animation;
  39866. };
  39867. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39868. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39869. if (!animation) {
  39870. return null;
  39871. }
  39872. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39873. };
  39874. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  39875. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  39876. if (!animation) {
  39877. return null;
  39878. }
  39879. node.animations.push(animation);
  39880. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  39881. };
  39882. /**
  39883. * Transition property of the Camera to the target Value.
  39884. * @param property The property to transition
  39885. * @param targetValue The target Value of the property
  39886. * @param host The object where the property to animate belongs
  39887. * @param scene Scene used to run the animation
  39888. * @param frameRate Framerate (in frame/s) to use
  39889. * @param transition The transition type we want to use
  39890. * @param duration The duration of the animation, in milliseconds
  39891. * @param onAnimationEnd Call back trigger at the end of the animation.
  39892. */
  39893. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  39894. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  39895. if (duration <= 0) {
  39896. host[property] = targetValue;
  39897. if (onAnimationEnd) {
  39898. onAnimationEnd();
  39899. }
  39900. return null;
  39901. }
  39902. var endFrame = frameRate * (duration / 1000);
  39903. transition.setKeys([{
  39904. frame: 0,
  39905. value: host[property].clone ? host[property].clone() : host[property]
  39906. },
  39907. {
  39908. frame: endFrame,
  39909. value: targetValue
  39910. }]);
  39911. if (!host.animations) {
  39912. host.animations = [];
  39913. }
  39914. host.animations.push(transition);
  39915. var animation = scene.beginAnimation(host, 0, endFrame, false);
  39916. animation.onAnimationEnd = onAnimationEnd;
  39917. return animation;
  39918. };
  39919. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  39920. /**
  39921. * Return the array of runtime animations currently using this animation
  39922. */
  39923. get: function () {
  39924. return this._runtimeAnimations;
  39925. },
  39926. enumerable: true,
  39927. configurable: true
  39928. });
  39929. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  39930. get: function () {
  39931. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  39932. var runtimeAnimation = _a[_i];
  39933. if (!runtimeAnimation.isStopped) {
  39934. return true;
  39935. }
  39936. }
  39937. return false;
  39938. },
  39939. enumerable: true,
  39940. configurable: true
  39941. });
  39942. // Methods
  39943. /**
  39944. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  39945. */
  39946. Animation.prototype.toString = function (fullDetails) {
  39947. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  39948. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  39949. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  39950. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  39951. if (fullDetails) {
  39952. ret += ", Ranges: {";
  39953. var first = true;
  39954. for (var name in this._ranges) {
  39955. if (first) {
  39956. ret += ", ";
  39957. first = false;
  39958. }
  39959. ret += name;
  39960. }
  39961. ret += "}";
  39962. }
  39963. return ret;
  39964. };
  39965. /**
  39966. * Add an event to this animation.
  39967. */
  39968. Animation.prototype.addEvent = function (event) {
  39969. this._events.push(event);
  39970. };
  39971. /**
  39972. * Remove all events found at the given frame
  39973. * @param frame
  39974. */
  39975. Animation.prototype.removeEvents = function (frame) {
  39976. for (var index = 0; index < this._events.length; index++) {
  39977. if (this._events[index].frame === frame) {
  39978. this._events.splice(index, 1);
  39979. index--;
  39980. }
  39981. }
  39982. };
  39983. Animation.prototype.getEvents = function () {
  39984. return this._events;
  39985. };
  39986. Animation.prototype.createRange = function (name, from, to) {
  39987. // check name not already in use; could happen for bones after serialized
  39988. if (!this._ranges[name]) {
  39989. this._ranges[name] = new AnimationRange(name, from, to);
  39990. }
  39991. };
  39992. Animation.prototype.deleteRange = function (name, deleteFrames) {
  39993. if (deleteFrames === void 0) { deleteFrames = true; }
  39994. var range = this._ranges[name];
  39995. if (!range) {
  39996. return;
  39997. }
  39998. if (deleteFrames) {
  39999. var from = range.from;
  40000. var to = range.to;
  40001. // this loop MUST go high to low for multiple splices to work
  40002. for (var key = this._keys.length - 1; key >= 0; key--) {
  40003. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40004. this._keys.splice(key, 1);
  40005. }
  40006. }
  40007. }
  40008. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40009. };
  40010. Animation.prototype.getRange = function (name) {
  40011. return this._ranges[name];
  40012. };
  40013. Animation.prototype.getKeys = function () {
  40014. return this._keys;
  40015. };
  40016. Animation.prototype.getHighestFrame = function () {
  40017. var ret = 0;
  40018. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40019. if (ret < this._keys[key].frame) {
  40020. ret = this._keys[key].frame;
  40021. }
  40022. }
  40023. return ret;
  40024. };
  40025. Animation.prototype.getEasingFunction = function () {
  40026. return this._easingFunction;
  40027. };
  40028. Animation.prototype.setEasingFunction = function (easingFunction) {
  40029. this._easingFunction = easingFunction;
  40030. };
  40031. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40032. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40033. };
  40034. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40035. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40036. };
  40037. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40038. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40039. };
  40040. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40041. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40042. };
  40043. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40044. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40045. };
  40046. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40047. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40048. };
  40049. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40050. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40051. };
  40052. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40053. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40054. };
  40055. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40056. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40057. };
  40058. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40059. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40060. };
  40061. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40062. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40063. };
  40064. Animation.prototype.clone = function () {
  40065. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40066. clone.enableBlending = this.enableBlending;
  40067. clone.blendingSpeed = this.blendingSpeed;
  40068. if (this._keys) {
  40069. clone.setKeys(this._keys);
  40070. }
  40071. if (this._ranges) {
  40072. clone._ranges = {};
  40073. for (var name in this._ranges) {
  40074. var range = this._ranges[name];
  40075. if (!range) {
  40076. continue;
  40077. }
  40078. clone._ranges[name] = range.clone();
  40079. }
  40080. }
  40081. return clone;
  40082. };
  40083. Animation.prototype.setKeys = function (values) {
  40084. this._keys = values.slice(0);
  40085. };
  40086. Animation.prototype.serialize = function () {
  40087. var serializationObject = {};
  40088. serializationObject.name = this.name;
  40089. serializationObject.property = this.targetProperty;
  40090. serializationObject.framePerSecond = this.framePerSecond;
  40091. serializationObject.dataType = this.dataType;
  40092. serializationObject.loopBehavior = this.loopMode;
  40093. serializationObject.enableBlending = this.enableBlending;
  40094. serializationObject.blendingSpeed = this.blendingSpeed;
  40095. var dataType = this.dataType;
  40096. serializationObject.keys = [];
  40097. var keys = this.getKeys();
  40098. for (var index = 0; index < keys.length; index++) {
  40099. var animationKey = keys[index];
  40100. var key = {};
  40101. key.frame = animationKey.frame;
  40102. switch (dataType) {
  40103. case Animation.ANIMATIONTYPE_FLOAT:
  40104. key.values = [animationKey.value];
  40105. break;
  40106. case Animation.ANIMATIONTYPE_QUATERNION:
  40107. case Animation.ANIMATIONTYPE_MATRIX:
  40108. case Animation.ANIMATIONTYPE_VECTOR3:
  40109. case Animation.ANIMATIONTYPE_COLOR3:
  40110. key.values = animationKey.value.asArray();
  40111. break;
  40112. }
  40113. serializationObject.keys.push(key);
  40114. }
  40115. serializationObject.ranges = [];
  40116. for (var name in this._ranges) {
  40117. var source = this._ranges[name];
  40118. if (!source) {
  40119. continue;
  40120. }
  40121. var range = {};
  40122. range.name = name;
  40123. range.from = source.from;
  40124. range.to = source.to;
  40125. serializationObject.ranges.push(range);
  40126. }
  40127. return serializationObject;
  40128. };
  40129. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40130. get: function () {
  40131. return Animation._ANIMATIONTYPE_FLOAT;
  40132. },
  40133. enumerable: true,
  40134. configurable: true
  40135. });
  40136. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40137. get: function () {
  40138. return Animation._ANIMATIONTYPE_VECTOR3;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40144. get: function () {
  40145. return Animation._ANIMATIONTYPE_VECTOR2;
  40146. },
  40147. enumerable: true,
  40148. configurable: true
  40149. });
  40150. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40151. get: function () {
  40152. return Animation._ANIMATIONTYPE_SIZE;
  40153. },
  40154. enumerable: true,
  40155. configurable: true
  40156. });
  40157. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40158. get: function () {
  40159. return Animation._ANIMATIONTYPE_QUATERNION;
  40160. },
  40161. enumerable: true,
  40162. configurable: true
  40163. });
  40164. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40165. get: function () {
  40166. return Animation._ANIMATIONTYPE_MATRIX;
  40167. },
  40168. enumerable: true,
  40169. configurable: true
  40170. });
  40171. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40172. get: function () {
  40173. return Animation._ANIMATIONTYPE_COLOR3;
  40174. },
  40175. enumerable: true,
  40176. configurable: true
  40177. });
  40178. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40179. get: function () {
  40180. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40181. },
  40182. enumerable: true,
  40183. configurable: true
  40184. });
  40185. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40186. get: function () {
  40187. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40188. },
  40189. enumerable: true,
  40190. configurable: true
  40191. });
  40192. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40193. get: function () {
  40194. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40195. },
  40196. enumerable: true,
  40197. configurable: true
  40198. });
  40199. Animation.Parse = function (parsedAnimation) {
  40200. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40201. var dataType = parsedAnimation.dataType;
  40202. var keys = [];
  40203. var data;
  40204. var index;
  40205. if (parsedAnimation.enableBlending) {
  40206. animation.enableBlending = parsedAnimation.enableBlending;
  40207. }
  40208. if (parsedAnimation.blendingSpeed) {
  40209. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40210. }
  40211. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40212. var key = parsedAnimation.keys[index];
  40213. var inTangent;
  40214. var outTangent;
  40215. switch (dataType) {
  40216. case Animation.ANIMATIONTYPE_FLOAT:
  40217. data = key.values[0];
  40218. if (key.values.length >= 1) {
  40219. inTangent = key.values[1];
  40220. }
  40221. if (key.values.length >= 2) {
  40222. outTangent = key.values[2];
  40223. }
  40224. break;
  40225. case Animation.ANIMATIONTYPE_QUATERNION:
  40226. data = BABYLON.Quaternion.FromArray(key.values);
  40227. if (key.values.length >= 8) {
  40228. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40229. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40230. inTangent = _inTangent;
  40231. }
  40232. }
  40233. if (key.values.length >= 12) {
  40234. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40235. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40236. outTangent = _outTangent;
  40237. }
  40238. }
  40239. break;
  40240. case Animation.ANIMATIONTYPE_MATRIX:
  40241. data = BABYLON.Matrix.FromArray(key.values);
  40242. break;
  40243. case Animation.ANIMATIONTYPE_COLOR3:
  40244. data = BABYLON.Color3.FromArray(key.values);
  40245. break;
  40246. case Animation.ANIMATIONTYPE_VECTOR3:
  40247. default:
  40248. data = BABYLON.Vector3.FromArray(key.values);
  40249. break;
  40250. }
  40251. var keyData = {};
  40252. keyData.frame = key.frame;
  40253. keyData.value = data;
  40254. if (inTangent != undefined) {
  40255. keyData.inTangent = inTangent;
  40256. }
  40257. if (outTangent != undefined) {
  40258. keyData.outTangent = outTangent;
  40259. }
  40260. keys.push(keyData);
  40261. }
  40262. animation.setKeys(keys);
  40263. if (parsedAnimation.ranges) {
  40264. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40265. data = parsedAnimation.ranges[index];
  40266. animation.createRange(data.name, data.from, data.to);
  40267. }
  40268. }
  40269. return animation;
  40270. };
  40271. Animation.AppendSerializedAnimations = function (source, destination) {
  40272. if (source.animations) {
  40273. destination.animations = [];
  40274. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40275. var animation = source.animations[animationIndex];
  40276. destination.animations.push(animation.serialize());
  40277. }
  40278. }
  40279. };
  40280. Animation.AllowMatricesInterpolation = false;
  40281. // Statics
  40282. Animation._ANIMATIONTYPE_FLOAT = 0;
  40283. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40284. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40285. Animation._ANIMATIONTYPE_MATRIX = 3;
  40286. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40287. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40288. Animation._ANIMATIONTYPE_SIZE = 6;
  40289. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40290. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40291. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40292. return Animation;
  40293. }());
  40294. BABYLON.Animation = Animation;
  40295. })(BABYLON || (BABYLON = {}));
  40296. //# sourceMappingURL=babylon.animation.js.map
  40297. var BABYLON;
  40298. (function (BABYLON) {
  40299. var RuntimeAnimation = /** @class */ (function () {
  40300. function RuntimeAnimation(target, animation) {
  40301. this._offsetsCache = {};
  40302. this._highLimitsCache = {};
  40303. this._stopped = false;
  40304. this._blendingFactor = 0;
  40305. this._ratioOffset = 0;
  40306. this._animation = animation;
  40307. this._target = target;
  40308. animation._runtimeAnimations.push(this);
  40309. }
  40310. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40311. get: function () {
  40312. return this._animation;
  40313. },
  40314. enumerable: true,
  40315. configurable: true
  40316. });
  40317. RuntimeAnimation.prototype.reset = function () {
  40318. this._offsetsCache = {};
  40319. this._highLimitsCache = {};
  40320. this.currentFrame = 0;
  40321. this._blendingFactor = 0;
  40322. this._originalBlendValue = null;
  40323. };
  40324. RuntimeAnimation.prototype.isStopped = function () {
  40325. return this._stopped;
  40326. };
  40327. RuntimeAnimation.prototype.dispose = function () {
  40328. var index = this._animation.runtimeAnimations.indexOf(this);
  40329. if (index > -1) {
  40330. this._animation.runtimeAnimations.splice(index, 1);
  40331. }
  40332. };
  40333. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40334. if (typeof value === "function") {
  40335. return value();
  40336. }
  40337. return value;
  40338. };
  40339. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40340. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40341. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40342. }
  40343. this.currentFrame = currentFrame;
  40344. var keys = this._animation.getKeys();
  40345. // Try to get a hash to find the right key
  40346. 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));
  40347. if (keys[startKeyIndex].frame >= currentFrame) {
  40348. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40349. startKeyIndex--;
  40350. }
  40351. }
  40352. for (var key = startKeyIndex; key < keys.length; key++) {
  40353. var endKey = keys[key + 1];
  40354. if (endKey.frame >= currentFrame) {
  40355. var startKey = keys[key];
  40356. var startValue = this._getKeyValue(startKey.value);
  40357. var endValue = this._getKeyValue(endKey.value);
  40358. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40359. var frameDelta = endKey.frame - startKey.frame;
  40360. // gradient : percent of currentFrame between the frame inf and the frame sup
  40361. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40362. // check for easingFunction and correction of gradient
  40363. var easingFunction = this._animation.getEasingFunction();
  40364. if (easingFunction != null) {
  40365. gradient = easingFunction.ease(gradient);
  40366. }
  40367. switch (this._animation.dataType) {
  40368. // Float
  40369. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40370. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40371. switch (loopMode) {
  40372. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40373. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40374. return floatValue;
  40375. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40376. return offsetValue * repeatCount + floatValue;
  40377. }
  40378. break;
  40379. // Quaternion
  40380. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40381. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40382. switch (loopMode) {
  40383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40385. return quatValue;
  40386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40387. return quatValue.add(offsetValue.scale(repeatCount));
  40388. }
  40389. return quatValue;
  40390. // Vector3
  40391. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40392. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40393. switch (loopMode) {
  40394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40396. return vec3Value;
  40397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40398. return vec3Value.add(offsetValue.scale(repeatCount));
  40399. }
  40400. // Vector2
  40401. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40402. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40403. switch (loopMode) {
  40404. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40405. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40406. return vec2Value;
  40407. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40408. return vec2Value.add(offsetValue.scale(repeatCount));
  40409. }
  40410. // Size
  40411. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40412. switch (loopMode) {
  40413. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40414. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40415. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40416. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40417. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40418. }
  40419. // Color3
  40420. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40421. switch (loopMode) {
  40422. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40423. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40424. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40425. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40426. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40427. }
  40428. // Matrix
  40429. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40430. switch (loopMode) {
  40431. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40432. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40433. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40434. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40435. }
  40436. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40437. return startValue;
  40438. }
  40439. default:
  40440. break;
  40441. }
  40442. break;
  40443. }
  40444. }
  40445. return this._getKeyValue(keys[keys.length - 1].value);
  40446. };
  40447. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40448. if (blend === void 0) { blend = false; }
  40449. // Set value
  40450. var path;
  40451. var destination;
  40452. var targetPropertyPath = this._animation.targetPropertyPath;
  40453. if (targetPropertyPath.length > 1) {
  40454. var property = this._target[targetPropertyPath[0]];
  40455. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40456. property = property[targetPropertyPath[index]];
  40457. }
  40458. path = targetPropertyPath[targetPropertyPath.length - 1];
  40459. destination = property;
  40460. }
  40461. else {
  40462. path = targetPropertyPath[0];
  40463. destination = this._target;
  40464. }
  40465. // Blending
  40466. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40467. if (!this._originalBlendValue) {
  40468. if (destination[path].clone) {
  40469. this._originalBlendValue = destination[path].clone();
  40470. }
  40471. else {
  40472. this._originalBlendValue = destination[path];
  40473. }
  40474. }
  40475. if (this._originalBlendValue.prototype) {
  40476. if (this._originalBlendValue.prototype.Lerp) {
  40477. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40478. }
  40479. else {
  40480. destination[path] = currentValue;
  40481. }
  40482. }
  40483. else if (this._originalBlendValue.m) {
  40484. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40485. }
  40486. else {
  40487. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40488. }
  40489. this._blendingFactor += this._animation.blendingSpeed;
  40490. }
  40491. else {
  40492. destination[path] = currentValue;
  40493. }
  40494. if (this._target.markAsDirty) {
  40495. this._target.markAsDirty(this._animation.targetProperty);
  40496. }
  40497. };
  40498. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40499. var keys = this._animation.getKeys();
  40500. if (frame < keys[0].frame) {
  40501. frame = keys[0].frame;
  40502. }
  40503. else if (frame > keys[keys.length - 1].frame) {
  40504. frame = keys[keys.length - 1].frame;
  40505. }
  40506. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40507. this.setValue(currentValue);
  40508. };
  40509. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40510. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40511. this._ratioOffset = this._previousRatio - newRatio;
  40512. };
  40513. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40514. if (blend === void 0) { blend = false; }
  40515. var targetPropertyPath = this._animation.targetPropertyPath;
  40516. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40517. this._stopped = true;
  40518. return false;
  40519. }
  40520. var returnValue = true;
  40521. var keys = this._animation.getKeys();
  40522. // Adding a start key at frame 0 if missing
  40523. if (keys[0].frame !== 0) {
  40524. var newKey = { frame: 0, value: keys[0].value };
  40525. keys.splice(0, 0, newKey);
  40526. }
  40527. // Check limits
  40528. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40529. from = keys[0].frame;
  40530. }
  40531. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40532. to = keys[keys.length - 1].frame;
  40533. }
  40534. //to and from cannot be the same key
  40535. if (from === to) {
  40536. if (from > keys[0].frame) {
  40537. from--;
  40538. }
  40539. else if (to < keys[keys.length - 1].frame) {
  40540. to++;
  40541. }
  40542. }
  40543. // Compute ratio
  40544. var range = to - from;
  40545. var offsetValue;
  40546. // ratio represents the frame delta between from and to
  40547. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40548. var highLimitValue = 0;
  40549. this._previousDelay = delay;
  40550. this._previousRatio = ratio;
  40551. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40552. returnValue = false;
  40553. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40554. }
  40555. else {
  40556. // Get max value if required
  40557. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40558. var keyOffset = to.toString() + from.toString();
  40559. if (!this._offsetsCache[keyOffset]) {
  40560. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40561. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40562. switch (this._animation.dataType) {
  40563. // Float
  40564. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40565. this._offsetsCache[keyOffset] = toValue - fromValue;
  40566. break;
  40567. // Quaternion
  40568. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40569. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40570. break;
  40571. // Vector3
  40572. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40573. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40574. // Vector2
  40575. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40576. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40577. // Size
  40578. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40579. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40580. // Color3
  40581. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40582. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40583. default:
  40584. break;
  40585. }
  40586. this._highLimitsCache[keyOffset] = toValue;
  40587. }
  40588. highLimitValue = this._highLimitsCache[keyOffset];
  40589. offsetValue = this._offsetsCache[keyOffset];
  40590. }
  40591. }
  40592. if (offsetValue === undefined) {
  40593. switch (this._animation.dataType) {
  40594. // Float
  40595. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40596. offsetValue = 0;
  40597. break;
  40598. // Quaternion
  40599. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40600. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40601. break;
  40602. // Vector3
  40603. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40604. offsetValue = BABYLON.Vector3.Zero();
  40605. break;
  40606. // Vector2
  40607. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40608. offsetValue = BABYLON.Vector2.Zero();
  40609. break;
  40610. // Size
  40611. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40612. offsetValue = BABYLON.Size.Zero();
  40613. break;
  40614. // Color3
  40615. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40616. offsetValue = BABYLON.Color3.Black();
  40617. }
  40618. }
  40619. // Compute value
  40620. var repeatCount = (ratio / range) >> 0;
  40621. var currentFrame = returnValue ? from + ratio % range : to;
  40622. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40623. // Set value
  40624. this.setValue(currentValue);
  40625. // Check events
  40626. var events = this._animation.getEvents();
  40627. for (var index = 0; index < events.length; index++) {
  40628. // Make sure current frame has passed event frame and that event frame is within the current range
  40629. // Also, handle both forward and reverse animations
  40630. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40631. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40632. var event = events[index];
  40633. if (!event.isDone) {
  40634. // If event should be done only once, remove it.
  40635. if (event.onlyOnce) {
  40636. events.splice(index, 1);
  40637. index--;
  40638. }
  40639. event.isDone = true;
  40640. event.action();
  40641. } // Don't do anything if the event has already be done.
  40642. }
  40643. else if (events[index].isDone && !events[index].onlyOnce) {
  40644. // reset event, the animation is looping
  40645. events[index].isDone = false;
  40646. }
  40647. }
  40648. if (!returnValue) {
  40649. this._stopped = true;
  40650. }
  40651. return returnValue;
  40652. };
  40653. return RuntimeAnimation;
  40654. }());
  40655. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40656. })(BABYLON || (BABYLON = {}));
  40657. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40658. var BABYLON;
  40659. (function (BABYLON) {
  40660. var Animatable = /** @class */ (function () {
  40661. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40662. if (fromFrame === void 0) { fromFrame = 0; }
  40663. if (toFrame === void 0) { toFrame = 100; }
  40664. if (loopAnimation === void 0) { loopAnimation = false; }
  40665. if (speedRatio === void 0) { speedRatio = 1.0; }
  40666. this.target = target;
  40667. this.fromFrame = fromFrame;
  40668. this.toFrame = toFrame;
  40669. this.loopAnimation = loopAnimation;
  40670. this.onAnimationEnd = onAnimationEnd;
  40671. this._localDelayOffset = null;
  40672. this._pausedDelay = null;
  40673. this._runtimeAnimations = new Array();
  40674. this._paused = false;
  40675. this._speedRatio = 1;
  40676. this.animationStarted = false;
  40677. if (animations) {
  40678. this.appendAnimations(target, animations);
  40679. }
  40680. this._speedRatio = speedRatio;
  40681. this._scene = scene;
  40682. scene._activeAnimatables.push(this);
  40683. }
  40684. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40685. get: function () {
  40686. return this._speedRatio;
  40687. },
  40688. set: function (value) {
  40689. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40690. var animation = this._runtimeAnimations[index];
  40691. animation._prepareForSpeedRatioChange(value);
  40692. }
  40693. this._speedRatio = value;
  40694. },
  40695. enumerable: true,
  40696. configurable: true
  40697. });
  40698. // Methods
  40699. Animatable.prototype.getAnimations = function () {
  40700. return this._runtimeAnimations;
  40701. };
  40702. Animatable.prototype.appendAnimations = function (target, animations) {
  40703. for (var index = 0; index < animations.length; index++) {
  40704. var animation = animations[index];
  40705. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40706. }
  40707. };
  40708. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40709. var runtimeAnimations = this._runtimeAnimations;
  40710. for (var index = 0; index < runtimeAnimations.length; index++) {
  40711. if (runtimeAnimations[index].animation.targetProperty === property) {
  40712. return runtimeAnimations[index].animation;
  40713. }
  40714. }
  40715. return null;
  40716. };
  40717. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40718. var runtimeAnimations = this._runtimeAnimations;
  40719. for (var index = 0; index < runtimeAnimations.length; index++) {
  40720. if (runtimeAnimations[index].animation.targetProperty === property) {
  40721. return runtimeAnimations[index];
  40722. }
  40723. }
  40724. return null;
  40725. };
  40726. Animatable.prototype.reset = function () {
  40727. var runtimeAnimations = this._runtimeAnimations;
  40728. for (var index = 0; index < runtimeAnimations.length; index++) {
  40729. runtimeAnimations[index].reset();
  40730. }
  40731. this._localDelayOffset = null;
  40732. this._pausedDelay = null;
  40733. };
  40734. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40735. var runtimeAnimations = this._runtimeAnimations;
  40736. for (var index = 0; index < runtimeAnimations.length; index++) {
  40737. runtimeAnimations[index].animation.enableBlending = true;
  40738. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40739. }
  40740. };
  40741. Animatable.prototype.disableBlending = function () {
  40742. var runtimeAnimations = this._runtimeAnimations;
  40743. for (var index = 0; index < runtimeAnimations.length; index++) {
  40744. runtimeAnimations[index].animation.enableBlending = false;
  40745. }
  40746. };
  40747. Animatable.prototype.goToFrame = function (frame) {
  40748. var runtimeAnimations = this._runtimeAnimations;
  40749. if (runtimeAnimations[0]) {
  40750. var fps = runtimeAnimations[0].animation.framePerSecond;
  40751. var currentFrame = runtimeAnimations[0].currentFrame;
  40752. var adjustTime = frame - currentFrame;
  40753. var delay = adjustTime * 1000 / fps;
  40754. if (this._localDelayOffset === null) {
  40755. this._localDelayOffset = 0;
  40756. }
  40757. this._localDelayOffset -= delay;
  40758. }
  40759. for (var index = 0; index < runtimeAnimations.length; index++) {
  40760. runtimeAnimations[index].goToFrame(frame);
  40761. }
  40762. };
  40763. Animatable.prototype.pause = function () {
  40764. if (this._paused) {
  40765. return;
  40766. }
  40767. this._paused = true;
  40768. };
  40769. Animatable.prototype.restart = function () {
  40770. this._paused = false;
  40771. };
  40772. Animatable.prototype.stop = function (animationName) {
  40773. if (animationName) {
  40774. var idx = this._scene._activeAnimatables.indexOf(this);
  40775. if (idx > -1) {
  40776. var runtimeAnimations = this._runtimeAnimations;
  40777. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40778. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40779. continue;
  40780. }
  40781. runtimeAnimations[index].dispose();
  40782. runtimeAnimations.splice(index, 1);
  40783. }
  40784. if (runtimeAnimations.length == 0) {
  40785. this._scene._activeAnimatables.splice(idx, 1);
  40786. if (this.onAnimationEnd) {
  40787. this.onAnimationEnd();
  40788. }
  40789. }
  40790. }
  40791. }
  40792. else {
  40793. var index = this._scene._activeAnimatables.indexOf(this);
  40794. if (index > -1) {
  40795. this._scene._activeAnimatables.splice(index, 1);
  40796. var runtimeAnimations = this._runtimeAnimations;
  40797. for (var index = 0; index < runtimeAnimations.length; index++) {
  40798. runtimeAnimations[index].dispose();
  40799. }
  40800. if (this.onAnimationEnd) {
  40801. this.onAnimationEnd();
  40802. }
  40803. }
  40804. }
  40805. };
  40806. Animatable.prototype._animate = function (delay) {
  40807. if (this._paused) {
  40808. this.animationStarted = false;
  40809. if (this._pausedDelay === null) {
  40810. this._pausedDelay = delay;
  40811. }
  40812. return true;
  40813. }
  40814. if (this._localDelayOffset === null) {
  40815. this._localDelayOffset = delay;
  40816. }
  40817. else if (this._pausedDelay !== null) {
  40818. this._localDelayOffset += delay - this._pausedDelay;
  40819. this._pausedDelay = null;
  40820. }
  40821. // Animating
  40822. var running = false;
  40823. var runtimeAnimations = this._runtimeAnimations;
  40824. var index;
  40825. for (index = 0; index < runtimeAnimations.length; index++) {
  40826. var animation = runtimeAnimations[index];
  40827. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  40828. running = running || isRunning;
  40829. }
  40830. this.animationStarted = running;
  40831. if (!running) {
  40832. // Remove from active animatables
  40833. index = this._scene._activeAnimatables.indexOf(this);
  40834. this._scene._activeAnimatables.splice(index, 1);
  40835. // Dispose all runtime animations
  40836. for (index = 0; index < runtimeAnimations.length; index++) {
  40837. runtimeAnimations[index].dispose();
  40838. }
  40839. }
  40840. if (!running && this.onAnimationEnd) {
  40841. this.onAnimationEnd();
  40842. this.onAnimationEnd = null;
  40843. }
  40844. return running;
  40845. };
  40846. return Animatable;
  40847. }());
  40848. BABYLON.Animatable = Animatable;
  40849. })(BABYLON || (BABYLON = {}));
  40850. //# sourceMappingURL=babylon.animatable.js.map
  40851. var BABYLON;
  40852. (function (BABYLON) {
  40853. var EasingFunction = /** @class */ (function () {
  40854. function EasingFunction() {
  40855. // Properties
  40856. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  40857. }
  40858. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  40859. get: function () {
  40860. return EasingFunction._EASINGMODE_EASEIN;
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  40866. get: function () {
  40867. return EasingFunction._EASINGMODE_EASEOUT;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  40873. get: function () {
  40874. return EasingFunction._EASINGMODE_EASEINOUT;
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. EasingFunction.prototype.setEasingMode = function (easingMode) {
  40880. var n = Math.min(Math.max(easingMode, 0), 2);
  40881. this._easingMode = n;
  40882. };
  40883. EasingFunction.prototype.getEasingMode = function () {
  40884. return this._easingMode;
  40885. };
  40886. EasingFunction.prototype.easeInCore = function (gradient) {
  40887. throw new Error('You must implement this method');
  40888. };
  40889. EasingFunction.prototype.ease = function (gradient) {
  40890. switch (this._easingMode) {
  40891. case EasingFunction.EASINGMODE_EASEIN:
  40892. return this.easeInCore(gradient);
  40893. case EasingFunction.EASINGMODE_EASEOUT:
  40894. return (1 - this.easeInCore(1 - gradient));
  40895. }
  40896. if (gradient >= 0.5) {
  40897. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  40898. }
  40899. return (this.easeInCore(gradient * 2) * 0.5);
  40900. };
  40901. //Statics
  40902. EasingFunction._EASINGMODE_EASEIN = 0;
  40903. EasingFunction._EASINGMODE_EASEOUT = 1;
  40904. EasingFunction._EASINGMODE_EASEINOUT = 2;
  40905. return EasingFunction;
  40906. }());
  40907. BABYLON.EasingFunction = EasingFunction;
  40908. var CircleEase = /** @class */ (function (_super) {
  40909. __extends(CircleEase, _super);
  40910. function CircleEase() {
  40911. return _super !== null && _super.apply(this, arguments) || this;
  40912. }
  40913. CircleEase.prototype.easeInCore = function (gradient) {
  40914. gradient = Math.max(0, Math.min(1, gradient));
  40915. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  40916. };
  40917. return CircleEase;
  40918. }(EasingFunction));
  40919. BABYLON.CircleEase = CircleEase;
  40920. var BackEase = /** @class */ (function (_super) {
  40921. __extends(BackEase, _super);
  40922. function BackEase(amplitude) {
  40923. if (amplitude === void 0) { amplitude = 1; }
  40924. var _this = _super.call(this) || this;
  40925. _this.amplitude = amplitude;
  40926. return _this;
  40927. }
  40928. BackEase.prototype.easeInCore = function (gradient) {
  40929. var num = Math.max(0, this.amplitude);
  40930. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  40931. };
  40932. return BackEase;
  40933. }(EasingFunction));
  40934. BABYLON.BackEase = BackEase;
  40935. var BounceEase = /** @class */ (function (_super) {
  40936. __extends(BounceEase, _super);
  40937. function BounceEase(bounces, bounciness) {
  40938. if (bounces === void 0) { bounces = 3; }
  40939. if (bounciness === void 0) { bounciness = 2; }
  40940. var _this = _super.call(this) || this;
  40941. _this.bounces = bounces;
  40942. _this.bounciness = bounciness;
  40943. return _this;
  40944. }
  40945. BounceEase.prototype.easeInCore = function (gradient) {
  40946. var y = Math.max(0.0, this.bounces);
  40947. var bounciness = this.bounciness;
  40948. if (bounciness <= 1.0) {
  40949. bounciness = 1.001;
  40950. }
  40951. var num9 = Math.pow(bounciness, y);
  40952. var num5 = 1.0 - bounciness;
  40953. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  40954. var num15 = gradient * num4;
  40955. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  40956. var num3 = Math.floor(num65);
  40957. var num13 = num3 + 1.0;
  40958. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  40959. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  40960. var num7 = (num8 + num12) * 0.5;
  40961. var num6 = gradient - num7;
  40962. var num2 = num7 - num8;
  40963. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  40964. };
  40965. return BounceEase;
  40966. }(EasingFunction));
  40967. BABYLON.BounceEase = BounceEase;
  40968. var CubicEase = /** @class */ (function (_super) {
  40969. __extends(CubicEase, _super);
  40970. function CubicEase() {
  40971. return _super !== null && _super.apply(this, arguments) || this;
  40972. }
  40973. CubicEase.prototype.easeInCore = function (gradient) {
  40974. return (gradient * gradient * gradient);
  40975. };
  40976. return CubicEase;
  40977. }(EasingFunction));
  40978. BABYLON.CubicEase = CubicEase;
  40979. var ElasticEase = /** @class */ (function (_super) {
  40980. __extends(ElasticEase, _super);
  40981. function ElasticEase(oscillations, springiness) {
  40982. if (oscillations === void 0) { oscillations = 3; }
  40983. if (springiness === void 0) { springiness = 3; }
  40984. var _this = _super.call(this) || this;
  40985. _this.oscillations = oscillations;
  40986. _this.springiness = springiness;
  40987. return _this;
  40988. }
  40989. ElasticEase.prototype.easeInCore = function (gradient) {
  40990. var num2;
  40991. var num3 = Math.max(0.0, this.oscillations);
  40992. var num = Math.max(0.0, this.springiness);
  40993. if (num == 0) {
  40994. num2 = gradient;
  40995. }
  40996. else {
  40997. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  40998. }
  40999. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41000. };
  41001. return ElasticEase;
  41002. }(EasingFunction));
  41003. BABYLON.ElasticEase = ElasticEase;
  41004. var ExponentialEase = /** @class */ (function (_super) {
  41005. __extends(ExponentialEase, _super);
  41006. function ExponentialEase(exponent) {
  41007. if (exponent === void 0) { exponent = 2; }
  41008. var _this = _super.call(this) || this;
  41009. _this.exponent = exponent;
  41010. return _this;
  41011. }
  41012. ExponentialEase.prototype.easeInCore = function (gradient) {
  41013. if (this.exponent <= 0) {
  41014. return gradient;
  41015. }
  41016. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41017. };
  41018. return ExponentialEase;
  41019. }(EasingFunction));
  41020. BABYLON.ExponentialEase = ExponentialEase;
  41021. var PowerEase = /** @class */ (function (_super) {
  41022. __extends(PowerEase, _super);
  41023. function PowerEase(power) {
  41024. if (power === void 0) { power = 2; }
  41025. var _this = _super.call(this) || this;
  41026. _this.power = power;
  41027. return _this;
  41028. }
  41029. PowerEase.prototype.easeInCore = function (gradient) {
  41030. var y = Math.max(0.0, this.power);
  41031. return Math.pow(gradient, y);
  41032. };
  41033. return PowerEase;
  41034. }(EasingFunction));
  41035. BABYLON.PowerEase = PowerEase;
  41036. var QuadraticEase = /** @class */ (function (_super) {
  41037. __extends(QuadraticEase, _super);
  41038. function QuadraticEase() {
  41039. return _super !== null && _super.apply(this, arguments) || this;
  41040. }
  41041. QuadraticEase.prototype.easeInCore = function (gradient) {
  41042. return (gradient * gradient);
  41043. };
  41044. return QuadraticEase;
  41045. }(EasingFunction));
  41046. BABYLON.QuadraticEase = QuadraticEase;
  41047. var QuarticEase = /** @class */ (function (_super) {
  41048. __extends(QuarticEase, _super);
  41049. function QuarticEase() {
  41050. return _super !== null && _super.apply(this, arguments) || this;
  41051. }
  41052. QuarticEase.prototype.easeInCore = function (gradient) {
  41053. return (gradient * gradient * gradient * gradient);
  41054. };
  41055. return QuarticEase;
  41056. }(EasingFunction));
  41057. BABYLON.QuarticEase = QuarticEase;
  41058. var QuinticEase = /** @class */ (function (_super) {
  41059. __extends(QuinticEase, _super);
  41060. function QuinticEase() {
  41061. return _super !== null && _super.apply(this, arguments) || this;
  41062. }
  41063. QuinticEase.prototype.easeInCore = function (gradient) {
  41064. return (gradient * gradient * gradient * gradient * gradient);
  41065. };
  41066. return QuinticEase;
  41067. }(EasingFunction));
  41068. BABYLON.QuinticEase = QuinticEase;
  41069. var SineEase = /** @class */ (function (_super) {
  41070. __extends(SineEase, _super);
  41071. function SineEase() {
  41072. return _super !== null && _super.apply(this, arguments) || this;
  41073. }
  41074. SineEase.prototype.easeInCore = function (gradient) {
  41075. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41076. };
  41077. return SineEase;
  41078. }(EasingFunction));
  41079. BABYLON.SineEase = SineEase;
  41080. var BezierCurveEase = /** @class */ (function (_super) {
  41081. __extends(BezierCurveEase, _super);
  41082. function BezierCurveEase(x1, y1, x2, y2) {
  41083. if (x1 === void 0) { x1 = 0; }
  41084. if (y1 === void 0) { y1 = 0; }
  41085. if (x2 === void 0) { x2 = 1; }
  41086. if (y2 === void 0) { y2 = 1; }
  41087. var _this = _super.call(this) || this;
  41088. _this.x1 = x1;
  41089. _this.y1 = y1;
  41090. _this.x2 = x2;
  41091. _this.y2 = y2;
  41092. return _this;
  41093. }
  41094. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41095. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41096. };
  41097. return BezierCurveEase;
  41098. }(EasingFunction));
  41099. BABYLON.BezierCurveEase = BezierCurveEase;
  41100. })(BABYLON || (BABYLON = {}));
  41101. //# sourceMappingURL=babylon.easing.js.map
  41102. var BABYLON;
  41103. (function (BABYLON) {
  41104. var Condition = /** @class */ (function () {
  41105. function Condition(actionManager) {
  41106. this._actionManager = actionManager;
  41107. }
  41108. Condition.prototype.isValid = function () {
  41109. return true;
  41110. };
  41111. Condition.prototype._getProperty = function (propertyPath) {
  41112. return this._actionManager._getProperty(propertyPath);
  41113. };
  41114. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41115. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41116. };
  41117. Condition.prototype.serialize = function () {
  41118. };
  41119. Condition.prototype._serialize = function (serializedCondition) {
  41120. return {
  41121. type: 2,
  41122. children: [],
  41123. name: serializedCondition.name,
  41124. properties: serializedCondition.properties
  41125. };
  41126. };
  41127. return Condition;
  41128. }());
  41129. BABYLON.Condition = Condition;
  41130. var ValueCondition = /** @class */ (function (_super) {
  41131. __extends(ValueCondition, _super);
  41132. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41133. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41134. var _this = _super.call(this, actionManager) || this;
  41135. _this.propertyPath = propertyPath;
  41136. _this.value = value;
  41137. _this.operator = operator;
  41138. _this._target = target;
  41139. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41140. _this._property = _this._getProperty(_this.propertyPath);
  41141. return _this;
  41142. }
  41143. Object.defineProperty(ValueCondition, "IsEqual", {
  41144. get: function () {
  41145. return ValueCondition._IsEqual;
  41146. },
  41147. enumerable: true,
  41148. configurable: true
  41149. });
  41150. Object.defineProperty(ValueCondition, "IsDifferent", {
  41151. get: function () {
  41152. return ValueCondition._IsDifferent;
  41153. },
  41154. enumerable: true,
  41155. configurable: true
  41156. });
  41157. Object.defineProperty(ValueCondition, "IsGreater", {
  41158. get: function () {
  41159. return ValueCondition._IsGreater;
  41160. },
  41161. enumerable: true,
  41162. configurable: true
  41163. });
  41164. Object.defineProperty(ValueCondition, "IsLesser", {
  41165. get: function () {
  41166. return ValueCondition._IsLesser;
  41167. },
  41168. enumerable: true,
  41169. configurable: true
  41170. });
  41171. // Methods
  41172. ValueCondition.prototype.isValid = function () {
  41173. switch (this.operator) {
  41174. case ValueCondition.IsGreater:
  41175. return this._effectiveTarget[this._property] > this.value;
  41176. case ValueCondition.IsLesser:
  41177. return this._effectiveTarget[this._property] < this.value;
  41178. case ValueCondition.IsEqual:
  41179. case ValueCondition.IsDifferent:
  41180. var check;
  41181. if (this.value.equals) {
  41182. check = this.value.equals(this._effectiveTarget[this._property]);
  41183. }
  41184. else {
  41185. check = this.value === this._effectiveTarget[this._property];
  41186. }
  41187. return this.operator === ValueCondition.IsEqual ? check : !check;
  41188. }
  41189. return false;
  41190. };
  41191. ValueCondition.prototype.serialize = function () {
  41192. return this._serialize({
  41193. name: "ValueCondition",
  41194. properties: [
  41195. BABYLON.Action._GetTargetProperty(this._target),
  41196. { name: "propertyPath", value: this.propertyPath },
  41197. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41198. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41199. ]
  41200. });
  41201. };
  41202. ValueCondition.GetOperatorName = function (operator) {
  41203. switch (operator) {
  41204. case ValueCondition._IsEqual: return "IsEqual";
  41205. case ValueCondition._IsDifferent: return "IsDifferent";
  41206. case ValueCondition._IsGreater: return "IsGreater";
  41207. case ValueCondition._IsLesser: return "IsLesser";
  41208. default: return "";
  41209. }
  41210. };
  41211. // Statics
  41212. ValueCondition._IsEqual = 0;
  41213. ValueCondition._IsDifferent = 1;
  41214. ValueCondition._IsGreater = 2;
  41215. ValueCondition._IsLesser = 3;
  41216. return ValueCondition;
  41217. }(Condition));
  41218. BABYLON.ValueCondition = ValueCondition;
  41219. var PredicateCondition = /** @class */ (function (_super) {
  41220. __extends(PredicateCondition, _super);
  41221. function PredicateCondition(actionManager, predicate) {
  41222. var _this = _super.call(this, actionManager) || this;
  41223. _this.predicate = predicate;
  41224. return _this;
  41225. }
  41226. PredicateCondition.prototype.isValid = function () {
  41227. return this.predicate();
  41228. };
  41229. return PredicateCondition;
  41230. }(Condition));
  41231. BABYLON.PredicateCondition = PredicateCondition;
  41232. var StateCondition = /** @class */ (function (_super) {
  41233. __extends(StateCondition, _super);
  41234. function StateCondition(actionManager, target, value) {
  41235. var _this = _super.call(this, actionManager) || this;
  41236. _this.value = value;
  41237. _this._target = target;
  41238. return _this;
  41239. }
  41240. // Methods
  41241. StateCondition.prototype.isValid = function () {
  41242. return this._target.state === this.value;
  41243. };
  41244. StateCondition.prototype.serialize = function () {
  41245. return this._serialize({
  41246. name: "StateCondition",
  41247. properties: [
  41248. BABYLON.Action._GetTargetProperty(this._target),
  41249. { name: "value", value: this.value }
  41250. ]
  41251. });
  41252. };
  41253. return StateCondition;
  41254. }(Condition));
  41255. BABYLON.StateCondition = StateCondition;
  41256. })(BABYLON || (BABYLON = {}));
  41257. //# sourceMappingURL=babylon.condition.js.map
  41258. var BABYLON;
  41259. (function (BABYLON) {
  41260. var Action = /** @class */ (function () {
  41261. function Action(triggerOptions, condition) {
  41262. this.triggerOptions = triggerOptions;
  41263. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41264. if (triggerOptions.parameter) {
  41265. this.trigger = triggerOptions.trigger;
  41266. this._triggerParameter = triggerOptions.parameter;
  41267. }
  41268. else {
  41269. this.trigger = triggerOptions;
  41270. }
  41271. this._nextActiveAction = this;
  41272. this._condition = condition;
  41273. }
  41274. // Methods
  41275. Action.prototype._prepare = function () {
  41276. };
  41277. Action.prototype.getTriggerParameter = function () {
  41278. return this._triggerParameter;
  41279. };
  41280. Action.prototype._executeCurrent = function (evt) {
  41281. if (this._nextActiveAction._condition) {
  41282. var condition = this._nextActiveAction._condition;
  41283. var currentRenderId = this._actionManager.getScene().getRenderId();
  41284. // We cache the current evaluation for the current frame
  41285. if (condition._evaluationId === currentRenderId) {
  41286. if (!condition._currentResult) {
  41287. return;
  41288. }
  41289. }
  41290. else {
  41291. condition._evaluationId = currentRenderId;
  41292. if (!condition.isValid()) {
  41293. condition._currentResult = false;
  41294. return;
  41295. }
  41296. condition._currentResult = true;
  41297. }
  41298. }
  41299. this.onBeforeExecuteObservable.notifyObservers(this);
  41300. this._nextActiveAction.execute(evt);
  41301. this.skipToNextActiveAction();
  41302. };
  41303. Action.prototype.execute = function (evt) {
  41304. };
  41305. Action.prototype.skipToNextActiveAction = function () {
  41306. if (this._nextActiveAction._child) {
  41307. if (!this._nextActiveAction._child._actionManager) {
  41308. this._nextActiveAction._child._actionManager = this._actionManager;
  41309. }
  41310. this._nextActiveAction = this._nextActiveAction._child;
  41311. }
  41312. else {
  41313. this._nextActiveAction = this;
  41314. }
  41315. };
  41316. Action.prototype.then = function (action) {
  41317. this._child = action;
  41318. action._actionManager = this._actionManager;
  41319. action._prepare();
  41320. return action;
  41321. };
  41322. Action.prototype._getProperty = function (propertyPath) {
  41323. return this._actionManager._getProperty(propertyPath);
  41324. };
  41325. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41326. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41327. };
  41328. Action.prototype.serialize = function (parent) {
  41329. };
  41330. // Called by BABYLON.Action objects in serialize(...). Internal use
  41331. Action.prototype._serialize = function (serializedAction, parent) {
  41332. var serializationObject = {
  41333. type: 1,
  41334. children: [],
  41335. name: serializedAction.name,
  41336. properties: serializedAction.properties || []
  41337. };
  41338. // Serialize child
  41339. if (this._child) {
  41340. this._child.serialize(serializationObject);
  41341. }
  41342. // Check if "this" has a condition
  41343. if (this._condition) {
  41344. var serializedCondition = this._condition.serialize();
  41345. serializedCondition.children.push(serializationObject);
  41346. if (parent) {
  41347. parent.children.push(serializedCondition);
  41348. }
  41349. return serializedCondition;
  41350. }
  41351. if (parent) {
  41352. parent.children.push(serializationObject);
  41353. }
  41354. return serializationObject;
  41355. };
  41356. Action._SerializeValueAsString = function (value) {
  41357. if (typeof value === "number") {
  41358. return value.toString();
  41359. }
  41360. if (typeof value === "boolean") {
  41361. return value ? "true" : "false";
  41362. }
  41363. if (value instanceof BABYLON.Vector2) {
  41364. return value.x + ", " + value.y;
  41365. }
  41366. if (value instanceof BABYLON.Vector3) {
  41367. return value.x + ", " + value.y + ", " + value.z;
  41368. }
  41369. if (value instanceof BABYLON.Color3) {
  41370. return value.r + ", " + value.g + ", " + value.b;
  41371. }
  41372. if (value instanceof BABYLON.Color4) {
  41373. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41374. }
  41375. return value; // string
  41376. };
  41377. Action._GetTargetProperty = function (target) {
  41378. return {
  41379. name: "target",
  41380. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41381. : target instanceof BABYLON.Light ? "LightProperties"
  41382. : target instanceof BABYLON.Camera ? "CameraProperties"
  41383. : "SceneProperties",
  41384. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41385. };
  41386. };
  41387. return Action;
  41388. }());
  41389. BABYLON.Action = Action;
  41390. })(BABYLON || (BABYLON = {}));
  41391. //# sourceMappingURL=babylon.action.js.map
  41392. var BABYLON;
  41393. (function (BABYLON) {
  41394. /**
  41395. * ActionEvent is the event beint sent when an action is triggered.
  41396. */
  41397. var ActionEvent = /** @class */ (function () {
  41398. /**
  41399. * @param source The mesh or sprite that triggered the action.
  41400. * @param pointerX The X mouse cursor position at the time of the event
  41401. * @param pointerY The Y mouse cursor position at the time of the event
  41402. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41403. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41404. */
  41405. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41406. this.source = source;
  41407. this.pointerX = pointerX;
  41408. this.pointerY = pointerY;
  41409. this.meshUnderPointer = meshUnderPointer;
  41410. this.sourceEvent = sourceEvent;
  41411. this.additionalData = additionalData;
  41412. }
  41413. /**
  41414. * Helper function to auto-create an ActionEvent from a source mesh.
  41415. * @param source The source mesh that triggered the event
  41416. * @param evt {Event} The original (browser) event
  41417. */
  41418. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41419. var scene = source.getScene();
  41420. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41421. };
  41422. /**
  41423. * Helper function to auto-create an ActionEvent from a source mesh.
  41424. * @param source The source sprite that triggered the event
  41425. * @param scene Scene associated with the sprite
  41426. * @param evt {Event} The original (browser) event
  41427. */
  41428. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41429. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41430. };
  41431. /**
  41432. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41433. * @param scene the scene where the event occurred
  41434. * @param evt {Event} The original (browser) event
  41435. */
  41436. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41437. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41438. };
  41439. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41440. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41441. };
  41442. return ActionEvent;
  41443. }());
  41444. BABYLON.ActionEvent = ActionEvent;
  41445. /**
  41446. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41447. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41448. */
  41449. var ActionManager = /** @class */ (function () {
  41450. function ActionManager(scene) {
  41451. // Members
  41452. this.actions = new Array();
  41453. this.hoverCursor = '';
  41454. this._scene = scene;
  41455. scene._actionManagers.push(this);
  41456. }
  41457. Object.defineProperty(ActionManager, "NothingTrigger", {
  41458. get: function () {
  41459. return ActionManager._NothingTrigger;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41465. get: function () {
  41466. return ActionManager._OnPickTrigger;
  41467. },
  41468. enumerable: true,
  41469. configurable: true
  41470. });
  41471. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41472. get: function () {
  41473. return ActionManager._OnLeftPickTrigger;
  41474. },
  41475. enumerable: true,
  41476. configurable: true
  41477. });
  41478. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41479. get: function () {
  41480. return ActionManager._OnRightPickTrigger;
  41481. },
  41482. enumerable: true,
  41483. configurable: true
  41484. });
  41485. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41486. get: function () {
  41487. return ActionManager._OnCenterPickTrigger;
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41493. get: function () {
  41494. return ActionManager._OnPickDownTrigger;
  41495. },
  41496. enumerable: true,
  41497. configurable: true
  41498. });
  41499. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41500. get: function () {
  41501. return ActionManager._OnDoublePickTrigger;
  41502. },
  41503. enumerable: true,
  41504. configurable: true
  41505. });
  41506. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41507. get: function () {
  41508. return ActionManager._OnPickUpTrigger;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41514. /// This trigger will only be raised if you also declared a OnPickDown
  41515. get: function () {
  41516. return ActionManager._OnPickOutTrigger;
  41517. },
  41518. enumerable: true,
  41519. configurable: true
  41520. });
  41521. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41522. get: function () {
  41523. return ActionManager._OnLongPressTrigger;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41529. get: function () {
  41530. return ActionManager._OnPointerOverTrigger;
  41531. },
  41532. enumerable: true,
  41533. configurable: true
  41534. });
  41535. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41536. get: function () {
  41537. return ActionManager._OnPointerOutTrigger;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41543. get: function () {
  41544. return ActionManager._OnEveryFrameTrigger;
  41545. },
  41546. enumerable: true,
  41547. configurable: true
  41548. });
  41549. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41550. get: function () {
  41551. return ActionManager._OnIntersectionEnterTrigger;
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41557. get: function () {
  41558. return ActionManager._OnIntersectionExitTrigger;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41564. get: function () {
  41565. return ActionManager._OnKeyDownTrigger;
  41566. },
  41567. enumerable: true,
  41568. configurable: true
  41569. });
  41570. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41571. get: function () {
  41572. return ActionManager._OnKeyUpTrigger;
  41573. },
  41574. enumerable: true,
  41575. configurable: true
  41576. });
  41577. // Methods
  41578. ActionManager.prototype.dispose = function () {
  41579. var index = this._scene._actionManagers.indexOf(this);
  41580. for (var i = 0; i < this.actions.length; i++) {
  41581. var action = this.actions[i];
  41582. ActionManager.Triggers[action.trigger]--;
  41583. if (ActionManager.Triggers[action.trigger] === 0) {
  41584. delete ActionManager.Triggers[action.trigger];
  41585. }
  41586. }
  41587. if (index > -1) {
  41588. this._scene._actionManagers.splice(index, 1);
  41589. }
  41590. };
  41591. ActionManager.prototype.getScene = function () {
  41592. return this._scene;
  41593. };
  41594. /**
  41595. * Does this action manager handles actions of any of the given triggers
  41596. * @param {number[]} triggers - the triggers to be tested
  41597. * @return {boolean} whether one (or more) of the triggers is handeled
  41598. */
  41599. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41600. for (var index = 0; index < this.actions.length; index++) {
  41601. var action = this.actions[index];
  41602. if (triggers.indexOf(action.trigger) > -1) {
  41603. return true;
  41604. }
  41605. }
  41606. return false;
  41607. };
  41608. /**
  41609. * Does this action manager handles actions of a given trigger
  41610. * @param {number} trigger - the trigger to be tested
  41611. * @return {boolean} whether the trigger is handeled
  41612. */
  41613. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41614. for (var index = 0; index < this.actions.length; index++) {
  41615. var action = this.actions[index];
  41616. if (action.trigger === trigger) {
  41617. return true;
  41618. }
  41619. }
  41620. return false;
  41621. };
  41622. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41623. /**
  41624. * Does this action manager has pointer triggers
  41625. * @return {boolean} whether or not it has pointer triggers
  41626. */
  41627. get: function () {
  41628. for (var index = 0; index < this.actions.length; index++) {
  41629. var action = this.actions[index];
  41630. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41631. return true;
  41632. }
  41633. }
  41634. return false;
  41635. },
  41636. enumerable: true,
  41637. configurable: true
  41638. });
  41639. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41640. /**
  41641. * Does this action manager has pick triggers
  41642. * @return {boolean} whether or not it has pick triggers
  41643. */
  41644. get: function () {
  41645. for (var index = 0; index < this.actions.length; index++) {
  41646. var action = this.actions[index];
  41647. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41648. return true;
  41649. }
  41650. }
  41651. return false;
  41652. },
  41653. enumerable: true,
  41654. configurable: true
  41655. });
  41656. Object.defineProperty(ActionManager, "HasTriggers", {
  41657. /**
  41658. * Does exist one action manager with at least one trigger
  41659. * @return {boolean} whether or not it exists one action manager with one trigger
  41660. **/
  41661. get: function () {
  41662. for (var t in ActionManager.Triggers) {
  41663. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41664. return true;
  41665. }
  41666. }
  41667. return false;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41673. /**
  41674. * Does exist one action manager with at least one pick trigger
  41675. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41676. **/
  41677. get: function () {
  41678. for (var t in ActionManager.Triggers) {
  41679. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41680. var t_int = parseInt(t);
  41681. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41682. return true;
  41683. }
  41684. }
  41685. }
  41686. return false;
  41687. },
  41688. enumerable: true,
  41689. configurable: true
  41690. });
  41691. /**
  41692. * Does exist one action manager that handles actions of a given trigger
  41693. * @param {number} trigger - the trigger to be tested
  41694. * @return {boolean} whether the trigger is handeled by at least one action manager
  41695. **/
  41696. ActionManager.HasSpecificTrigger = function (trigger) {
  41697. for (var t in ActionManager.Triggers) {
  41698. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41699. var t_int = parseInt(t);
  41700. if (t_int === trigger) {
  41701. return true;
  41702. }
  41703. }
  41704. }
  41705. return false;
  41706. };
  41707. /**
  41708. * Registers an action to this action manager
  41709. * @param {BABYLON.Action} action - the action to be registered
  41710. * @return {BABYLON.Action} the action amended (prepared) after registration
  41711. */
  41712. ActionManager.prototype.registerAction = function (action) {
  41713. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41714. if (this.getScene().actionManager !== this) {
  41715. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41716. return null;
  41717. }
  41718. }
  41719. this.actions.push(action);
  41720. if (ActionManager.Triggers[action.trigger]) {
  41721. ActionManager.Triggers[action.trigger]++;
  41722. }
  41723. else {
  41724. ActionManager.Triggers[action.trigger] = 1;
  41725. }
  41726. action._actionManager = this;
  41727. action._prepare();
  41728. return action;
  41729. };
  41730. /**
  41731. * Process a specific trigger
  41732. * @param {number} trigger - the trigger to process
  41733. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41734. */
  41735. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41736. for (var index = 0; index < this.actions.length; index++) {
  41737. var action = this.actions[index];
  41738. if (action.trigger === trigger) {
  41739. if (evt) {
  41740. if (trigger === ActionManager.OnKeyUpTrigger
  41741. || trigger === ActionManager.OnKeyDownTrigger) {
  41742. var parameter = action.getTriggerParameter();
  41743. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41744. if (!parameter.toLowerCase) {
  41745. continue;
  41746. }
  41747. var lowerCase = parameter.toLowerCase();
  41748. if (lowerCase !== evt.sourceEvent.key) {
  41749. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41750. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41751. if (actualkey !== lowerCase) {
  41752. continue;
  41753. }
  41754. }
  41755. }
  41756. }
  41757. }
  41758. action._executeCurrent(evt);
  41759. }
  41760. }
  41761. };
  41762. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41763. var properties = propertyPath.split(".");
  41764. for (var index = 0; index < properties.length - 1; index++) {
  41765. target = target[properties[index]];
  41766. }
  41767. return target;
  41768. };
  41769. ActionManager.prototype._getProperty = function (propertyPath) {
  41770. var properties = propertyPath.split(".");
  41771. return properties[properties.length - 1];
  41772. };
  41773. ActionManager.prototype.serialize = function (name) {
  41774. var root = {
  41775. children: new Array(),
  41776. name: name,
  41777. type: 3,
  41778. properties: new Array() // Empty for root but required
  41779. };
  41780. for (var i = 0; i < this.actions.length; i++) {
  41781. var triggerObject = {
  41782. type: 0,
  41783. children: new Array(),
  41784. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41785. properties: new Array()
  41786. };
  41787. var triggerOptions = this.actions[i].triggerOptions;
  41788. if (triggerOptions && typeof triggerOptions !== "number") {
  41789. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41790. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  41791. }
  41792. else {
  41793. var parameter = {};
  41794. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  41795. if (triggerOptions.parameter.mesh) {
  41796. parameter._meshId = triggerOptions.parameter.mesh.id;
  41797. }
  41798. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  41799. }
  41800. }
  41801. // Serialize child action, recursively
  41802. this.actions[i].serialize(triggerObject);
  41803. // Add serialized trigger
  41804. root.children.push(triggerObject);
  41805. }
  41806. return root;
  41807. };
  41808. ActionManager.Parse = function (parsedActions, object, scene) {
  41809. var actionManager = new BABYLON.ActionManager(scene);
  41810. if (object === null)
  41811. scene.actionManager = actionManager;
  41812. else
  41813. object.actionManager = actionManager;
  41814. // instanciate a new object
  41815. var instanciate = function (name, params) {
  41816. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  41817. newInstance.constructor.apply(newInstance, params);
  41818. return newInstance;
  41819. };
  41820. var parseParameter = function (name, value, target, propertyPath) {
  41821. if (propertyPath === null) {
  41822. // String, boolean or float
  41823. var floatValue = parseFloat(value);
  41824. if (value === "true" || value === "false")
  41825. return value === "true";
  41826. else
  41827. return isNaN(floatValue) ? value : floatValue;
  41828. }
  41829. var effectiveTarget = propertyPath.split(".");
  41830. var values = value.split(",");
  41831. // Get effective Target
  41832. for (var i = 0; i < effectiveTarget.length; i++) {
  41833. target = target[effectiveTarget[i]];
  41834. }
  41835. // Return appropriate value with its type
  41836. if (typeof (target) === "boolean")
  41837. return values[0] === "true";
  41838. if (typeof (target) === "string")
  41839. return values[0];
  41840. // Parameters with multiple values such as Vector3 etc.
  41841. var split = new Array();
  41842. for (var i = 0; i < values.length; i++)
  41843. split.push(parseFloat(values[i]));
  41844. if (target instanceof BABYLON.Vector3)
  41845. return BABYLON.Vector3.FromArray(split);
  41846. if (target instanceof BABYLON.Vector4)
  41847. return BABYLON.Vector4.FromArray(split);
  41848. if (target instanceof BABYLON.Color3)
  41849. return BABYLON.Color3.FromArray(split);
  41850. if (target instanceof BABYLON.Color4)
  41851. return BABYLON.Color4.FromArray(split);
  41852. return parseFloat(values[0]);
  41853. };
  41854. // traverse graph per trigger
  41855. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  41856. if (combineArray === void 0) { combineArray = null; }
  41857. if (parsedAction.detached)
  41858. return;
  41859. var parameters = new Array();
  41860. var target = null;
  41861. var propertyPath = null;
  41862. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  41863. // Parameters
  41864. if (parsedAction.type === 2)
  41865. parameters.push(actionManager);
  41866. else
  41867. parameters.push(trigger);
  41868. if (combine) {
  41869. var actions = new Array();
  41870. for (var j = 0; j < parsedAction.combine.length; j++) {
  41871. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  41872. }
  41873. parameters.push(actions);
  41874. }
  41875. else {
  41876. for (var i = 0; i < parsedAction.properties.length; i++) {
  41877. var value = parsedAction.properties[i].value;
  41878. var name = parsedAction.properties[i].name;
  41879. var targetType = parsedAction.properties[i].targetType;
  41880. if (name === "target")
  41881. if (targetType !== null && targetType === "SceneProperties")
  41882. value = target = scene;
  41883. else
  41884. value = target = scene.getNodeByName(value);
  41885. else if (name === "parent")
  41886. value = scene.getNodeByName(value);
  41887. else if (name === "sound")
  41888. value = scene.getSoundByName(value);
  41889. else if (name !== "propertyPath") {
  41890. if (parsedAction.type === 2 && name === "operator")
  41891. value = BABYLON.ValueCondition[value];
  41892. else
  41893. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  41894. }
  41895. else {
  41896. propertyPath = value;
  41897. }
  41898. parameters.push(value);
  41899. }
  41900. }
  41901. if (combineArray === null) {
  41902. parameters.push(condition);
  41903. }
  41904. else {
  41905. parameters.push(null);
  41906. }
  41907. // If interpolate value action
  41908. if (parsedAction.name === "InterpolateValueAction") {
  41909. var param = parameters[parameters.length - 2];
  41910. parameters[parameters.length - 1] = param;
  41911. parameters[parameters.length - 2] = condition;
  41912. }
  41913. // Action or condition(s) and not CombineAction
  41914. var newAction = instanciate(parsedAction.name, parameters);
  41915. if (newAction instanceof BABYLON.Condition && condition !== null) {
  41916. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  41917. if (action)
  41918. action.then(nothing);
  41919. else
  41920. actionManager.registerAction(nothing);
  41921. action = nothing;
  41922. }
  41923. if (combineArray === null) {
  41924. if (newAction instanceof BABYLON.Condition) {
  41925. condition = newAction;
  41926. newAction = action;
  41927. }
  41928. else {
  41929. condition = null;
  41930. if (action)
  41931. action.then(newAction);
  41932. else
  41933. actionManager.registerAction(newAction);
  41934. }
  41935. }
  41936. else {
  41937. combineArray.push(newAction);
  41938. }
  41939. for (var i = 0; i < parsedAction.children.length; i++)
  41940. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  41941. };
  41942. // triggers
  41943. for (var i = 0; i < parsedActions.children.length; i++) {
  41944. var triggerParams;
  41945. var trigger = parsedActions.children[i];
  41946. if (trigger.properties.length > 0) {
  41947. var param = trigger.properties[0].value;
  41948. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  41949. if (value._meshId) {
  41950. value.mesh = scene.getMeshByID(value._meshId);
  41951. }
  41952. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  41953. }
  41954. else
  41955. triggerParams = ActionManager[trigger.name];
  41956. for (var j = 0; j < trigger.children.length; j++) {
  41957. if (!trigger.detached)
  41958. traverse(trigger.children[j], triggerParams, null, null);
  41959. }
  41960. }
  41961. };
  41962. ActionManager.GetTriggerName = function (trigger) {
  41963. switch (trigger) {
  41964. case 0: return "NothingTrigger";
  41965. case 1: return "OnPickTrigger";
  41966. case 2: return "OnLeftPickTrigger";
  41967. case 3: return "OnRightPickTrigger";
  41968. case 4: return "OnCenterPickTrigger";
  41969. case 5: return "OnPickDownTrigger";
  41970. case 6: return "OnPickUpTrigger";
  41971. case 7: return "OnLongPressTrigger";
  41972. case 8: return "OnPointerOverTrigger";
  41973. case 9: return "OnPointerOutTrigger";
  41974. case 10: return "OnEveryFrameTrigger";
  41975. case 11: return "OnIntersectionEnterTrigger";
  41976. case 12: return "OnIntersectionExitTrigger";
  41977. case 13: return "OnKeyDownTrigger";
  41978. case 14: return "OnKeyUpTrigger";
  41979. case 15: return "OnPickOutTrigger";
  41980. default: return "";
  41981. }
  41982. };
  41983. // Statics
  41984. ActionManager._NothingTrigger = 0;
  41985. ActionManager._OnPickTrigger = 1;
  41986. ActionManager._OnLeftPickTrigger = 2;
  41987. ActionManager._OnRightPickTrigger = 3;
  41988. ActionManager._OnCenterPickTrigger = 4;
  41989. ActionManager._OnPickDownTrigger = 5;
  41990. ActionManager._OnDoublePickTrigger = 6;
  41991. ActionManager._OnPickUpTrigger = 7;
  41992. ActionManager._OnLongPressTrigger = 8;
  41993. ActionManager._OnPointerOverTrigger = 9;
  41994. ActionManager._OnPointerOutTrigger = 10;
  41995. ActionManager._OnEveryFrameTrigger = 11;
  41996. ActionManager._OnIntersectionEnterTrigger = 12;
  41997. ActionManager._OnIntersectionExitTrigger = 13;
  41998. ActionManager._OnKeyDownTrigger = 14;
  41999. ActionManager._OnKeyUpTrigger = 15;
  42000. ActionManager._OnPickOutTrigger = 16;
  42001. ActionManager.Triggers = {};
  42002. return ActionManager;
  42003. }());
  42004. BABYLON.ActionManager = ActionManager;
  42005. })(BABYLON || (BABYLON = {}));
  42006. //# sourceMappingURL=babylon.actionManager.js.map
  42007. var BABYLON;
  42008. (function (BABYLON) {
  42009. var InterpolateValueAction = /** @class */ (function (_super) {
  42010. __extends(InterpolateValueAction, _super);
  42011. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42012. if (duration === void 0) { duration = 1000; }
  42013. var _this = _super.call(this, triggerOptions, condition) || this;
  42014. _this.propertyPath = propertyPath;
  42015. _this.value = value;
  42016. _this.duration = duration;
  42017. _this.stopOtherAnimations = stopOtherAnimations;
  42018. _this.onInterpolationDone = onInterpolationDone;
  42019. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42020. _this._target = _this._effectiveTarget = target;
  42021. return _this;
  42022. }
  42023. InterpolateValueAction.prototype._prepare = function () {
  42024. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42025. this._property = this._getProperty(this.propertyPath);
  42026. };
  42027. InterpolateValueAction.prototype.execute = function () {
  42028. var _this = this;
  42029. var scene = this._actionManager.getScene();
  42030. var keys = [
  42031. {
  42032. frame: 0,
  42033. value: this._effectiveTarget[this._property]
  42034. }, {
  42035. frame: 100,
  42036. value: this.value
  42037. }
  42038. ];
  42039. var dataType;
  42040. if (typeof this.value === "number") {
  42041. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42042. }
  42043. else if (this.value instanceof BABYLON.Color3) {
  42044. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42045. }
  42046. else if (this.value instanceof BABYLON.Vector3) {
  42047. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42048. }
  42049. else if (this.value instanceof BABYLON.Matrix) {
  42050. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42051. }
  42052. else if (this.value instanceof BABYLON.Quaternion) {
  42053. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42054. }
  42055. else {
  42056. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42057. return;
  42058. }
  42059. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42060. animation.setKeys(keys);
  42061. if (this.stopOtherAnimations) {
  42062. scene.stopAnimation(this._effectiveTarget);
  42063. }
  42064. var wrapper = function () {
  42065. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42066. if (_this.onInterpolationDone) {
  42067. _this.onInterpolationDone();
  42068. }
  42069. };
  42070. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42071. };
  42072. InterpolateValueAction.prototype.serialize = function (parent) {
  42073. return _super.prototype._serialize.call(this, {
  42074. name: "InterpolateValueAction",
  42075. properties: [
  42076. BABYLON.Action._GetTargetProperty(this._target),
  42077. { name: "propertyPath", value: this.propertyPath },
  42078. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42079. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42080. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42081. ]
  42082. }, parent);
  42083. };
  42084. return InterpolateValueAction;
  42085. }(BABYLON.Action));
  42086. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42087. })(BABYLON || (BABYLON = {}));
  42088. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42089. var BABYLON;
  42090. (function (BABYLON) {
  42091. var SwitchBooleanAction = /** @class */ (function (_super) {
  42092. __extends(SwitchBooleanAction, _super);
  42093. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42094. var _this = _super.call(this, triggerOptions, condition) || this;
  42095. _this.propertyPath = propertyPath;
  42096. _this._target = _this._effectiveTarget = target;
  42097. return _this;
  42098. }
  42099. SwitchBooleanAction.prototype._prepare = function () {
  42100. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42101. this._property = this._getProperty(this.propertyPath);
  42102. };
  42103. SwitchBooleanAction.prototype.execute = function () {
  42104. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42105. };
  42106. SwitchBooleanAction.prototype.serialize = function (parent) {
  42107. return _super.prototype._serialize.call(this, {
  42108. name: "SwitchBooleanAction",
  42109. properties: [
  42110. BABYLON.Action._GetTargetProperty(this._target),
  42111. { name: "propertyPath", value: this.propertyPath }
  42112. ]
  42113. }, parent);
  42114. };
  42115. return SwitchBooleanAction;
  42116. }(BABYLON.Action));
  42117. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42118. var SetStateAction = /** @class */ (function (_super) {
  42119. __extends(SetStateAction, _super);
  42120. function SetStateAction(triggerOptions, target, value, condition) {
  42121. var _this = _super.call(this, triggerOptions, condition) || this;
  42122. _this.value = value;
  42123. _this._target = target;
  42124. return _this;
  42125. }
  42126. SetStateAction.prototype.execute = function () {
  42127. this._target.state = this.value;
  42128. };
  42129. SetStateAction.prototype.serialize = function (parent) {
  42130. return _super.prototype._serialize.call(this, {
  42131. name: "SetStateAction",
  42132. properties: [
  42133. BABYLON.Action._GetTargetProperty(this._target),
  42134. { name: "value", value: this.value }
  42135. ]
  42136. }, parent);
  42137. };
  42138. return SetStateAction;
  42139. }(BABYLON.Action));
  42140. BABYLON.SetStateAction = SetStateAction;
  42141. var SetValueAction = /** @class */ (function (_super) {
  42142. __extends(SetValueAction, _super);
  42143. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42144. var _this = _super.call(this, triggerOptions, condition) || this;
  42145. _this.propertyPath = propertyPath;
  42146. _this.value = value;
  42147. _this._target = _this._effectiveTarget = target;
  42148. return _this;
  42149. }
  42150. SetValueAction.prototype._prepare = function () {
  42151. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42152. this._property = this._getProperty(this.propertyPath);
  42153. };
  42154. SetValueAction.prototype.execute = function () {
  42155. this._effectiveTarget[this._property] = this.value;
  42156. if (this._target.markAsDirty) {
  42157. this._target.markAsDirty(this._property);
  42158. }
  42159. };
  42160. SetValueAction.prototype.serialize = function (parent) {
  42161. return _super.prototype._serialize.call(this, {
  42162. name: "SetValueAction",
  42163. properties: [
  42164. BABYLON.Action._GetTargetProperty(this._target),
  42165. { name: "propertyPath", value: this.propertyPath },
  42166. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42167. ]
  42168. }, parent);
  42169. };
  42170. return SetValueAction;
  42171. }(BABYLON.Action));
  42172. BABYLON.SetValueAction = SetValueAction;
  42173. var IncrementValueAction = /** @class */ (function (_super) {
  42174. __extends(IncrementValueAction, _super);
  42175. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42176. var _this = _super.call(this, triggerOptions, condition) || this;
  42177. _this.propertyPath = propertyPath;
  42178. _this.value = value;
  42179. _this._target = _this._effectiveTarget = target;
  42180. return _this;
  42181. }
  42182. IncrementValueAction.prototype._prepare = function () {
  42183. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42184. this._property = this._getProperty(this.propertyPath);
  42185. if (typeof this._effectiveTarget[this._property] !== "number") {
  42186. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42187. }
  42188. };
  42189. IncrementValueAction.prototype.execute = function () {
  42190. this._effectiveTarget[this._property] += this.value;
  42191. if (this._target.markAsDirty) {
  42192. this._target.markAsDirty(this._property);
  42193. }
  42194. };
  42195. IncrementValueAction.prototype.serialize = function (parent) {
  42196. return _super.prototype._serialize.call(this, {
  42197. name: "IncrementValueAction",
  42198. properties: [
  42199. BABYLON.Action._GetTargetProperty(this._target),
  42200. { name: "propertyPath", value: this.propertyPath },
  42201. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42202. ]
  42203. }, parent);
  42204. };
  42205. return IncrementValueAction;
  42206. }(BABYLON.Action));
  42207. BABYLON.IncrementValueAction = IncrementValueAction;
  42208. var PlayAnimationAction = /** @class */ (function (_super) {
  42209. __extends(PlayAnimationAction, _super);
  42210. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42211. var _this = _super.call(this, triggerOptions, condition) || this;
  42212. _this.from = from;
  42213. _this.to = to;
  42214. _this.loop = loop;
  42215. _this._target = target;
  42216. return _this;
  42217. }
  42218. PlayAnimationAction.prototype._prepare = function () {
  42219. };
  42220. PlayAnimationAction.prototype.execute = function () {
  42221. var scene = this._actionManager.getScene();
  42222. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42223. };
  42224. PlayAnimationAction.prototype.serialize = function (parent) {
  42225. return _super.prototype._serialize.call(this, {
  42226. name: "PlayAnimationAction",
  42227. properties: [
  42228. BABYLON.Action._GetTargetProperty(this._target),
  42229. { name: "from", value: String(this.from) },
  42230. { name: "to", value: String(this.to) },
  42231. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42232. ]
  42233. }, parent);
  42234. };
  42235. return PlayAnimationAction;
  42236. }(BABYLON.Action));
  42237. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42238. var StopAnimationAction = /** @class */ (function (_super) {
  42239. __extends(StopAnimationAction, _super);
  42240. function StopAnimationAction(triggerOptions, target, condition) {
  42241. var _this = _super.call(this, triggerOptions, condition) || this;
  42242. _this._target = target;
  42243. return _this;
  42244. }
  42245. StopAnimationAction.prototype._prepare = function () {
  42246. };
  42247. StopAnimationAction.prototype.execute = function () {
  42248. var scene = this._actionManager.getScene();
  42249. scene.stopAnimation(this._target);
  42250. };
  42251. StopAnimationAction.prototype.serialize = function (parent) {
  42252. return _super.prototype._serialize.call(this, {
  42253. name: "StopAnimationAction",
  42254. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42255. }, parent);
  42256. };
  42257. return StopAnimationAction;
  42258. }(BABYLON.Action));
  42259. BABYLON.StopAnimationAction = StopAnimationAction;
  42260. var DoNothingAction = /** @class */ (function (_super) {
  42261. __extends(DoNothingAction, _super);
  42262. function DoNothingAction(triggerOptions, condition) {
  42263. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42264. return _super.call(this, triggerOptions, condition) || this;
  42265. }
  42266. DoNothingAction.prototype.execute = function () {
  42267. };
  42268. DoNothingAction.prototype.serialize = function (parent) {
  42269. return _super.prototype._serialize.call(this, {
  42270. name: "DoNothingAction",
  42271. properties: []
  42272. }, parent);
  42273. };
  42274. return DoNothingAction;
  42275. }(BABYLON.Action));
  42276. BABYLON.DoNothingAction = DoNothingAction;
  42277. var CombineAction = /** @class */ (function (_super) {
  42278. __extends(CombineAction, _super);
  42279. function CombineAction(triggerOptions, children, condition) {
  42280. var _this = _super.call(this, triggerOptions, condition) || this;
  42281. _this.children = children;
  42282. return _this;
  42283. }
  42284. CombineAction.prototype._prepare = function () {
  42285. for (var index = 0; index < this.children.length; index++) {
  42286. this.children[index]._actionManager = this._actionManager;
  42287. this.children[index]._prepare();
  42288. }
  42289. };
  42290. CombineAction.prototype.execute = function (evt) {
  42291. for (var index = 0; index < this.children.length; index++) {
  42292. this.children[index].execute(evt);
  42293. }
  42294. };
  42295. CombineAction.prototype.serialize = function (parent) {
  42296. var serializationObject = _super.prototype._serialize.call(this, {
  42297. name: "CombineAction",
  42298. properties: [],
  42299. combine: []
  42300. }, parent);
  42301. for (var i = 0; i < this.children.length; i++) {
  42302. serializationObject.combine.push(this.children[i].serialize(null));
  42303. }
  42304. return serializationObject;
  42305. };
  42306. return CombineAction;
  42307. }(BABYLON.Action));
  42308. BABYLON.CombineAction = CombineAction;
  42309. var ExecuteCodeAction = /** @class */ (function (_super) {
  42310. __extends(ExecuteCodeAction, _super);
  42311. function ExecuteCodeAction(triggerOptions, func, condition) {
  42312. var _this = _super.call(this, triggerOptions, condition) || this;
  42313. _this.func = func;
  42314. return _this;
  42315. }
  42316. ExecuteCodeAction.prototype.execute = function (evt) {
  42317. this.func(evt);
  42318. };
  42319. return ExecuteCodeAction;
  42320. }(BABYLON.Action));
  42321. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42322. var SetParentAction = /** @class */ (function (_super) {
  42323. __extends(SetParentAction, _super);
  42324. function SetParentAction(triggerOptions, target, parent, condition) {
  42325. var _this = _super.call(this, triggerOptions, condition) || this;
  42326. _this._target = target;
  42327. _this._parent = parent;
  42328. return _this;
  42329. }
  42330. SetParentAction.prototype._prepare = function () {
  42331. };
  42332. SetParentAction.prototype.execute = function () {
  42333. if (this._target.parent === this._parent) {
  42334. return;
  42335. }
  42336. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42337. invertParentWorldMatrix.invert();
  42338. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42339. this._target.parent = this._parent;
  42340. };
  42341. SetParentAction.prototype.serialize = function (parent) {
  42342. return _super.prototype._serialize.call(this, {
  42343. name: "SetParentAction",
  42344. properties: [
  42345. BABYLON.Action._GetTargetProperty(this._target),
  42346. BABYLON.Action._GetTargetProperty(this._parent),
  42347. ]
  42348. }, parent);
  42349. };
  42350. return SetParentAction;
  42351. }(BABYLON.Action));
  42352. BABYLON.SetParentAction = SetParentAction;
  42353. var PlaySoundAction = /** @class */ (function (_super) {
  42354. __extends(PlaySoundAction, _super);
  42355. function PlaySoundAction(triggerOptions, sound, condition) {
  42356. var _this = _super.call(this, triggerOptions, condition) || this;
  42357. _this._sound = sound;
  42358. return _this;
  42359. }
  42360. PlaySoundAction.prototype._prepare = function () {
  42361. };
  42362. PlaySoundAction.prototype.execute = function () {
  42363. if (this._sound !== undefined)
  42364. this._sound.play();
  42365. };
  42366. PlaySoundAction.prototype.serialize = function (parent) {
  42367. return _super.prototype._serialize.call(this, {
  42368. name: "PlaySoundAction",
  42369. properties: [{ name: "sound", value: this._sound.name }]
  42370. }, parent);
  42371. };
  42372. return PlaySoundAction;
  42373. }(BABYLON.Action));
  42374. BABYLON.PlaySoundAction = PlaySoundAction;
  42375. var StopSoundAction = /** @class */ (function (_super) {
  42376. __extends(StopSoundAction, _super);
  42377. function StopSoundAction(triggerOptions, sound, condition) {
  42378. var _this = _super.call(this, triggerOptions, condition) || this;
  42379. _this._sound = sound;
  42380. return _this;
  42381. }
  42382. StopSoundAction.prototype._prepare = function () {
  42383. };
  42384. StopSoundAction.prototype.execute = function () {
  42385. if (this._sound !== undefined)
  42386. this._sound.stop();
  42387. };
  42388. StopSoundAction.prototype.serialize = function (parent) {
  42389. return _super.prototype._serialize.call(this, {
  42390. name: "StopSoundAction",
  42391. properties: [{ name: "sound", value: this._sound.name }]
  42392. }, parent);
  42393. };
  42394. return StopSoundAction;
  42395. }(BABYLON.Action));
  42396. BABYLON.StopSoundAction = StopSoundAction;
  42397. })(BABYLON || (BABYLON = {}));
  42398. //# sourceMappingURL=babylon.directActions.js.map
  42399. var BABYLON;
  42400. (function (BABYLON) {
  42401. var SpriteManager = /** @class */ (function () {
  42402. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42403. if (epsilon === void 0) { epsilon = 0.01; }
  42404. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42405. this.name = name;
  42406. this.sprites = new Array();
  42407. this.renderingGroupId = 0;
  42408. this.layerMask = 0x0FFFFFFF;
  42409. this.fogEnabled = true;
  42410. this.isPickable = false;
  42411. /**
  42412. * An event triggered when the manager is disposed.
  42413. * @type {BABYLON.Observable}
  42414. */
  42415. this.onDisposeObservable = new BABYLON.Observable();
  42416. this._vertexBuffers = {};
  42417. this._capacity = capacity;
  42418. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42419. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42420. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42421. if (cellSize.width && cellSize.height) {
  42422. this.cellWidth = cellSize.width;
  42423. this.cellHeight = cellSize.height;
  42424. }
  42425. else if (cellSize !== undefined) {
  42426. this.cellWidth = cellSize;
  42427. this.cellHeight = cellSize;
  42428. }
  42429. else {
  42430. return;
  42431. }
  42432. this._epsilon = epsilon;
  42433. this._scene = scene;
  42434. this._scene.spriteManagers.push(this);
  42435. var indices = [];
  42436. var index = 0;
  42437. for (var count = 0; count < capacity; count++) {
  42438. indices.push(index);
  42439. indices.push(index + 1);
  42440. indices.push(index + 2);
  42441. indices.push(index);
  42442. indices.push(index + 2);
  42443. indices.push(index + 3);
  42444. index += 4;
  42445. }
  42446. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42447. // VBO
  42448. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42449. this._vertexData = new Float32Array(capacity * 16 * 4);
  42450. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42451. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42452. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42453. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42454. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42455. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42456. this._vertexBuffers["options"] = options;
  42457. this._vertexBuffers["cellInfo"] = cellInfo;
  42458. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42459. // Effects
  42460. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42461. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42462. }
  42463. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42464. set: function (callback) {
  42465. if (this._onDisposeObserver) {
  42466. this.onDisposeObservable.remove(this._onDisposeObserver);
  42467. }
  42468. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42469. },
  42470. enumerable: true,
  42471. configurable: true
  42472. });
  42473. Object.defineProperty(SpriteManager.prototype, "texture", {
  42474. get: function () {
  42475. return this._spriteTexture;
  42476. },
  42477. set: function (value) {
  42478. this._spriteTexture = value;
  42479. },
  42480. enumerable: true,
  42481. configurable: true
  42482. });
  42483. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42484. var arrayOffset = index * 16;
  42485. if (offsetX === 0)
  42486. offsetX = this._epsilon;
  42487. else if (offsetX === 1)
  42488. offsetX = 1 - this._epsilon;
  42489. if (offsetY === 0)
  42490. offsetY = this._epsilon;
  42491. else if (offsetY === 1)
  42492. offsetY = 1 - this._epsilon;
  42493. this._vertexData[arrayOffset] = sprite.position.x;
  42494. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42495. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42496. this._vertexData[arrayOffset + 3] = sprite.angle;
  42497. this._vertexData[arrayOffset + 4] = sprite.width;
  42498. this._vertexData[arrayOffset + 5] = sprite.height;
  42499. this._vertexData[arrayOffset + 6] = offsetX;
  42500. this._vertexData[arrayOffset + 7] = offsetY;
  42501. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42502. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42503. var offset = (sprite.cellIndex / rowSize) >> 0;
  42504. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42505. this._vertexData[arrayOffset + 11] = offset;
  42506. // Color
  42507. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42508. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42509. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42510. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42511. };
  42512. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42513. var count = Math.min(this._capacity, this.sprites.length);
  42514. var min = BABYLON.Vector3.Zero();
  42515. var max = BABYLON.Vector3.Zero();
  42516. var distance = Number.MAX_VALUE;
  42517. var currentSprite = null;
  42518. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42519. var cameraView = camera.getViewMatrix();
  42520. for (var index = 0; index < count; index++) {
  42521. var sprite = this.sprites[index];
  42522. if (!sprite) {
  42523. continue;
  42524. }
  42525. if (predicate) {
  42526. if (!predicate(sprite)) {
  42527. continue;
  42528. }
  42529. }
  42530. else if (!sprite.isPickable) {
  42531. continue;
  42532. }
  42533. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42534. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42535. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42536. if (ray.intersectsBoxMinMax(min, max)) {
  42537. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42538. if (distance > currentDistance) {
  42539. distance = currentDistance;
  42540. currentSprite = sprite;
  42541. if (fastCheck) {
  42542. break;
  42543. }
  42544. }
  42545. }
  42546. }
  42547. if (currentSprite) {
  42548. var result = new BABYLON.PickingInfo();
  42549. result.hit = true;
  42550. result.pickedSprite = currentSprite;
  42551. result.distance = distance;
  42552. return result;
  42553. }
  42554. return null;
  42555. };
  42556. SpriteManager.prototype.render = function () {
  42557. // Check
  42558. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42559. return;
  42560. var engine = this._scene.getEngine();
  42561. var baseSize = this._spriteTexture.getBaseSize();
  42562. // Sprites
  42563. var deltaTime = engine.getDeltaTime();
  42564. var max = Math.min(this._capacity, this.sprites.length);
  42565. var rowSize = baseSize.width / this.cellWidth;
  42566. var offset = 0;
  42567. for (var index = 0; index < max; index++) {
  42568. var sprite = this.sprites[index];
  42569. if (!sprite) {
  42570. continue;
  42571. }
  42572. sprite._animate(deltaTime);
  42573. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42574. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42575. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42576. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42577. }
  42578. this._buffer.update(this._vertexData);
  42579. // Render
  42580. var effect = this._effectBase;
  42581. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42582. effect = this._effectFog;
  42583. }
  42584. engine.enableEffect(effect);
  42585. var viewMatrix = this._scene.getViewMatrix();
  42586. effect.setTexture("diffuseSampler", this._spriteTexture);
  42587. effect.setMatrix("view", viewMatrix);
  42588. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42589. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42590. // Fog
  42591. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42592. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42593. effect.setColor3("vFogColor", this._scene.fogColor);
  42594. }
  42595. // VBOs
  42596. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42597. // Draw order
  42598. engine.setDepthFunctionToLessOrEqual();
  42599. effect.setBool("alphaTest", true);
  42600. engine.setColorWrite(false);
  42601. engine.draw(true, 0, max * 6);
  42602. engine.setColorWrite(true);
  42603. effect.setBool("alphaTest", false);
  42604. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42605. engine.draw(true, 0, max * 6);
  42606. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42607. };
  42608. SpriteManager.prototype.dispose = function () {
  42609. if (this._buffer) {
  42610. this._buffer.dispose();
  42611. this._buffer = null;
  42612. }
  42613. if (this._indexBuffer) {
  42614. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42615. this._indexBuffer = null;
  42616. }
  42617. if (this._spriteTexture) {
  42618. this._spriteTexture.dispose();
  42619. this._spriteTexture = null;
  42620. }
  42621. // Remove from scene
  42622. var index = this._scene.spriteManagers.indexOf(this);
  42623. this._scene.spriteManagers.splice(index, 1);
  42624. // Callback
  42625. this.onDisposeObservable.notifyObservers(this);
  42626. this.onDisposeObservable.clear();
  42627. };
  42628. return SpriteManager;
  42629. }());
  42630. BABYLON.SpriteManager = SpriteManager;
  42631. })(BABYLON || (BABYLON = {}));
  42632. //# sourceMappingURL=babylon.spriteManager.js.map
  42633. var BABYLON;
  42634. (function (BABYLON) {
  42635. var Sprite = /** @class */ (function () {
  42636. function Sprite(name, manager) {
  42637. this.name = name;
  42638. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42639. this.width = 1.0;
  42640. this.height = 1.0;
  42641. this.angle = 0;
  42642. this.cellIndex = 0;
  42643. this.invertU = 0;
  42644. this.invertV = 0;
  42645. this.animations = new Array();
  42646. this.isPickable = false;
  42647. this._animationStarted = false;
  42648. this._loopAnimation = false;
  42649. this._fromIndex = 0;
  42650. this._toIndex = 0;
  42651. this._delay = 0;
  42652. this._direction = 1;
  42653. this._time = 0;
  42654. this._manager = manager;
  42655. this._manager.sprites.push(this);
  42656. this.position = BABYLON.Vector3.Zero();
  42657. }
  42658. Object.defineProperty(Sprite.prototype, "size", {
  42659. get: function () {
  42660. return this.width;
  42661. },
  42662. set: function (value) {
  42663. this.width = value;
  42664. this.height = value;
  42665. },
  42666. enumerable: true,
  42667. configurable: true
  42668. });
  42669. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42670. this._fromIndex = from;
  42671. this._toIndex = to;
  42672. this._loopAnimation = loop;
  42673. this._delay = delay;
  42674. this._animationStarted = true;
  42675. this._direction = from < to ? 1 : -1;
  42676. this.cellIndex = from;
  42677. this._time = 0;
  42678. this._onAnimationEnd = onAnimationEnd;
  42679. };
  42680. Sprite.prototype.stopAnimation = function () {
  42681. this._animationStarted = false;
  42682. };
  42683. Sprite.prototype._animate = function (deltaTime) {
  42684. if (!this._animationStarted)
  42685. return;
  42686. this._time += deltaTime;
  42687. if (this._time > this._delay) {
  42688. this._time = this._time % this._delay;
  42689. this.cellIndex += this._direction;
  42690. if (this.cellIndex > this._toIndex) {
  42691. if (this._loopAnimation) {
  42692. this.cellIndex = this._fromIndex;
  42693. }
  42694. else {
  42695. this.cellIndex = this._toIndex;
  42696. this._animationStarted = false;
  42697. if (this._onAnimationEnd) {
  42698. this._onAnimationEnd();
  42699. }
  42700. if (this.disposeWhenFinishedAnimating) {
  42701. this.dispose();
  42702. }
  42703. }
  42704. }
  42705. }
  42706. };
  42707. Sprite.prototype.dispose = function () {
  42708. for (var i = 0; i < this._manager.sprites.length; i++) {
  42709. if (this._manager.sprites[i] == this) {
  42710. this._manager.sprites.splice(i, 1);
  42711. }
  42712. }
  42713. };
  42714. return Sprite;
  42715. }());
  42716. BABYLON.Sprite = Sprite;
  42717. })(BABYLON || (BABYLON = {}));
  42718. //# sourceMappingURL=babylon.sprite.js.map
  42719. var BABYLON;
  42720. (function (BABYLON) {
  42721. var IntersectionInfo = /** @class */ (function () {
  42722. function IntersectionInfo(bu, bv, distance) {
  42723. this.bu = bu;
  42724. this.bv = bv;
  42725. this.distance = distance;
  42726. this.faceId = 0;
  42727. this.subMeshId = 0;
  42728. }
  42729. return IntersectionInfo;
  42730. }());
  42731. BABYLON.IntersectionInfo = IntersectionInfo;
  42732. var PickingInfo = /** @class */ (function () {
  42733. function PickingInfo() {
  42734. this.hit = false;
  42735. this.distance = 0;
  42736. this.pickedPoint = null;
  42737. this.pickedMesh = null;
  42738. this.bu = 0;
  42739. this.bv = 0;
  42740. this.faceId = -1;
  42741. this.subMeshId = 0;
  42742. this.pickedSprite = null;
  42743. }
  42744. // Methods
  42745. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42746. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42747. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42748. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42749. return null;
  42750. }
  42751. var indices = this.pickedMesh.getIndices();
  42752. if (!indices) {
  42753. return null;
  42754. }
  42755. var result;
  42756. if (useVerticesNormals) {
  42757. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42758. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42759. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42760. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42761. normal0 = normal0.scale(this.bu);
  42762. normal1 = normal1.scale(this.bv);
  42763. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42764. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42765. }
  42766. else {
  42767. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42768. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42769. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42770. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42771. var p1p2 = vertex1.subtract(vertex2);
  42772. var p3p2 = vertex3.subtract(vertex2);
  42773. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42774. }
  42775. if (useWorldCoordinates) {
  42776. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42777. }
  42778. return BABYLON.Vector3.Normalize(result);
  42779. };
  42780. PickingInfo.prototype.getTextureCoordinates = function () {
  42781. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42782. return null;
  42783. }
  42784. var indices = this.pickedMesh.getIndices();
  42785. if (!indices) {
  42786. return null;
  42787. }
  42788. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42789. if (!uvs) {
  42790. return null;
  42791. }
  42792. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  42793. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  42794. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  42795. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  42796. uv1 = uv1.scale(this.bu);
  42797. uv2 = uv2.scale(this.bv);
  42798. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  42799. };
  42800. return PickingInfo;
  42801. }());
  42802. BABYLON.PickingInfo = PickingInfo;
  42803. })(BABYLON || (BABYLON = {}));
  42804. //# sourceMappingURL=babylon.pickingInfo.js.map
  42805. var BABYLON;
  42806. (function (BABYLON) {
  42807. var Ray = /** @class */ (function () {
  42808. function Ray(origin, direction, length) {
  42809. if (length === void 0) { length = Number.MAX_VALUE; }
  42810. this.origin = origin;
  42811. this.direction = direction;
  42812. this.length = length;
  42813. }
  42814. // Methods
  42815. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  42816. var d = 0.0;
  42817. var maxValue = Number.MAX_VALUE;
  42818. var inv;
  42819. var min;
  42820. var max;
  42821. var temp;
  42822. if (Math.abs(this.direction.x) < 0.0000001) {
  42823. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  42824. return false;
  42825. }
  42826. }
  42827. else {
  42828. inv = 1.0 / this.direction.x;
  42829. min = (minimum.x - this.origin.x) * inv;
  42830. max = (maximum.x - this.origin.x) * inv;
  42831. if (max === -Infinity) {
  42832. max = Infinity;
  42833. }
  42834. if (min > max) {
  42835. temp = min;
  42836. min = max;
  42837. max = temp;
  42838. }
  42839. d = Math.max(min, d);
  42840. maxValue = Math.min(max, maxValue);
  42841. if (d > maxValue) {
  42842. return false;
  42843. }
  42844. }
  42845. if (Math.abs(this.direction.y) < 0.0000001) {
  42846. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  42847. return false;
  42848. }
  42849. }
  42850. else {
  42851. inv = 1.0 / this.direction.y;
  42852. min = (minimum.y - this.origin.y) * inv;
  42853. max = (maximum.y - this.origin.y) * inv;
  42854. if (max === -Infinity) {
  42855. max = Infinity;
  42856. }
  42857. if (min > max) {
  42858. temp = min;
  42859. min = max;
  42860. max = temp;
  42861. }
  42862. d = Math.max(min, d);
  42863. maxValue = Math.min(max, maxValue);
  42864. if (d > maxValue) {
  42865. return false;
  42866. }
  42867. }
  42868. if (Math.abs(this.direction.z) < 0.0000001) {
  42869. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  42870. return false;
  42871. }
  42872. }
  42873. else {
  42874. inv = 1.0 / this.direction.z;
  42875. min = (minimum.z - this.origin.z) * inv;
  42876. max = (maximum.z - this.origin.z) * inv;
  42877. if (max === -Infinity) {
  42878. max = Infinity;
  42879. }
  42880. if (min > max) {
  42881. temp = min;
  42882. min = max;
  42883. max = temp;
  42884. }
  42885. d = Math.max(min, d);
  42886. maxValue = Math.min(max, maxValue);
  42887. if (d > maxValue) {
  42888. return false;
  42889. }
  42890. }
  42891. return true;
  42892. };
  42893. Ray.prototype.intersectsBox = function (box) {
  42894. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  42895. };
  42896. Ray.prototype.intersectsSphere = function (sphere) {
  42897. var x = sphere.center.x - this.origin.x;
  42898. var y = sphere.center.y - this.origin.y;
  42899. var z = sphere.center.z - this.origin.z;
  42900. var pyth = (x * x) + (y * y) + (z * z);
  42901. var rr = sphere.radius * sphere.radius;
  42902. if (pyth <= rr) {
  42903. return true;
  42904. }
  42905. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  42906. if (dot < 0.0) {
  42907. return false;
  42908. }
  42909. var temp = pyth - (dot * dot);
  42910. return temp <= rr;
  42911. };
  42912. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  42913. if (!this._edge1) {
  42914. this._edge1 = BABYLON.Vector3.Zero();
  42915. this._edge2 = BABYLON.Vector3.Zero();
  42916. this._pvec = BABYLON.Vector3.Zero();
  42917. this._tvec = BABYLON.Vector3.Zero();
  42918. this._qvec = BABYLON.Vector3.Zero();
  42919. }
  42920. vertex1.subtractToRef(vertex0, this._edge1);
  42921. vertex2.subtractToRef(vertex0, this._edge2);
  42922. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  42923. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  42924. if (det === 0) {
  42925. return null;
  42926. }
  42927. var invdet = 1 / det;
  42928. this.origin.subtractToRef(vertex0, this._tvec);
  42929. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  42930. if (bu < 0 || bu > 1.0) {
  42931. return null;
  42932. }
  42933. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  42934. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  42935. if (bv < 0 || bu + bv > 1.0) {
  42936. return null;
  42937. }
  42938. //check if the distance is longer than the predefined length.
  42939. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  42940. if (distance > this.length) {
  42941. return null;
  42942. }
  42943. return new BABYLON.IntersectionInfo(bu, bv, distance);
  42944. };
  42945. Ray.prototype.intersectsPlane = function (plane) {
  42946. var distance;
  42947. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  42948. if (Math.abs(result1) < 9.99999997475243E-07) {
  42949. return null;
  42950. }
  42951. else {
  42952. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  42953. distance = (-plane.d - result2) / result1;
  42954. if (distance < 0.0) {
  42955. if (distance < -9.99999997475243E-07) {
  42956. return null;
  42957. }
  42958. else {
  42959. return 0;
  42960. }
  42961. }
  42962. return distance;
  42963. }
  42964. };
  42965. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  42966. var tm = BABYLON.Tmp.Matrix[0];
  42967. mesh.getWorldMatrix().invertToRef(tm);
  42968. if (this._tmpRay) {
  42969. Ray.TransformToRef(this, tm, this._tmpRay);
  42970. }
  42971. else {
  42972. this._tmpRay = Ray.Transform(this, tm);
  42973. }
  42974. return mesh.intersects(this._tmpRay, fastCheck);
  42975. };
  42976. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  42977. if (results) {
  42978. results.length = 0;
  42979. }
  42980. else {
  42981. results = [];
  42982. }
  42983. for (var i = 0; i < meshes.length; i++) {
  42984. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  42985. if (pickInfo.hit) {
  42986. results.push(pickInfo);
  42987. }
  42988. }
  42989. results.sort(this._comparePickingInfo);
  42990. return results;
  42991. };
  42992. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  42993. if (pickingInfoA.distance < pickingInfoB.distance) {
  42994. return -1;
  42995. }
  42996. else if (pickingInfoA.distance > pickingInfoB.distance) {
  42997. return 1;
  42998. }
  42999. else {
  43000. return 0;
  43001. }
  43002. };
  43003. /**
  43004. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43005. * @param sega the first point of the segment to test the intersection against
  43006. * @param segb the second point of the segment to test the intersection against
  43007. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43008. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43009. */
  43010. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43011. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43012. var u = segb.subtract(sega);
  43013. var v = rsegb.subtract(this.origin);
  43014. var w = sega.subtract(this.origin);
  43015. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43016. var b = BABYLON.Vector3.Dot(u, v);
  43017. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43018. var d = BABYLON.Vector3.Dot(u, w);
  43019. var e = BABYLON.Vector3.Dot(v, w);
  43020. var D = a * c - b * b; // always >= 0
  43021. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43022. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43023. // compute the line parameters of the two closest points
  43024. if (D < Ray.smallnum) {
  43025. sN = 0.0; // force using point P0 on segment S1
  43026. sD = 1.0; // to prevent possible division by 0.0 later
  43027. tN = e;
  43028. tD = c;
  43029. }
  43030. else {
  43031. sN = (b * e - c * d);
  43032. tN = (a * e - b * d);
  43033. if (sN < 0.0) {
  43034. sN = 0.0;
  43035. tN = e;
  43036. tD = c;
  43037. }
  43038. else if (sN > sD) {
  43039. sN = sD;
  43040. tN = e + b;
  43041. tD = c;
  43042. }
  43043. }
  43044. if (tN < 0.0) {
  43045. tN = 0.0;
  43046. // recompute sc for this edge
  43047. if (-d < 0.0) {
  43048. sN = 0.0;
  43049. }
  43050. else if (-d > a)
  43051. sN = sD;
  43052. else {
  43053. sN = -d;
  43054. sD = a;
  43055. }
  43056. }
  43057. else if (tN > tD) {
  43058. tN = tD;
  43059. // recompute sc for this edge
  43060. if ((-d + b) < 0.0) {
  43061. sN = 0;
  43062. }
  43063. else if ((-d + b) > a) {
  43064. sN = sD;
  43065. }
  43066. else {
  43067. sN = (-d + b);
  43068. sD = a;
  43069. }
  43070. }
  43071. // finally do the division to get sc and tc
  43072. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43073. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43074. // get the difference of the two closest points
  43075. var qtc = v.multiplyByFloats(tc, tc, tc);
  43076. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43077. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43078. if (isIntersected) {
  43079. return qtc.length();
  43080. }
  43081. return -1;
  43082. };
  43083. // Statics
  43084. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43085. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43086. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43087. var direction = end.subtract(start);
  43088. direction.normalize();
  43089. return new Ray(start, direction);
  43090. };
  43091. /**
  43092. * 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
  43093. * transformed to the given world matrix.
  43094. * @param origin The origin point
  43095. * @param end The end point
  43096. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43097. */
  43098. Ray.CreateNewFromTo = function (origin, end, world) {
  43099. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43100. var direction = end.subtract(origin);
  43101. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43102. direction.normalize();
  43103. return Ray.Transform(new Ray(origin, direction, length), world);
  43104. };
  43105. Ray.Transform = function (ray, matrix) {
  43106. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43107. Ray.TransformToRef(ray, matrix, result);
  43108. return result;
  43109. };
  43110. Ray.TransformToRef = function (ray, matrix, result) {
  43111. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43112. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43113. result.length = ray.length;
  43114. var dir = result.direction;
  43115. var len = dir.length();
  43116. if (!(len === 0 || len === 1)) {
  43117. var num = 1.0 / len;
  43118. dir.x *= num;
  43119. dir.y *= num;
  43120. dir.z *= num;
  43121. result.length *= len;
  43122. }
  43123. };
  43124. Ray.smallnum = 0.00000001;
  43125. Ray.rayl = 10e8;
  43126. return Ray;
  43127. }());
  43128. BABYLON.Ray = Ray;
  43129. })(BABYLON || (BABYLON = {}));
  43130. //# sourceMappingURL=babylon.ray.js.map
  43131. var BABYLON;
  43132. (function (BABYLON) {
  43133. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43134. if (boxMin.x > sphereCenter.x + sphereRadius)
  43135. return false;
  43136. if (sphereCenter.x - sphereRadius > boxMax.x)
  43137. return false;
  43138. if (boxMin.y > sphereCenter.y + sphereRadius)
  43139. return false;
  43140. if (sphereCenter.y - sphereRadius > boxMax.y)
  43141. return false;
  43142. if (boxMin.z > sphereCenter.z + sphereRadius)
  43143. return false;
  43144. if (sphereCenter.z - sphereRadius > boxMax.z)
  43145. return false;
  43146. return true;
  43147. };
  43148. var getLowestRoot = (function () {
  43149. var result = { root: 0, found: false };
  43150. return function (a, b, c, maxR) {
  43151. result.root = 0;
  43152. result.found = false;
  43153. var determinant = b * b - 4.0 * a * c;
  43154. if (determinant < 0)
  43155. return result;
  43156. var sqrtD = Math.sqrt(determinant);
  43157. var r1 = (-b - sqrtD) / (2.0 * a);
  43158. var r2 = (-b + sqrtD) / (2.0 * a);
  43159. if (r1 > r2) {
  43160. var temp = r2;
  43161. r2 = r1;
  43162. r1 = temp;
  43163. }
  43164. if (r1 > 0 && r1 < maxR) {
  43165. result.root = r1;
  43166. result.found = true;
  43167. return result;
  43168. }
  43169. if (r2 > 0 && r2 < maxR) {
  43170. result.root = r2;
  43171. result.found = true;
  43172. return result;
  43173. }
  43174. return result;
  43175. };
  43176. })();
  43177. var Collider = /** @class */ (function () {
  43178. function Collider() {
  43179. this.radius = BABYLON.Vector3.One();
  43180. this.retry = 0;
  43181. this.basePointWorld = BABYLON.Vector3.Zero();
  43182. this.velocityWorld = BABYLON.Vector3.Zero();
  43183. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43184. this._collisionPoint = BABYLON.Vector3.Zero();
  43185. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43186. this._tempVector = BABYLON.Vector3.Zero();
  43187. this._tempVector2 = BABYLON.Vector3.Zero();
  43188. this._tempVector3 = BABYLON.Vector3.Zero();
  43189. this._tempVector4 = BABYLON.Vector3.Zero();
  43190. this._edge = BABYLON.Vector3.Zero();
  43191. this._baseToVertex = BABYLON.Vector3.Zero();
  43192. this._destinationPoint = BABYLON.Vector3.Zero();
  43193. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43194. this._displacementVector = BABYLON.Vector3.Zero();
  43195. this._collisionMask = -1;
  43196. }
  43197. Object.defineProperty(Collider.prototype, "collisionMask", {
  43198. get: function () {
  43199. return this._collisionMask;
  43200. },
  43201. set: function (mask) {
  43202. this._collisionMask = !isNaN(mask) ? mask : -1;
  43203. },
  43204. enumerable: true,
  43205. configurable: true
  43206. });
  43207. // Methods
  43208. Collider.prototype._initialize = function (source, dir, e) {
  43209. this.velocity = dir;
  43210. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43211. this.basePoint = source;
  43212. source.multiplyToRef(this.radius, this.basePointWorld);
  43213. dir.multiplyToRef(this.radius, this.velocityWorld);
  43214. this.velocityWorldLength = this.velocityWorld.length();
  43215. this.epsilon = e;
  43216. this.collisionFound = false;
  43217. };
  43218. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43219. pa.subtractToRef(point, this._tempVector);
  43220. pb.subtractToRef(point, this._tempVector2);
  43221. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43222. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43223. if (d < 0)
  43224. return false;
  43225. pc.subtractToRef(point, this._tempVector3);
  43226. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43227. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43228. if (d < 0)
  43229. return false;
  43230. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43231. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43232. return d >= 0;
  43233. };
  43234. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43235. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43236. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43237. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43238. return false;
  43239. }
  43240. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43241. return false;
  43242. return true;
  43243. };
  43244. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43245. var t0;
  43246. var embeddedInPlane = false;
  43247. //defensive programming, actually not needed.
  43248. if (!trianglePlaneArray) {
  43249. trianglePlaneArray = [];
  43250. }
  43251. if (!trianglePlaneArray[faceIndex]) {
  43252. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43253. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43254. }
  43255. var trianglePlane = trianglePlaneArray[faceIndex];
  43256. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43257. return;
  43258. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43259. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43260. if (normalDotVelocity == 0) {
  43261. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43262. return;
  43263. embeddedInPlane = true;
  43264. t0 = 0;
  43265. }
  43266. else {
  43267. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43268. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43269. if (t0 > t1) {
  43270. var temp = t1;
  43271. t1 = t0;
  43272. t0 = temp;
  43273. }
  43274. if (t0 > 1.0 || t1 < 0.0)
  43275. return;
  43276. if (t0 < 0)
  43277. t0 = 0;
  43278. if (t0 > 1.0)
  43279. t0 = 1.0;
  43280. }
  43281. this._collisionPoint.copyFromFloats(0, 0, 0);
  43282. var found = false;
  43283. var t = 1.0;
  43284. if (!embeddedInPlane) {
  43285. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43286. this.velocity.scaleToRef(t0, this._tempVector);
  43287. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43288. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43289. found = true;
  43290. t = t0;
  43291. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43292. }
  43293. }
  43294. if (!found) {
  43295. var velocitySquaredLength = this.velocity.lengthSquared();
  43296. var a = velocitySquaredLength;
  43297. this.basePoint.subtractToRef(p1, this._tempVector);
  43298. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43299. var c = this._tempVector.lengthSquared() - 1.0;
  43300. var lowestRoot = getLowestRoot(a, b, c, t);
  43301. if (lowestRoot.found) {
  43302. t = lowestRoot.root;
  43303. found = true;
  43304. this._collisionPoint.copyFrom(p1);
  43305. }
  43306. this.basePoint.subtractToRef(p2, this._tempVector);
  43307. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43308. c = this._tempVector.lengthSquared() - 1.0;
  43309. lowestRoot = getLowestRoot(a, b, c, t);
  43310. if (lowestRoot.found) {
  43311. t = lowestRoot.root;
  43312. found = true;
  43313. this._collisionPoint.copyFrom(p2);
  43314. }
  43315. this.basePoint.subtractToRef(p3, this._tempVector);
  43316. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43317. c = this._tempVector.lengthSquared() - 1.0;
  43318. lowestRoot = getLowestRoot(a, b, c, t);
  43319. if (lowestRoot.found) {
  43320. t = lowestRoot.root;
  43321. found = true;
  43322. this._collisionPoint.copyFrom(p3);
  43323. }
  43324. p2.subtractToRef(p1, this._edge);
  43325. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43326. var edgeSquaredLength = this._edge.lengthSquared();
  43327. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43328. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43329. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43330. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43331. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43332. lowestRoot = getLowestRoot(a, b, c, t);
  43333. if (lowestRoot.found) {
  43334. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43335. if (f >= 0.0 && f <= 1.0) {
  43336. t = lowestRoot.root;
  43337. found = true;
  43338. this._edge.scaleInPlace(f);
  43339. p1.addToRef(this._edge, this._collisionPoint);
  43340. }
  43341. }
  43342. p3.subtractToRef(p2, this._edge);
  43343. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43344. edgeSquaredLength = this._edge.lengthSquared();
  43345. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43346. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43347. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43348. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43349. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43350. lowestRoot = getLowestRoot(a, b, c, t);
  43351. if (lowestRoot.found) {
  43352. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43353. if (f >= 0.0 && f <= 1.0) {
  43354. t = lowestRoot.root;
  43355. found = true;
  43356. this._edge.scaleInPlace(f);
  43357. p2.addToRef(this._edge, this._collisionPoint);
  43358. }
  43359. }
  43360. p1.subtractToRef(p3, this._edge);
  43361. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43362. edgeSquaredLength = this._edge.lengthSquared();
  43363. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43364. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43365. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43366. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43367. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43368. lowestRoot = getLowestRoot(a, b, c, t);
  43369. if (lowestRoot.found) {
  43370. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43371. if (f >= 0.0 && f <= 1.0) {
  43372. t = lowestRoot.root;
  43373. found = true;
  43374. this._edge.scaleInPlace(f);
  43375. p3.addToRef(this._edge, this._collisionPoint);
  43376. }
  43377. }
  43378. }
  43379. if (found) {
  43380. var distToCollision = t * this.velocity.length();
  43381. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43382. if (!this.intersectionPoint) {
  43383. this.intersectionPoint = this._collisionPoint.clone();
  43384. }
  43385. else {
  43386. this.intersectionPoint.copyFrom(this._collisionPoint);
  43387. }
  43388. this.nearestDistance = distToCollision;
  43389. this.collisionFound = true;
  43390. }
  43391. }
  43392. };
  43393. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43394. for (var i = indexStart; i < indexEnd; i += 3) {
  43395. var p1 = pts[indices[i] - decal];
  43396. var p2 = pts[indices[i + 1] - decal];
  43397. var p3 = pts[indices[i + 2] - decal];
  43398. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43399. }
  43400. };
  43401. Collider.prototype._getResponse = function (pos, vel) {
  43402. pos.addToRef(vel, this._destinationPoint);
  43403. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43404. this.basePoint.addToRef(vel, pos);
  43405. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43406. this._slidePlaneNormal.normalize();
  43407. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43408. pos.addInPlace(this._displacementVector);
  43409. this.intersectionPoint.addInPlace(this._displacementVector);
  43410. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43411. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43412. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43413. };
  43414. return Collider;
  43415. }());
  43416. BABYLON.Collider = Collider;
  43417. })(BABYLON || (BABYLON = {}));
  43418. //# sourceMappingURL=babylon.collider.js.map
  43419. var BABYLON;
  43420. (function (BABYLON) {
  43421. //WebWorker code will be inserted to this variable.
  43422. BABYLON.CollisionWorker = "";
  43423. var WorkerTaskType;
  43424. (function (WorkerTaskType) {
  43425. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43426. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43427. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43428. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43429. var WorkerReplyType;
  43430. (function (WorkerReplyType) {
  43431. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43432. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43433. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43434. var CollisionCoordinatorWorker = /** @class */ (function () {
  43435. function CollisionCoordinatorWorker() {
  43436. var _this = this;
  43437. this._scaledPosition = BABYLON.Vector3.Zero();
  43438. this._scaledVelocity = BABYLON.Vector3.Zero();
  43439. this.onMeshUpdated = function (mesh) {
  43440. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43441. };
  43442. this.onGeometryUpdated = function (geometry) {
  43443. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43444. };
  43445. this._afterRender = function () {
  43446. if (!_this._init)
  43447. return;
  43448. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43449. return;
  43450. }
  43451. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43452. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43453. if (_this._runningUpdated > 4) {
  43454. return;
  43455. }
  43456. ++_this._runningUpdated;
  43457. var payload = {
  43458. updatedMeshes: _this._addUpdateMeshesList,
  43459. updatedGeometries: _this._addUpdateGeometriesList,
  43460. removedGeometries: _this._toRemoveGeometryArray,
  43461. removedMeshes: _this._toRemoveMeshesArray
  43462. };
  43463. var message = {
  43464. payload: payload,
  43465. taskType: WorkerTaskType.UPDATE
  43466. };
  43467. var serializable = [];
  43468. for (var id in payload.updatedGeometries) {
  43469. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43470. //prepare transferables
  43471. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43472. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43473. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43474. }
  43475. }
  43476. _this._worker.postMessage(message, serializable);
  43477. _this._addUpdateMeshesList = {};
  43478. _this._addUpdateGeometriesList = {};
  43479. _this._toRemoveGeometryArray = [];
  43480. _this._toRemoveMeshesArray = [];
  43481. };
  43482. this._onMessageFromWorker = function (e) {
  43483. var returnData = e.data;
  43484. if (returnData.error != WorkerReplyType.SUCCESS) {
  43485. //TODO what errors can be returned from the worker?
  43486. BABYLON.Tools.Warn("error returned from worker!");
  43487. return;
  43488. }
  43489. switch (returnData.taskType) {
  43490. case WorkerTaskType.INIT:
  43491. _this._init = true;
  43492. //Update the worked with ALL of the scene's current state
  43493. _this._scene.meshes.forEach(function (mesh) {
  43494. _this.onMeshAdded(mesh);
  43495. });
  43496. _this._scene.getGeometries().forEach(function (geometry) {
  43497. _this.onGeometryAdded(geometry);
  43498. });
  43499. break;
  43500. case WorkerTaskType.UPDATE:
  43501. _this._runningUpdated--;
  43502. break;
  43503. case WorkerTaskType.COLLIDE:
  43504. _this._runningCollisionTask = false;
  43505. var returnPayload = returnData.payload;
  43506. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43507. return;
  43508. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43509. if (callback) {
  43510. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43511. if (mesh) {
  43512. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43513. }
  43514. }
  43515. //cleanup
  43516. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43517. break;
  43518. }
  43519. };
  43520. this._collisionsCallbackArray = [];
  43521. this._init = false;
  43522. this._runningUpdated = 0;
  43523. this._runningCollisionTask = false;
  43524. this._addUpdateMeshesList = {};
  43525. this._addUpdateGeometriesList = {};
  43526. this._toRemoveGeometryArray = [];
  43527. this._toRemoveMeshesArray = [];
  43528. }
  43529. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43530. if (!this._init)
  43531. return;
  43532. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43533. return;
  43534. position.divideToRef(collider.radius, this._scaledPosition);
  43535. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43536. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43537. var payload = {
  43538. collider: {
  43539. position: this._scaledPosition.asArray(),
  43540. velocity: this._scaledVelocity.asArray(),
  43541. radius: collider.radius.asArray()
  43542. },
  43543. collisionId: collisionIndex,
  43544. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43545. maximumRetry: maximumRetry
  43546. };
  43547. var message = {
  43548. payload: payload,
  43549. taskType: WorkerTaskType.COLLIDE
  43550. };
  43551. this._worker.postMessage(message);
  43552. };
  43553. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43554. this._scene = scene;
  43555. this._scene.registerAfterRender(this._afterRender);
  43556. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43557. this._worker = new Worker(workerUrl);
  43558. this._worker.onmessage = this._onMessageFromWorker;
  43559. var message = {
  43560. payload: {},
  43561. taskType: WorkerTaskType.INIT
  43562. };
  43563. this._worker.postMessage(message);
  43564. };
  43565. CollisionCoordinatorWorker.prototype.destroy = function () {
  43566. this._scene.unregisterAfterRender(this._afterRender);
  43567. this._worker.terminate();
  43568. };
  43569. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43570. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43571. this.onMeshUpdated(mesh);
  43572. };
  43573. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43574. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43575. };
  43576. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43577. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43578. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43579. this.onGeometryUpdated(geometry);
  43580. };
  43581. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43582. this._toRemoveGeometryArray.push(geometry.id);
  43583. };
  43584. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43585. var submeshes = [];
  43586. if (mesh.subMeshes) {
  43587. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43588. var boundingInfo = sm.getBoundingInfo();
  43589. return {
  43590. position: idx,
  43591. verticesStart: sm.verticesStart,
  43592. verticesCount: sm.verticesCount,
  43593. indexStart: sm.indexStart,
  43594. indexCount: sm.indexCount,
  43595. hasMaterial: !!sm.getMaterial(),
  43596. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43597. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43598. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43599. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43600. };
  43601. });
  43602. }
  43603. var geometryId = null;
  43604. if (mesh instanceof BABYLON.Mesh) {
  43605. var geometry = mesh.geometry;
  43606. geometryId = geometry ? geometry.id : null;
  43607. }
  43608. else if (mesh instanceof BABYLON.InstancedMesh) {
  43609. var geometry = mesh.sourceMesh.geometry;
  43610. geometryId = geometry ? geometry.id : null;
  43611. }
  43612. var boundingInfo = mesh.getBoundingInfo();
  43613. return {
  43614. uniqueId: mesh.uniqueId,
  43615. id: mesh.id,
  43616. name: mesh.name,
  43617. geometryId: geometryId,
  43618. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43619. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43620. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43621. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43622. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43623. subMeshes: submeshes,
  43624. checkCollisions: mesh.checkCollisions
  43625. };
  43626. };
  43627. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43628. return {
  43629. id: geometry.id,
  43630. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43631. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43632. indices: new Uint32Array(geometry.getIndices() || []),
  43633. };
  43634. };
  43635. return CollisionCoordinatorWorker;
  43636. }());
  43637. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43638. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43639. function CollisionCoordinatorLegacy() {
  43640. this._scaledPosition = BABYLON.Vector3.Zero();
  43641. this._scaledVelocity = BABYLON.Vector3.Zero();
  43642. this._finalPosition = BABYLON.Vector3.Zero();
  43643. }
  43644. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43645. position.divideToRef(collider.radius, this._scaledPosition);
  43646. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43647. collider.collidedMesh = null;
  43648. collider.retry = 0;
  43649. collider.initialVelocity = this._scaledVelocity;
  43650. collider.initialPosition = this._scaledPosition;
  43651. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43652. this._finalPosition.multiplyInPlace(collider.radius);
  43653. //run the callback
  43654. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43655. };
  43656. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43657. this._scene = scene;
  43658. };
  43659. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43660. //Legacy need no destruction method.
  43661. };
  43662. //No update in legacy mode
  43663. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43664. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43665. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43666. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43667. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43668. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43669. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43670. if (excludedMesh === void 0) { excludedMesh = null; }
  43671. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43672. if (collider.retry >= maximumRetry) {
  43673. finalPosition.copyFrom(position);
  43674. return;
  43675. }
  43676. // Check if this is a mesh else camera or -1
  43677. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43678. collider._initialize(position, velocity, closeDistance);
  43679. // Check all meshes
  43680. for (var index = 0; index < this._scene.meshes.length; index++) {
  43681. var mesh = this._scene.meshes[index];
  43682. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43683. mesh._checkCollision(collider);
  43684. }
  43685. }
  43686. if (!collider.collisionFound) {
  43687. position.addToRef(velocity, finalPosition);
  43688. return;
  43689. }
  43690. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43691. collider._getResponse(position, velocity);
  43692. }
  43693. if (velocity.length() <= closeDistance) {
  43694. finalPosition.copyFrom(position);
  43695. return;
  43696. }
  43697. collider.retry++;
  43698. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43699. };
  43700. return CollisionCoordinatorLegacy;
  43701. }());
  43702. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43703. })(BABYLON || (BABYLON = {}));
  43704. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43705. var BABYLON;
  43706. (function (BABYLON) {
  43707. var Particle = /** @class */ (function () {
  43708. function Particle(particleSystem) {
  43709. this.particleSystem = particleSystem;
  43710. this.position = BABYLON.Vector3.Zero();
  43711. this.direction = BABYLON.Vector3.Zero();
  43712. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43713. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43714. this.lifeTime = 1.0;
  43715. this.age = 0;
  43716. this.size = 0;
  43717. this.angle = 0;
  43718. this.angularSpeed = 0;
  43719. this._currentFrameCounter = 0;
  43720. this.cellIndex = 0;
  43721. if (!this.particleSystem.isAnimationSheetEnabled) {
  43722. return;
  43723. }
  43724. this.cellIndex = this.particleSystem.startSpriteCellID;
  43725. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43726. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43727. }
  43728. else {
  43729. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43730. }
  43731. }
  43732. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43733. // (ageOffset / scaledUpdateSpeed) / available cells
  43734. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43735. this._currentFrameCounter += scaledUpdateSpeed;
  43736. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43737. this._currentFrameCounter = 0;
  43738. this.cellIndex++;
  43739. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43740. this.cellIndex = this.particleSystem.endSpriteCellID;
  43741. }
  43742. }
  43743. };
  43744. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43745. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43746. this.cellIndex++;
  43747. this._currentFrameCounter = 0;
  43748. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43749. if (this.particleSystem.spriteCellLoop) {
  43750. this.cellIndex = this.particleSystem.startSpriteCellID;
  43751. }
  43752. else {
  43753. this.cellIndex = this.particleSystem.endSpriteCellID;
  43754. }
  43755. }
  43756. }
  43757. else {
  43758. this._currentFrameCounter++;
  43759. }
  43760. };
  43761. Particle.prototype.copyTo = function (other) {
  43762. other.position.copyFrom(this.position);
  43763. other.direction.copyFrom(this.direction);
  43764. other.color.copyFrom(this.color);
  43765. other.colorStep.copyFrom(this.colorStep);
  43766. other.lifeTime = this.lifeTime;
  43767. other.age = this.age;
  43768. other.size = this.size;
  43769. other.angle = this.angle;
  43770. other.angularSpeed = this.angularSpeed;
  43771. other.particleSystem = this.particleSystem;
  43772. other.cellIndex = this.cellIndex;
  43773. };
  43774. return Particle;
  43775. }());
  43776. BABYLON.Particle = Particle;
  43777. })(BABYLON || (BABYLON = {}));
  43778. //# sourceMappingURL=babylon.particle.js.map
  43779. var BABYLON;
  43780. (function (BABYLON) {
  43781. var randomNumber = function (min, max) {
  43782. if (min === max) {
  43783. return (min);
  43784. }
  43785. var random = Math.random();
  43786. return ((random * (max - min)) + min);
  43787. };
  43788. var ParticleSystem = /** @class */ (function () {
  43789. // end of sheet animation
  43790. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  43791. if (customEffect === void 0) { customEffect = null; }
  43792. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  43793. if (epsilon === void 0) { epsilon = 0.01; }
  43794. var _this = this;
  43795. this.name = name;
  43796. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  43797. // Members
  43798. this.animations = [];
  43799. this.renderingGroupId = 0;
  43800. this.emitter = null;
  43801. this.emitRate = 10;
  43802. this.manualEmitCount = -1;
  43803. this.updateSpeed = 0.01;
  43804. this.targetStopDuration = 0;
  43805. this.disposeOnStop = false;
  43806. this.minEmitPower = 1;
  43807. this.maxEmitPower = 1;
  43808. this.minLifeTime = 1;
  43809. this.maxLifeTime = 1;
  43810. this.minSize = 1;
  43811. this.maxSize = 1;
  43812. this.minAngularSpeed = 0;
  43813. this.maxAngularSpeed = 0;
  43814. this.layerMask = 0x0FFFFFFF;
  43815. this.customShader = null;
  43816. this.preventAutoStart = false;
  43817. /**
  43818. * An event triggered when the system is disposed.
  43819. * @type {BABYLON.Observable}
  43820. */
  43821. this.onDisposeObservable = new BABYLON.Observable();
  43822. this.onAnimationEnd = null;
  43823. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  43824. this.forceDepthWrite = false;
  43825. this.gravity = BABYLON.Vector3.Zero();
  43826. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  43827. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  43828. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  43829. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43830. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43831. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43832. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  43833. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43834. this.particles = new Array();
  43835. this._stockParticles = new Array();
  43836. this._newPartsExcess = 0;
  43837. this._vertexBuffers = {};
  43838. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  43839. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  43840. this._scaledDirection = BABYLON.Vector3.Zero();
  43841. this._scaledGravity = BABYLON.Vector3.Zero();
  43842. this._currentRenderId = -1;
  43843. this._started = false;
  43844. this._stopped = false;
  43845. this._actualFrame = 0;
  43846. // sheet animation
  43847. this.startSpriteCellID = 0;
  43848. this.endSpriteCellID = 0;
  43849. this.spriteCellLoop = true;
  43850. this.spriteCellChangeSpeed = 0;
  43851. this.spriteCellWidth = 0;
  43852. this.spriteCellHeight = 0;
  43853. this._vertexBufferSize = 11;
  43854. this.appendParticleVertexes = null;
  43855. this.id = name;
  43856. this._capacity = capacity;
  43857. this._epsilon = epsilon;
  43858. if (_isAnimationSheetEnabled) {
  43859. this._vertexBufferSize = 12;
  43860. }
  43861. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43862. this._customEffect = customEffect;
  43863. scene.particleSystems.push(this);
  43864. this._createIndexBuffer();
  43865. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  43866. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  43867. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  43868. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  43869. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  43870. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  43871. if (this._isAnimationSheetEnabled) {
  43872. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  43873. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  43874. }
  43875. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43876. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43877. this._vertexBuffers["options"] = options;
  43878. // Default behaviors
  43879. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  43880. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  43881. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  43882. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  43883. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  43884. };
  43885. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  43886. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  43887. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  43888. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  43889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  43890. };
  43891. this.updateFunction = function (particles) {
  43892. for (var index = 0; index < particles.length; index++) {
  43893. var particle = particles[index];
  43894. particle.age += _this._scaledUpdateSpeed;
  43895. if (particle.age >= particle.lifeTime) {
  43896. _this.recycleParticle(particle);
  43897. index--;
  43898. continue;
  43899. }
  43900. else {
  43901. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  43902. particle.color.addInPlace(_this._scaledColorStep);
  43903. if (particle.color.a < 0)
  43904. particle.color.a = 0;
  43905. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  43906. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  43907. particle.position.addInPlace(_this._scaledDirection);
  43908. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  43909. particle.direction.addInPlace(_this._scaledGravity);
  43910. if (_this._isAnimationSheetEnabled) {
  43911. particle.updateCellIndex(_this._scaledUpdateSpeed);
  43912. }
  43913. }
  43914. }
  43915. };
  43916. }
  43917. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  43918. set: function (callback) {
  43919. if (this._onDisposeObserver) {
  43920. this.onDisposeObservable.remove(this._onDisposeObserver);
  43921. }
  43922. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43923. },
  43924. enumerable: true,
  43925. configurable: true
  43926. });
  43927. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  43928. get: function () {
  43929. return this._isAnimationSheetEnabled;
  43930. },
  43931. enumerable: true,
  43932. configurable: true
  43933. });
  43934. ParticleSystem.prototype._createIndexBuffer = function () {
  43935. var indices = [];
  43936. var index = 0;
  43937. for (var count = 0; count < this._capacity; count++) {
  43938. indices.push(index);
  43939. indices.push(index + 1);
  43940. indices.push(index + 2);
  43941. indices.push(index);
  43942. indices.push(index + 2);
  43943. indices.push(index + 3);
  43944. index += 4;
  43945. }
  43946. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  43947. };
  43948. ParticleSystem.prototype.recycleParticle = function (particle) {
  43949. var lastParticle = this.particles.pop();
  43950. if (lastParticle !== particle) {
  43951. lastParticle.copyTo(particle);
  43952. this._stockParticles.push(lastParticle);
  43953. }
  43954. };
  43955. ParticleSystem.prototype.getCapacity = function () {
  43956. return this._capacity;
  43957. };
  43958. ParticleSystem.prototype.isAlive = function () {
  43959. return this._alive;
  43960. };
  43961. ParticleSystem.prototype.isStarted = function () {
  43962. return this._started;
  43963. };
  43964. ParticleSystem.prototype.start = function () {
  43965. this._started = true;
  43966. this._stopped = false;
  43967. this._actualFrame = 0;
  43968. };
  43969. ParticleSystem.prototype.stop = function () {
  43970. this._stopped = true;
  43971. };
  43972. // animation sheet
  43973. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  43974. var offset = index * this._vertexBufferSize;
  43975. this._vertexData[offset] = particle.position.x;
  43976. this._vertexData[offset + 1] = particle.position.y;
  43977. this._vertexData[offset + 2] = particle.position.z;
  43978. this._vertexData[offset + 3] = particle.color.r;
  43979. this._vertexData[offset + 4] = particle.color.g;
  43980. this._vertexData[offset + 5] = particle.color.b;
  43981. this._vertexData[offset + 6] = particle.color.a;
  43982. this._vertexData[offset + 7] = particle.angle;
  43983. this._vertexData[offset + 8] = particle.size;
  43984. this._vertexData[offset + 9] = offsetX;
  43985. this._vertexData[offset + 10] = offsetY;
  43986. };
  43987. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  43988. if (offsetX === 0)
  43989. offsetX = this._epsilon;
  43990. else if (offsetX === 1)
  43991. offsetX = 1 - this._epsilon;
  43992. if (offsetY === 0)
  43993. offsetY = this._epsilon;
  43994. else if (offsetY === 1)
  43995. offsetY = 1 - this._epsilon;
  43996. var offset = index * this._vertexBufferSize;
  43997. this._vertexData[offset] = particle.position.x;
  43998. this._vertexData[offset + 1] = particle.position.y;
  43999. this._vertexData[offset + 2] = particle.position.z;
  44000. this._vertexData[offset + 3] = particle.color.r;
  44001. this._vertexData[offset + 4] = particle.color.g;
  44002. this._vertexData[offset + 5] = particle.color.b;
  44003. this._vertexData[offset + 6] = particle.color.a;
  44004. this._vertexData[offset + 7] = particle.angle;
  44005. this._vertexData[offset + 8] = particle.size;
  44006. this._vertexData[offset + 9] = offsetX;
  44007. this._vertexData[offset + 10] = offsetY;
  44008. this._vertexData[offset + 11] = particle.cellIndex;
  44009. };
  44010. ParticleSystem.prototype._update = function (newParticles) {
  44011. // Update current
  44012. this._alive = this.particles.length > 0;
  44013. this.updateFunction(this.particles);
  44014. // Add new ones
  44015. var worldMatrix;
  44016. if (this.emitter.position) {
  44017. var emitterMesh = this.emitter;
  44018. worldMatrix = emitterMesh.getWorldMatrix();
  44019. }
  44020. else {
  44021. var emitterPosition = this.emitter;
  44022. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44023. }
  44024. var particle;
  44025. for (var index = 0; index < newParticles; index++) {
  44026. if (this.particles.length === this._capacity) {
  44027. break;
  44028. }
  44029. if (this._stockParticles.length !== 0) {
  44030. particle = this._stockParticles.pop();
  44031. particle.age = 0;
  44032. particle.cellIndex = this.startSpriteCellID;
  44033. }
  44034. else {
  44035. particle = new BABYLON.Particle(this);
  44036. }
  44037. this.particles.push(particle);
  44038. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44039. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44040. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44041. particle.size = randomNumber(this.minSize, this.maxSize);
  44042. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44043. this.startPositionFunction(worldMatrix, particle.position, particle);
  44044. var step = randomNumber(0, 1.0);
  44045. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44046. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44047. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44048. }
  44049. };
  44050. ParticleSystem.prototype._getEffect = function () {
  44051. if (this._customEffect) {
  44052. return this._customEffect;
  44053. }
  44054. ;
  44055. var defines = [];
  44056. if (this._scene.clipPlane) {
  44057. defines.push("#define CLIPPLANE");
  44058. }
  44059. if (this._isAnimationSheetEnabled) {
  44060. defines.push("#define ANIMATESHEET");
  44061. }
  44062. // Effect
  44063. var join = defines.join("\n");
  44064. if (this._cachedDefines !== join) {
  44065. this._cachedDefines = join;
  44066. var attributesNamesOrOptions;
  44067. var effectCreationOption;
  44068. if (this._isAnimationSheetEnabled) {
  44069. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44070. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44071. }
  44072. else {
  44073. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44074. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44075. }
  44076. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44077. }
  44078. return this._effect;
  44079. };
  44080. ParticleSystem.prototype.animate = function () {
  44081. if (!this._started)
  44082. return;
  44083. var effect = this._getEffect();
  44084. // Check
  44085. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44086. return;
  44087. if (this._currentRenderId === this._scene.getRenderId()) {
  44088. return;
  44089. }
  44090. this._currentRenderId = this._scene.getRenderId();
  44091. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44092. // determine the number of particles we need to create
  44093. var newParticles;
  44094. if (this.manualEmitCount > -1) {
  44095. newParticles = this.manualEmitCount;
  44096. this._newPartsExcess = 0;
  44097. this.manualEmitCount = 0;
  44098. }
  44099. else {
  44100. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44101. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44102. }
  44103. if (this._newPartsExcess > 1.0) {
  44104. newParticles += this._newPartsExcess >> 0;
  44105. this._newPartsExcess -= this._newPartsExcess >> 0;
  44106. }
  44107. this._alive = false;
  44108. if (!this._stopped) {
  44109. this._actualFrame += this._scaledUpdateSpeed;
  44110. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44111. this.stop();
  44112. }
  44113. else {
  44114. newParticles = 0;
  44115. }
  44116. this._update(newParticles);
  44117. // Stopped?
  44118. if (this._stopped) {
  44119. if (!this._alive) {
  44120. this._started = false;
  44121. if (this.onAnimationEnd) {
  44122. this.onAnimationEnd();
  44123. }
  44124. if (this.disposeOnStop) {
  44125. this._scene._toBeDisposed.push(this);
  44126. }
  44127. }
  44128. }
  44129. // Animation sheet
  44130. if (this._isAnimationSheetEnabled) {
  44131. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44132. }
  44133. else {
  44134. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44135. }
  44136. // Update VBO
  44137. var offset = 0;
  44138. for (var index = 0; index < this.particles.length; index++) {
  44139. var particle = this.particles[index];
  44140. this.appendParticleVertexes(offset, particle);
  44141. offset += 4;
  44142. }
  44143. if (this._vertexBuffer) {
  44144. this._vertexBuffer.update(this._vertexData);
  44145. }
  44146. };
  44147. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44148. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44149. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44150. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44151. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44152. };
  44153. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44154. this._appendParticleVertex(offset++, particle, 0, 0);
  44155. this._appendParticleVertex(offset++, particle, 1, 0);
  44156. this._appendParticleVertex(offset++, particle, 1, 1);
  44157. this._appendParticleVertex(offset++, particle, 0, 1);
  44158. };
  44159. ParticleSystem.prototype.rebuild = function () {
  44160. this._createIndexBuffer();
  44161. if (this._vertexBuffer) {
  44162. this._vertexBuffer._rebuild();
  44163. }
  44164. };
  44165. ParticleSystem.prototype.render = function () {
  44166. var effect = this._getEffect();
  44167. // Check
  44168. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44169. return 0;
  44170. var engine = this._scene.getEngine();
  44171. // Render
  44172. engine.enableEffect(effect);
  44173. engine.setState(false);
  44174. var viewMatrix = this._scene.getViewMatrix();
  44175. effect.setTexture("diffuseSampler", this.particleTexture);
  44176. effect.setMatrix("view", viewMatrix);
  44177. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44178. if (this._isAnimationSheetEnabled) {
  44179. var baseSize = this.particleTexture.getBaseSize();
  44180. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44181. }
  44182. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44183. if (this._scene.clipPlane) {
  44184. var clipPlane = this._scene.clipPlane;
  44185. var invView = viewMatrix.clone();
  44186. invView.invert();
  44187. effect.setMatrix("invView", invView);
  44188. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44189. }
  44190. // VBOs
  44191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44192. // Draw order
  44193. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44194. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44195. }
  44196. else {
  44197. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44198. }
  44199. if (this.forceDepthWrite) {
  44200. engine.setDepthWrite(true);
  44201. }
  44202. engine.draw(true, 0, this.particles.length * 6);
  44203. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44204. return this.particles.length;
  44205. };
  44206. ParticleSystem.prototype.dispose = function () {
  44207. if (this._vertexBuffer) {
  44208. this._vertexBuffer.dispose();
  44209. this._vertexBuffer = null;
  44210. }
  44211. if (this._indexBuffer) {
  44212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44213. this._indexBuffer = null;
  44214. }
  44215. if (this.particleTexture) {
  44216. this.particleTexture.dispose();
  44217. this.particleTexture = null;
  44218. }
  44219. // Remove from scene
  44220. var index = this._scene.particleSystems.indexOf(this);
  44221. if (index > -1) {
  44222. this._scene.particleSystems.splice(index, 1);
  44223. }
  44224. // Callback
  44225. this.onDisposeObservable.notifyObservers(this);
  44226. this.onDisposeObservable.clear();
  44227. };
  44228. // Clone
  44229. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44230. var custom = null;
  44231. var program = null;
  44232. if (this.customShader != null) {
  44233. program = this.customShader;
  44234. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44235. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44236. }
  44237. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44238. result.customShader = program;
  44239. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44240. if (newEmitter === undefined) {
  44241. newEmitter = this.emitter;
  44242. }
  44243. result.emitter = newEmitter;
  44244. if (this.particleTexture) {
  44245. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44246. }
  44247. if (!this.preventAutoStart) {
  44248. result.start();
  44249. }
  44250. return result;
  44251. };
  44252. ParticleSystem.prototype.serialize = function () {
  44253. var serializationObject = {};
  44254. serializationObject.name = this.name;
  44255. serializationObject.id = this.id;
  44256. // Emitter
  44257. if (this.emitter.position) {
  44258. var emitterMesh = this.emitter;
  44259. serializationObject.emitterId = emitterMesh.id;
  44260. }
  44261. else {
  44262. var emitterPosition = this.emitter;
  44263. serializationObject.emitter = emitterPosition.asArray();
  44264. }
  44265. serializationObject.capacity = this.getCapacity();
  44266. if (this.particleTexture) {
  44267. serializationObject.textureName = this.particleTexture.name;
  44268. }
  44269. // Animations
  44270. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44271. // Particle system
  44272. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44273. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44274. serializationObject.minSize = this.minSize;
  44275. serializationObject.maxSize = this.maxSize;
  44276. serializationObject.minEmitPower = this.minEmitPower;
  44277. serializationObject.maxEmitPower = this.maxEmitPower;
  44278. serializationObject.minLifeTime = this.minLifeTime;
  44279. serializationObject.maxLifeTime = this.maxLifeTime;
  44280. serializationObject.emitRate = this.emitRate;
  44281. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44282. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44283. serializationObject.gravity = this.gravity.asArray();
  44284. serializationObject.direction1 = this.direction1.asArray();
  44285. serializationObject.direction2 = this.direction2.asArray();
  44286. serializationObject.color1 = this.color1.asArray();
  44287. serializationObject.color2 = this.color2.asArray();
  44288. serializationObject.colorDead = this.colorDead.asArray();
  44289. serializationObject.updateSpeed = this.updateSpeed;
  44290. serializationObject.targetStopDuration = this.targetStopDuration;
  44291. serializationObject.textureMask = this.textureMask.asArray();
  44292. serializationObject.blendMode = this.blendMode;
  44293. serializationObject.customShader = this.customShader;
  44294. serializationObject.preventAutoStart = this.preventAutoStart;
  44295. return serializationObject;
  44296. };
  44297. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44298. var name = parsedParticleSystem.name;
  44299. var custom = null;
  44300. var program = null;
  44301. if (parsedParticleSystem.customShader) {
  44302. program = parsedParticleSystem.customShader;
  44303. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44304. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44305. }
  44306. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44307. particleSystem.customShader = program;
  44308. if (parsedParticleSystem.id) {
  44309. particleSystem.id = parsedParticleSystem.id;
  44310. }
  44311. // Auto start
  44312. if (parsedParticleSystem.preventAutoStart) {
  44313. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44314. }
  44315. // Texture
  44316. if (parsedParticleSystem.textureName) {
  44317. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44318. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44319. }
  44320. // Emitter
  44321. if (parsedParticleSystem.emitterId) {
  44322. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44323. }
  44324. else {
  44325. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44326. }
  44327. // Animations
  44328. if (parsedParticleSystem.animations) {
  44329. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44330. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44331. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44332. }
  44333. }
  44334. if (parsedParticleSystem.autoAnimate) {
  44335. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44336. }
  44337. // Particle system
  44338. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44339. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44340. particleSystem.minSize = parsedParticleSystem.minSize;
  44341. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44342. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44343. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44344. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44345. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44346. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44347. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44348. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44349. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44350. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44351. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44352. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44353. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44354. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44355. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44356. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44357. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44358. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44359. if (!particleSystem.preventAutoStart) {
  44360. particleSystem.start();
  44361. }
  44362. return particleSystem;
  44363. };
  44364. // Statics
  44365. ParticleSystem.BLENDMODE_ONEONE = 0;
  44366. ParticleSystem.BLENDMODE_STANDARD = 1;
  44367. return ParticleSystem;
  44368. }());
  44369. BABYLON.ParticleSystem = ParticleSystem;
  44370. })(BABYLON || (BABYLON = {}));
  44371. //# sourceMappingURL=babylon.particleSystem.js.map
  44372. var BABYLON;
  44373. (function (BABYLON) {
  44374. var SolidParticle = /** @class */ (function () {
  44375. /**
  44376. * Creates a Solid Particle object.
  44377. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44378. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44379. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44380. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44381. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44382. * `shapeId` (integer) is the model shape identifier in the SPS.
  44383. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44384. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44385. */
  44386. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44387. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44388. this.idx = 0; // particle global index
  44389. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44390. this.position = BABYLON.Vector3.Zero(); // position
  44391. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44392. this.scaling = BABYLON.Vector3.One(); // scaling
  44393. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44394. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44395. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44396. this.alive = true; // alive
  44397. this.isVisible = true; // visibility
  44398. this._pos = 0; // index of this particle in the global "positions" array
  44399. this._ind = 0; // index of this particle in the global "indices" array
  44400. this.shapeId = 0; // model shape id
  44401. this.idxInShape = 0; // index of the particle in its shape id
  44402. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44403. this.idx = particleIndex;
  44404. this._pos = positionIndex;
  44405. this._ind = indiceIndex;
  44406. this._model = model;
  44407. this.shapeId = shapeId;
  44408. this.idxInShape = idxInShape;
  44409. this._sps = sps;
  44410. if (modelBoundingInfo) {
  44411. this._modelBoundingInfo = modelBoundingInfo;
  44412. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44413. }
  44414. }
  44415. Object.defineProperty(SolidParticle.prototype, "scale", {
  44416. /**
  44417. * legacy support, changed scale to scaling
  44418. */
  44419. get: function () {
  44420. return this.scaling;
  44421. },
  44422. set: function (scale) {
  44423. this.scaling = scale;
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44429. /**
  44430. * legacy support, changed quaternion to rotationQuaternion
  44431. */
  44432. get: function () {
  44433. return this.rotationQuaternion;
  44434. },
  44435. set: function (q) {
  44436. this.rotationQuaternion = q;
  44437. },
  44438. enumerable: true,
  44439. configurable: true
  44440. });
  44441. /**
  44442. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44443. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44444. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44445. */
  44446. SolidParticle.prototype.intersectsMesh = function (target) {
  44447. if (!this._boundingInfo || !target._boundingInfo) {
  44448. return false;
  44449. }
  44450. if (this._sps._bSphereOnly) {
  44451. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44452. }
  44453. return this._boundingInfo.intersects(target._boundingInfo, false);
  44454. };
  44455. return SolidParticle;
  44456. }());
  44457. BABYLON.SolidParticle = SolidParticle;
  44458. var ModelShape = /** @class */ (function () {
  44459. /**
  44460. * 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.
  44461. * SPS internal tool, don't use it manually.
  44462. */
  44463. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44464. this._indicesLength = 0; // length of the shape in the model indices array
  44465. this.shapeID = id;
  44466. this._shape = shape;
  44467. this._indicesLength = indicesLength;
  44468. this._shapeUV = shapeUV;
  44469. this._positionFunction = posFunction;
  44470. this._vertexFunction = vtxFunction;
  44471. }
  44472. return ModelShape;
  44473. }());
  44474. BABYLON.ModelShape = ModelShape;
  44475. var DepthSortedParticle = /** @class */ (function () {
  44476. function DepthSortedParticle() {
  44477. this.ind = 0; // index of the particle in the "indices" array
  44478. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44479. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44480. }
  44481. return DepthSortedParticle;
  44482. }());
  44483. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44484. })(BABYLON || (BABYLON = {}));
  44485. //# sourceMappingURL=babylon.solidParticle.js.map
  44486. var BABYLON;
  44487. (function (BABYLON) {
  44488. /**
  44489. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44490. */
  44491. var SolidParticleSystem = /** @class */ (function () {
  44492. /**
  44493. * Creates a SPS (Solid Particle System) object.
  44494. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44495. * `scene` (Scene) is the scene in which the SPS is added.
  44496. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44497. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44498. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44499. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44500. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44501. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44502. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44503. */
  44504. function SolidParticleSystem(name, scene, options) {
  44505. // public members
  44506. /**
  44507. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44508. * Example : var p = SPS.particles[i];
  44509. */
  44510. this.particles = new Array();
  44511. /**
  44512. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44513. */
  44514. this.nbParticles = 0;
  44515. /**
  44516. * If the particles must ever face the camera (default false). Useful for planar particles.
  44517. */
  44518. this.billboard = false;
  44519. /**
  44520. * Recompute normals when adding a shape
  44521. */
  44522. this.recomputeNormals = true;
  44523. /**
  44524. * This a counter ofr your own usage. It's not set by any SPS functions.
  44525. */
  44526. this.counter = 0;
  44527. /**
  44528. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44529. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44530. */
  44531. this.vars = {};
  44532. this._positions = new Array();
  44533. this._indices = new Array();
  44534. this._normals = new Array();
  44535. this._colors = new Array();
  44536. this._uvs = new Array();
  44537. this._index = 0; // indices index
  44538. this._updatable = true;
  44539. this._pickable = false;
  44540. this._isVisibilityBoxLocked = false;
  44541. this._alwaysVisible = false;
  44542. this._depthSort = false;
  44543. this._shapeCounter = 0;
  44544. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44545. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44546. this._computeParticleColor = true;
  44547. this._computeParticleTexture = true;
  44548. this._computeParticleRotation = true;
  44549. this._computeParticleVertex = false;
  44550. this._computeBoundingBox = false;
  44551. this._depthSortParticles = true;
  44552. this._cam_axisZ = BABYLON.Vector3.Zero();
  44553. this._cam_axisY = BABYLON.Vector3.Zero();
  44554. this._cam_axisX = BABYLON.Vector3.Zero();
  44555. this._axisZ = BABYLON.Axis.Z;
  44556. this._camDir = BABYLON.Vector3.Zero();
  44557. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44558. this._rotMatrix = new BABYLON.Matrix();
  44559. this._invertMatrix = new BABYLON.Matrix();
  44560. this._rotated = BABYLON.Vector3.Zero();
  44561. this._quaternion = new BABYLON.Quaternion();
  44562. this._vertex = BABYLON.Vector3.Zero();
  44563. this._normal = BABYLON.Vector3.Zero();
  44564. this._yaw = 0.0;
  44565. this._pitch = 0.0;
  44566. this._roll = 0.0;
  44567. this._halfroll = 0.0;
  44568. this._halfpitch = 0.0;
  44569. this._halfyaw = 0.0;
  44570. this._sinRoll = 0.0;
  44571. this._cosRoll = 0.0;
  44572. this._sinPitch = 0.0;
  44573. this._cosPitch = 0.0;
  44574. this._sinYaw = 0.0;
  44575. this._cosYaw = 0.0;
  44576. this._mustUnrotateFixedNormals = false;
  44577. this._minimum = BABYLON.Tmp.Vector3[0];
  44578. this._maximum = BABYLON.Tmp.Vector3[1];
  44579. this._minBbox = BABYLON.Tmp.Vector3[4];
  44580. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44581. this._particlesIntersect = false;
  44582. this._depthSortFunction = function (p1, p2) {
  44583. return (p2.sqDistance - p1.sqDistance);
  44584. };
  44585. this._needs32Bits = false;
  44586. this._bSphereOnly = false;
  44587. this._bSphereRadiusFactor = 1.0;
  44588. this.name = name;
  44589. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44590. this._camera = scene.activeCamera;
  44591. this._pickable = options ? options.isPickable : false;
  44592. this._depthSort = options ? options.enableDepthSort : false;
  44593. this._particlesIntersect = options ? options.particleIntersection : false;
  44594. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44595. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44596. if (options && options.updatable) {
  44597. this._updatable = options.updatable;
  44598. }
  44599. else {
  44600. this._updatable = true;
  44601. }
  44602. if (this._pickable) {
  44603. this.pickedParticles = [];
  44604. }
  44605. if (this._depthSort) {
  44606. this.depthSortedParticles = [];
  44607. }
  44608. }
  44609. /**
  44610. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44611. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44612. */
  44613. SolidParticleSystem.prototype.buildMesh = function () {
  44614. if (this.nbParticles === 0) {
  44615. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44616. this.addShape(triangle, 1);
  44617. triangle.dispose();
  44618. }
  44619. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44620. this._positions32 = new Float32Array(this._positions);
  44621. this._uvs32 = new Float32Array(this._uvs);
  44622. this._colors32 = new Float32Array(this._colors);
  44623. if (this.recomputeNormals) {
  44624. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44625. }
  44626. this._normals32 = new Float32Array(this._normals);
  44627. this._fixedNormal32 = new Float32Array(this._normals);
  44628. if (this._mustUnrotateFixedNormals) {
  44629. this._unrotateFixedNormals();
  44630. }
  44631. var vertexData = new BABYLON.VertexData();
  44632. vertexData.indices = this._indices32;
  44633. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44634. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44635. if (this._uvs32) {
  44636. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44637. ;
  44638. }
  44639. if (this._colors32) {
  44640. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  44641. }
  44642. var mesh = new BABYLON.Mesh(this.name, this._scene);
  44643. vertexData.applyToMesh(mesh, this._updatable);
  44644. this.mesh = mesh;
  44645. this.mesh.isPickable = this._pickable;
  44646. // free memory
  44647. if (!this._depthSort) {
  44648. this._indices = null;
  44649. }
  44650. this._positions = null;
  44651. this._normals = null;
  44652. this._uvs = null;
  44653. this._colors = null;
  44654. if (!this._updatable) {
  44655. this.particles.length = 0;
  44656. }
  44657. return mesh;
  44658. };
  44659. /**
  44660. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  44661. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  44662. * Thus the particles generated from `digest()` have their property `position` set yet.
  44663. * `mesh` ( Mesh ) is the mesh to be digested
  44664. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  44665. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  44666. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  44667. */
  44668. SolidParticleSystem.prototype.digest = function (mesh, options) {
  44669. var size = (options && options.facetNb) || 1;
  44670. var number = (options && options.number) || 0;
  44671. var delta = (options && options.delta) || 0;
  44672. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44673. var meshInd = mesh.getIndices();
  44674. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44675. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44676. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44677. var f = 0; // facet counter
  44678. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  44679. // compute size from number
  44680. if (number) {
  44681. number = (number > totalFacets) ? totalFacets : number;
  44682. size = Math.round(totalFacets / number);
  44683. delta = 0;
  44684. }
  44685. else {
  44686. size = (size > totalFacets) ? totalFacets : size;
  44687. }
  44688. var facetPos = []; // submesh positions
  44689. var facetInd = []; // submesh indices
  44690. var facetUV = []; // submesh UV
  44691. var facetCol = []; // submesh colors
  44692. var barycenter = BABYLON.Tmp.Vector3[0];
  44693. var sizeO = size;
  44694. while (f < totalFacets) {
  44695. size = sizeO + Math.floor((1 + delta) * Math.random());
  44696. if (f > totalFacets - size) {
  44697. size = totalFacets - f;
  44698. }
  44699. // reset temp arrays
  44700. facetPos.length = 0;
  44701. facetInd.length = 0;
  44702. facetUV.length = 0;
  44703. facetCol.length = 0;
  44704. // iterate over "size" facets
  44705. var fi = 0;
  44706. for (var j = f * 3; j < (f + size) * 3; j++) {
  44707. facetInd.push(fi);
  44708. var i = meshInd[j];
  44709. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  44710. if (meshUV) {
  44711. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  44712. }
  44713. if (meshCol) {
  44714. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  44715. }
  44716. fi++;
  44717. }
  44718. // create a model shape for each single particle
  44719. var idx = this.nbParticles;
  44720. var shape = this._posToShape(facetPos);
  44721. var shapeUV = this._uvsToShapeUV(facetUV);
  44722. // compute the barycenter of the shape
  44723. var v;
  44724. for (v = 0; v < shape.length; v++) {
  44725. barycenter.addInPlace(shape[v]);
  44726. }
  44727. barycenter.scaleInPlace(1 / shape.length);
  44728. // shift the shape from its barycenter to the origin
  44729. for (v = 0; v < shape.length; v++) {
  44730. shape[v].subtractInPlace(barycenter);
  44731. }
  44732. var bInfo;
  44733. if (this._particlesIntersect) {
  44734. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  44735. }
  44736. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  44737. // add the particle in the SPS
  44738. var currentPos = this._positions.length;
  44739. var currentInd = this._indices.length;
  44740. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  44741. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  44742. // initialize the particle position
  44743. this.particles[this.nbParticles].position.addInPlace(barycenter);
  44744. this._index += shape.length;
  44745. idx++;
  44746. this.nbParticles++;
  44747. this._shapeCounter++;
  44748. f += size;
  44749. }
  44750. return this;
  44751. };
  44752. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  44753. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  44754. var index = 0;
  44755. var idx = 0;
  44756. for (var p = 0; p < this.particles.length; p++) {
  44757. this._particle = this.particles[p];
  44758. this._shape = this._particle._model._shape;
  44759. if (this._particle.rotationQuaternion) {
  44760. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  44761. }
  44762. else {
  44763. this._yaw = this._particle.rotation.y;
  44764. this._pitch = this._particle.rotation.x;
  44765. this._roll = this._particle.rotation.z;
  44766. this._quaternionRotationYPR();
  44767. }
  44768. this._quaternionToRotationMatrix();
  44769. this._rotMatrix.invertToRef(this._invertMatrix);
  44770. for (var pt = 0; pt < this._shape.length; pt++) {
  44771. idx = index + pt * 3;
  44772. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  44773. this._fixedNormal32[idx] = this._normal.x;
  44774. this._fixedNormal32[idx + 1] = this._normal.y;
  44775. this._fixedNormal32[idx + 2] = this._normal.z;
  44776. }
  44777. index = idx + 3;
  44778. }
  44779. };
  44780. //reset copy
  44781. SolidParticleSystem.prototype._resetCopy = function () {
  44782. this._copy.position.x = 0;
  44783. this._copy.position.y = 0;
  44784. this._copy.position.z = 0;
  44785. this._copy.rotation.x = 0;
  44786. this._copy.rotation.y = 0;
  44787. this._copy.rotation.z = 0;
  44788. this._copy.rotationQuaternion = null;
  44789. this._copy.scaling.x = 1.0;
  44790. this._copy.scaling.y = 1.0;
  44791. this._copy.scaling.z = 1.0;
  44792. this._copy.uvs.x = 0;
  44793. this._copy.uvs.y = 0;
  44794. this._copy.uvs.z = 1.0;
  44795. this._copy.uvs.w = 1.0;
  44796. this._copy.color = null;
  44797. };
  44798. // _meshBuilder : inserts the shape model in the global SPS mesh
  44799. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  44800. var i;
  44801. var u = 0;
  44802. var c = 0;
  44803. var n = 0;
  44804. this._resetCopy();
  44805. if (options && options.positionFunction) {
  44806. options.positionFunction(this._copy, idx, idxInShape);
  44807. this._mustUnrotateFixedNormals = true;
  44808. }
  44809. if (this._copy.rotationQuaternion) {
  44810. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44811. }
  44812. else {
  44813. this._yaw = this._copy.rotation.y;
  44814. this._pitch = this._copy.rotation.x;
  44815. this._roll = this._copy.rotation.z;
  44816. this._quaternionRotationYPR();
  44817. }
  44818. this._quaternionToRotationMatrix();
  44819. for (i = 0; i < shape.length; i++) {
  44820. this._vertex.x = shape[i].x;
  44821. this._vertex.y = shape[i].y;
  44822. this._vertex.z = shape[i].z;
  44823. if (options && options.vertexFunction) {
  44824. options.vertexFunction(this._copy, this._vertex, i);
  44825. }
  44826. this._vertex.x *= this._copy.scaling.x;
  44827. this._vertex.y *= this._copy.scaling.y;
  44828. this._vertex.z *= this._copy.scaling.z;
  44829. this._vertex.x += this._copy.pivot.x;
  44830. this._vertex.y += this._copy.pivot.y;
  44831. this._vertex.z += this._copy.pivot.z;
  44832. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44833. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  44834. if (meshUV) {
  44835. 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);
  44836. u += 2;
  44837. }
  44838. if (this._copy.color) {
  44839. this._color = this._copy.color;
  44840. }
  44841. else if (meshCol && meshCol[c] !== undefined) {
  44842. this._color.r = meshCol[c];
  44843. this._color.g = meshCol[c + 1];
  44844. this._color.b = meshCol[c + 2];
  44845. this._color.a = meshCol[c + 3];
  44846. }
  44847. else {
  44848. this._color.r = 1.0;
  44849. this._color.g = 1.0;
  44850. this._color.b = 1.0;
  44851. this._color.a = 1.0;
  44852. }
  44853. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  44854. c += 4;
  44855. if (!this.recomputeNormals && meshNor) {
  44856. this._normal.x = meshNor[n];
  44857. this._normal.y = meshNor[n + 1];
  44858. this._normal.z = meshNor[n + 2];
  44859. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  44860. normals.push(this._normal.x, this._normal.y, this._normal.z);
  44861. n += 3;
  44862. }
  44863. }
  44864. for (i = 0; i < meshInd.length; i++) {
  44865. var current_ind = p + meshInd[i];
  44866. indices.push(current_ind);
  44867. if (current_ind > 65535) {
  44868. this._needs32Bits = true;
  44869. }
  44870. }
  44871. if (this._pickable) {
  44872. var nbfaces = meshInd.length / 3;
  44873. for (i = 0; i < nbfaces; i++) {
  44874. this.pickedParticles.push({ idx: idx, faceId: i });
  44875. }
  44876. }
  44877. if (this._depthSort) {
  44878. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  44879. }
  44880. return this._copy;
  44881. };
  44882. // returns a shape array from positions array
  44883. SolidParticleSystem.prototype._posToShape = function (positions) {
  44884. var shape = [];
  44885. for (var i = 0; i < positions.length; i += 3) {
  44886. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  44887. }
  44888. return shape;
  44889. };
  44890. // returns a shapeUV array from a Vector4 uvs
  44891. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  44892. var shapeUV = [];
  44893. if (uvs) {
  44894. for (var i = 0; i < uvs.length; i++)
  44895. shapeUV.push(uvs[i]);
  44896. }
  44897. return shapeUV;
  44898. };
  44899. // adds a new particle object in the particles array
  44900. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  44901. if (bInfo === void 0) { bInfo = null; }
  44902. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  44903. this.particles.push(sp);
  44904. return sp;
  44905. };
  44906. /**
  44907. * Adds some particles to the SPS from the model shape. Returns the shape id.
  44908. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  44909. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  44910. * `nb` (positive integer) the number of particles to be created from this model
  44911. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  44912. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  44913. */
  44914. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  44915. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44916. var meshInd = mesh.getIndices();
  44917. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44918. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  44919. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44920. var bbInfo;
  44921. if (this._particlesIntersect) {
  44922. bbInfo = mesh.getBoundingInfo();
  44923. }
  44924. var shape = this._posToShape(meshPos);
  44925. var shapeUV = this._uvsToShapeUV(meshUV);
  44926. var posfunc = options ? options.positionFunction : null;
  44927. var vtxfunc = options ? options.vertexFunction : null;
  44928. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  44929. // particles
  44930. var sp;
  44931. var currentCopy;
  44932. var idx = this.nbParticles;
  44933. for (var i = 0; i < nb; i++) {
  44934. var currentPos = this._positions.length;
  44935. var currentInd = this._indices.length;
  44936. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  44937. if (this._updatable) {
  44938. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  44939. sp.position.copyFrom(currentCopy.position);
  44940. sp.rotation.copyFrom(currentCopy.rotation);
  44941. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  44942. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  44943. }
  44944. if (currentCopy.color && sp.color) {
  44945. sp.color.copyFrom(currentCopy.color);
  44946. }
  44947. sp.scaling.copyFrom(currentCopy.scaling);
  44948. sp.uvs.copyFrom(currentCopy.uvs);
  44949. }
  44950. this._index += shape.length;
  44951. idx++;
  44952. }
  44953. this.nbParticles += nb;
  44954. this._shapeCounter++;
  44955. return this._shapeCounter - 1;
  44956. };
  44957. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  44958. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  44959. this._resetCopy();
  44960. if (particle._model._positionFunction) {
  44961. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  44962. }
  44963. if (this._copy.rotationQuaternion) {
  44964. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  44965. }
  44966. else {
  44967. this._yaw = this._copy.rotation.y;
  44968. this._pitch = this._copy.rotation.x;
  44969. this._roll = this._copy.rotation.z;
  44970. this._quaternionRotationYPR();
  44971. }
  44972. this._quaternionToRotationMatrix();
  44973. this._shape = particle._model._shape;
  44974. for (var pt = 0; pt < this._shape.length; pt++) {
  44975. this._vertex.x = this._shape[pt].x;
  44976. this._vertex.y = this._shape[pt].y;
  44977. this._vertex.z = this._shape[pt].z;
  44978. if (particle._model._vertexFunction) {
  44979. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  44980. }
  44981. this._vertex.x *= this._copy.scaling.x;
  44982. this._vertex.y *= this._copy.scaling.y;
  44983. this._vertex.z *= this._copy.scaling.z;
  44984. this._vertex.x += this._copy.pivot.x;
  44985. this._vertex.y += this._copy.pivot.y;
  44986. this._vertex.z += this._copy.pivot.z;
  44987. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  44988. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  44989. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  44990. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  44991. }
  44992. particle.position.x = 0.0;
  44993. particle.position.y = 0.0;
  44994. particle.position.z = 0.0;
  44995. particle.rotation.x = 0.0;
  44996. particle.rotation.y = 0.0;
  44997. particle.rotation.z = 0.0;
  44998. particle.rotationQuaternion = null;
  44999. particle.scaling.x = 1.0;
  45000. particle.scaling.y = 1.0;
  45001. particle.scaling.z = 1.0;
  45002. };
  45003. /**
  45004. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45005. * Returns the SPS.
  45006. */
  45007. SolidParticleSystem.prototype.rebuildMesh = function () {
  45008. for (var p = 0; p < this.particles.length; p++) {
  45009. this._rebuildParticle(this.particles[p]);
  45010. }
  45011. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45012. return this;
  45013. };
  45014. /**
  45015. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45016. * This method calls `updateParticle()` for each particle of the SPS.
  45017. * For an animated SPS, it is usually called within the render loop.
  45018. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45019. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45020. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45021. * Returns the SPS.
  45022. */
  45023. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45024. if (start === void 0) { start = 0; }
  45025. if (end === void 0) { end = this.nbParticles - 1; }
  45026. if (update === void 0) { update = true; }
  45027. if (!this._updatable) {
  45028. return this;
  45029. }
  45030. // custom beforeUpdate
  45031. this.beforeUpdateParticles(start, end, update);
  45032. this._cam_axisX.x = 1.0;
  45033. this._cam_axisX.y = 0.0;
  45034. this._cam_axisX.z = 0.0;
  45035. this._cam_axisY.x = 0.0;
  45036. this._cam_axisY.y = 1.0;
  45037. this._cam_axisY.z = 0.0;
  45038. this._cam_axisZ.x = 0.0;
  45039. this._cam_axisZ.y = 0.0;
  45040. this._cam_axisZ.z = 1.0;
  45041. // cases when the World Matrix is to be computed first
  45042. if (this.billboard || this._depthSort) {
  45043. this.mesh.computeWorldMatrix(true);
  45044. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45045. }
  45046. // if the particles will always face the camera
  45047. if (this.billboard) {
  45048. // compute the camera position and un-rotate it by the current mesh rotation
  45049. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45050. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45051. this._cam_axisZ.normalize();
  45052. // same for camera up vector extracted from the cam view matrix
  45053. var view = this._camera.getViewMatrix(true);
  45054. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45055. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45056. this._cam_axisY.normalize();
  45057. this._cam_axisX.normalize();
  45058. }
  45059. // if depthSort, compute the camera global position in the mesh local system
  45060. if (this._depthSort) {
  45061. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45062. }
  45063. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45064. var idx = 0; // current position index in the global array positions32
  45065. var index = 0; // position start index in the global array positions32 of the current particle
  45066. var colidx = 0; // current color index in the global array colors32
  45067. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45068. var uvidx = 0; // current uv index in the global array uvs32
  45069. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45070. var pt = 0; // current index in the particle model shape
  45071. if (this.mesh.isFacetDataEnabled) {
  45072. this._computeBoundingBox = true;
  45073. }
  45074. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45075. if (this._computeBoundingBox) {
  45076. if (start == 0 && end == this.nbParticles - 1) {
  45077. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45078. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45079. }
  45080. else {
  45081. if (this.mesh._boundingInfo) {
  45082. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45083. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45084. }
  45085. }
  45086. }
  45087. // particle loop
  45088. index = this.particles[start]._pos;
  45089. var vpos = (index / 3) | 0;
  45090. colorIndex = vpos * 4;
  45091. uvIndex = vpos * 2;
  45092. for (var p = start; p <= end; p++) {
  45093. this._particle = this.particles[p];
  45094. this._shape = this._particle._model._shape;
  45095. this._shapeUV = this._particle._model._shapeUV;
  45096. // call to custom user function to update the particle properties
  45097. this.updateParticle(this._particle);
  45098. // camera-particle distance for depth sorting
  45099. if (this._depthSort && this._depthSortParticles) {
  45100. var dsp = this.depthSortedParticles[p];
  45101. dsp.ind = this._particle._ind;
  45102. dsp.indicesLength = this._particle._model._indicesLength;
  45103. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45104. }
  45105. // skip the computations for inactive or already invisible particles
  45106. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45107. // increment indexes for the next particle
  45108. pt = this._shape.length;
  45109. index += pt * 3;
  45110. colorIndex += pt * 4;
  45111. uvIndex += pt * 2;
  45112. continue;
  45113. }
  45114. if (this._particle.isVisible) {
  45115. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45116. // particle rotation matrix
  45117. if (this.billboard) {
  45118. this._particle.rotation.x = 0.0;
  45119. this._particle.rotation.y = 0.0;
  45120. }
  45121. if (this._computeParticleRotation || this.billboard) {
  45122. if (this._particle.rotationQuaternion) {
  45123. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45124. }
  45125. else {
  45126. this._yaw = this._particle.rotation.y;
  45127. this._pitch = this._particle.rotation.x;
  45128. this._roll = this._particle.rotation.z;
  45129. this._quaternionRotationYPR();
  45130. }
  45131. this._quaternionToRotationMatrix();
  45132. }
  45133. // particle vertex loop
  45134. for (pt = 0; pt < this._shape.length; pt++) {
  45135. idx = index + pt * 3;
  45136. colidx = colorIndex + pt * 4;
  45137. uvidx = uvIndex + pt * 2;
  45138. this._vertex.x = this._shape[pt].x;
  45139. this._vertex.y = this._shape[pt].y;
  45140. this._vertex.z = this._shape[pt].z;
  45141. if (this._computeParticleVertex) {
  45142. this.updateParticleVertex(this._particle, this._vertex, pt);
  45143. }
  45144. // positions
  45145. this._vertex.x *= this._particle.scaling.x;
  45146. this._vertex.y *= this._particle.scaling.y;
  45147. this._vertex.z *= this._particle.scaling.z;
  45148. this._vertex.x += this._particle.pivot.x;
  45149. this._vertex.y += this._particle.pivot.y;
  45150. this._vertex.z += this._particle.pivot.z;
  45151. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45152. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45153. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45154. 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;
  45155. 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;
  45156. 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;
  45157. if (this._computeBoundingBox) {
  45158. if (this._positions32[idx] < this._minimum.x) {
  45159. this._minimum.x = this._positions32[idx];
  45160. }
  45161. if (this._positions32[idx] > this._maximum.x) {
  45162. this._maximum.x = this._positions32[idx];
  45163. }
  45164. if (this._positions32[idx + 1] < this._minimum.y) {
  45165. this._minimum.y = this._positions32[idx + 1];
  45166. }
  45167. if (this._positions32[idx + 1] > this._maximum.y) {
  45168. this._maximum.y = this._positions32[idx + 1];
  45169. }
  45170. if (this._positions32[idx + 2] < this._minimum.z) {
  45171. this._minimum.z = this._positions32[idx + 2];
  45172. }
  45173. if (this._positions32[idx + 2] > this._maximum.z) {
  45174. this._maximum.z = this._positions32[idx + 2];
  45175. }
  45176. }
  45177. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45178. if (!this._computeParticleVertex) {
  45179. this._normal.x = this._fixedNormal32[idx];
  45180. this._normal.y = this._fixedNormal32[idx + 1];
  45181. this._normal.z = this._fixedNormal32[idx + 2];
  45182. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45183. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45184. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45185. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45186. 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;
  45187. 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;
  45188. }
  45189. if (this._computeParticleColor && this._particle.color) {
  45190. this._colors32[colidx] = this._particle.color.r;
  45191. this._colors32[colidx + 1] = this._particle.color.g;
  45192. this._colors32[colidx + 2] = this._particle.color.b;
  45193. this._colors32[colidx + 3] = this._particle.color.a;
  45194. }
  45195. if (this._computeParticleTexture) {
  45196. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45197. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45198. }
  45199. }
  45200. }
  45201. else {
  45202. this._particle._stillInvisible = true; // mark the particle as invisible
  45203. for (pt = 0; pt < this._shape.length; pt++) {
  45204. idx = index + pt * 3;
  45205. colidx = colorIndex + pt * 4;
  45206. uvidx = uvIndex + pt * 2;
  45207. this._positions32[idx] = 0.0;
  45208. this._positions32[idx + 1] = 0.0;
  45209. this._positions32[idx + 2] = 0.0;
  45210. this._normals32[idx] = 0.0;
  45211. this._normals32[idx + 1] = 0.0;
  45212. this._normals32[idx + 2] = 0.0;
  45213. if (this._computeParticleColor && this._particle.color) {
  45214. this._colors32[colidx] = this._particle.color.r;
  45215. this._colors32[colidx + 1] = this._particle.color.g;
  45216. this._colors32[colidx + 2] = this._particle.color.b;
  45217. this._colors32[colidx + 3] = this._particle.color.a;
  45218. }
  45219. if (this._computeParticleTexture) {
  45220. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45221. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45222. }
  45223. }
  45224. }
  45225. // if the particle intersections must be computed : update the bbInfo
  45226. if (this._particlesIntersect) {
  45227. var bInfo = this._particle._boundingInfo;
  45228. var bBox = bInfo.boundingBox;
  45229. var bSphere = bInfo.boundingSphere;
  45230. if (!this._bSphereOnly) {
  45231. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45232. for (var b = 0; b < bBox.vectors.length; b++) {
  45233. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45234. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45235. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45236. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45237. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45238. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45239. 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;
  45240. 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;
  45241. 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;
  45242. }
  45243. bBox._update(this.mesh._worldMatrix);
  45244. }
  45245. // place and scale the particle bouding sphere in the SPS local system, then update it
  45246. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45247. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45248. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45249. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45250. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45251. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45252. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45253. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45254. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45255. 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));
  45256. bSphere._update(this.mesh._worldMatrix);
  45257. }
  45258. // increment indexes for the next particle
  45259. index = idx + 3;
  45260. colorIndex = colidx + 4;
  45261. uvIndex = uvidx + 2;
  45262. }
  45263. // if the VBO must be updated
  45264. if (update) {
  45265. if (this._computeParticleColor) {
  45266. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45267. }
  45268. if (this._computeParticleTexture) {
  45269. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45270. }
  45271. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45272. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45273. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45274. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45275. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45276. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45277. for (var i = 0; i < this._normals32.length; i++) {
  45278. this._fixedNormal32[i] = this._normals32[i];
  45279. }
  45280. }
  45281. if (!this.mesh.areNormalsFrozen) {
  45282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45283. }
  45284. }
  45285. if (this._depthSort && this._depthSortParticles) {
  45286. this.depthSortedParticles.sort(this._depthSortFunction);
  45287. var dspl = this.depthSortedParticles.length;
  45288. var sorted = 0;
  45289. var lind = 0;
  45290. var sind = 0;
  45291. var sid = 0;
  45292. for (sorted = 0; sorted < dspl; sorted++) {
  45293. lind = this.depthSortedParticles[sorted].indicesLength;
  45294. sind = this.depthSortedParticles[sorted].ind;
  45295. for (var i = 0; i < lind; i++) {
  45296. this._indices32[sid] = this._indices[sind + i];
  45297. sid++;
  45298. }
  45299. }
  45300. this.mesh.updateIndices(this._indices32);
  45301. }
  45302. }
  45303. if (this._computeBoundingBox) {
  45304. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45305. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45306. }
  45307. this.afterUpdateParticles(start, end, update);
  45308. return this;
  45309. };
  45310. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45311. this._halfroll = this._roll * 0.5;
  45312. this._halfpitch = this._pitch * 0.5;
  45313. this._halfyaw = this._yaw * 0.5;
  45314. this._sinRoll = Math.sin(this._halfroll);
  45315. this._cosRoll = Math.cos(this._halfroll);
  45316. this._sinPitch = Math.sin(this._halfpitch);
  45317. this._cosPitch = Math.cos(this._halfpitch);
  45318. this._sinYaw = Math.sin(this._halfyaw);
  45319. this._cosYaw = Math.cos(this._halfyaw);
  45320. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45321. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45322. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45323. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45324. };
  45325. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45326. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45327. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45328. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45329. this._rotMatrix.m[3] = 0;
  45330. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45331. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45332. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45333. this._rotMatrix.m[7] = 0;
  45334. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45335. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45336. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45337. this._rotMatrix.m[11] = 0;
  45338. this._rotMatrix.m[12] = 0;
  45339. this._rotMatrix.m[13] = 0;
  45340. this._rotMatrix.m[14] = 0;
  45341. this._rotMatrix.m[15] = 1.0;
  45342. };
  45343. /**
  45344. * Disposes the SPS.
  45345. * Returns nothing.
  45346. */
  45347. SolidParticleSystem.prototype.dispose = function () {
  45348. this.mesh.dispose();
  45349. this.vars = null;
  45350. // drop references to internal big arrays for the GC
  45351. this._positions = null;
  45352. this._indices = null;
  45353. this._normals = null;
  45354. this._uvs = null;
  45355. this._colors = null;
  45356. this._indices32 = null;
  45357. this._positions32 = null;
  45358. this._normals32 = null;
  45359. this._fixedNormal32 = null;
  45360. this._uvs32 = null;
  45361. this._colors32 = null;
  45362. this.pickedParticles = null;
  45363. };
  45364. /**
  45365. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45367. * Returns the SPS.
  45368. */
  45369. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45370. if (!this._isVisibilityBoxLocked) {
  45371. this.mesh.refreshBoundingInfo();
  45372. }
  45373. return this;
  45374. };
  45375. /**
  45376. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45377. * @param size the size (float) of the visibility box
  45378. * note : this doesn't lock the SPS mesh bounding box.
  45379. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45380. */
  45381. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45382. var vis = size / 2;
  45383. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45384. };
  45385. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45386. // getter and setter
  45387. get: function () {
  45388. return this._alwaysVisible;
  45389. },
  45390. /**
  45391. * Sets the SPS as always visible or not
  45392. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45393. */
  45394. set: function (val) {
  45395. this._alwaysVisible = val;
  45396. this.mesh.alwaysSelectAsActiveMesh = val;
  45397. },
  45398. enumerable: true,
  45399. configurable: true
  45400. });
  45401. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45402. get: function () {
  45403. return this._isVisibilityBoxLocked;
  45404. },
  45405. /**
  45406. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45407. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45408. */
  45409. set: function (val) {
  45410. this._isVisibilityBoxLocked = val;
  45411. var boundingInfo = this.mesh.getBoundingInfo();
  45412. if (boundingInfo) {
  45413. boundingInfo.isLocked = val;
  45414. }
  45415. },
  45416. enumerable: true,
  45417. configurable: true
  45418. });
  45419. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45420. // getters
  45421. get: function () {
  45422. return this._computeParticleRotation;
  45423. },
  45424. // Optimizer setters
  45425. /**
  45426. * Tells to `setParticles()` to compute the particle rotations or not.
  45427. * Default value : true. The SPS is faster when it's set to false.
  45428. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45429. */
  45430. set: function (val) {
  45431. this._computeParticleRotation = val;
  45432. },
  45433. enumerable: true,
  45434. configurable: true
  45435. });
  45436. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45437. get: function () {
  45438. return this._computeParticleColor;
  45439. },
  45440. /**
  45441. * Tells to `setParticles()` to compute the particle colors or not.
  45442. * Default value : true. The SPS is faster when it's set to false.
  45443. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45444. */
  45445. set: function (val) {
  45446. this._computeParticleColor = val;
  45447. },
  45448. enumerable: true,
  45449. configurable: true
  45450. });
  45451. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45452. get: function () {
  45453. return this._computeParticleTexture;
  45454. },
  45455. /**
  45456. * Tells to `setParticles()` to compute the particle textures or not.
  45457. * Default value : true. The SPS is faster when it's set to false.
  45458. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45459. */
  45460. set: function (val) {
  45461. this._computeParticleTexture = val;
  45462. },
  45463. enumerable: true,
  45464. configurable: true
  45465. });
  45466. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45467. get: function () {
  45468. return this._computeParticleVertex;
  45469. },
  45470. /**
  45471. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45472. * Default value : false. The SPS is faster when it's set to false.
  45473. * Note : the particle custom vertex positions aren't stored values.
  45474. */
  45475. set: function (val) {
  45476. this._computeParticleVertex = val;
  45477. },
  45478. enumerable: true,
  45479. configurable: true
  45480. });
  45481. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45482. get: function () {
  45483. return this._computeBoundingBox;
  45484. },
  45485. /**
  45486. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45487. */
  45488. set: function (val) {
  45489. this._computeBoundingBox = val;
  45490. },
  45491. enumerable: true,
  45492. configurable: true
  45493. });
  45494. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45495. get: function () {
  45496. return this._depthSortParticles;
  45497. },
  45498. /**
  45499. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45500. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45501. * Default : `true`
  45502. */
  45503. set: function (val) {
  45504. this._depthSortParticles = val;
  45505. },
  45506. enumerable: true,
  45507. configurable: true
  45508. });
  45509. // =======================================================================
  45510. // Particle behavior logic
  45511. // these following methods may be overwritten by the user to fit his needs
  45512. /**
  45513. * This function does nothing. It may be overwritten to set all the particle first values.
  45514. * The SPS doesn't call this function, you may have to call it by your own.
  45515. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45516. */
  45517. SolidParticleSystem.prototype.initParticles = function () {
  45518. };
  45519. /**
  45520. * This function does nothing. It may be overwritten to recycle a particle.
  45521. * The SPS doesn't call this function, you may have to call it by your own.
  45522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45523. */
  45524. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45525. return particle;
  45526. };
  45527. /**
  45528. * Updates a particle : this function should be overwritten by the user.
  45529. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45531. * ex : just set a particle position or velocity and recycle conditions
  45532. */
  45533. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45534. return particle;
  45535. };
  45536. /**
  45537. * Updates a vertex of a particle : it can be overwritten by the user.
  45538. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45539. * @param particle the current particle
  45540. * @param vertex the current index of the current particle
  45541. * @param pt the index of the current vertex in the particle shape
  45542. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45543. * ex : just set a vertex particle position
  45544. */
  45545. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45546. return vertex;
  45547. };
  45548. /**
  45549. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45550. * This does nothing and may be overwritten by the user.
  45551. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45552. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45553. * @param update the boolean update value actually passed to setParticles()
  45554. */
  45555. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45556. };
  45557. /**
  45558. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45559. * This will be passed three parameters.
  45560. * This does nothing and may be overwritten by the user.
  45561. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45562. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45563. * @param update the boolean update value actually passed to setParticles()
  45564. */
  45565. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45566. };
  45567. return SolidParticleSystem;
  45568. }());
  45569. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45570. })(BABYLON || (BABYLON = {}));
  45571. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45572. var BABYLON;
  45573. (function (BABYLON) {
  45574. var GroundMesh = /** @class */ (function (_super) {
  45575. __extends(GroundMesh, _super);
  45576. function GroundMesh(name, scene) {
  45577. var _this = _super.call(this, name, scene) || this;
  45578. _this.generateOctree = false;
  45579. return _this;
  45580. }
  45581. GroundMesh.prototype.getClassName = function () {
  45582. return "GroundMesh";
  45583. };
  45584. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45585. get: function () {
  45586. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45592. get: function () {
  45593. return this._subdivisionsX;
  45594. },
  45595. enumerable: true,
  45596. configurable: true
  45597. });
  45598. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45599. get: function () {
  45600. return this._subdivisionsY;
  45601. },
  45602. enumerable: true,
  45603. configurable: true
  45604. });
  45605. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45606. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45607. this._subdivisionsX = chunksCount;
  45608. this._subdivisionsY = chunksCount;
  45609. this.subdivide(chunksCount);
  45610. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45611. };
  45612. /**
  45613. * Returns a height (y) value in the Worl system :
  45614. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45615. * Returns the ground y position if (x, z) are outside the ground surface.
  45616. */
  45617. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45618. var world = this.getWorldMatrix();
  45619. var invMat = BABYLON.Tmp.Matrix[5];
  45620. world.invertToRef(invMat);
  45621. var tmpVect = BABYLON.Tmp.Vector3[8];
  45622. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45623. x = tmpVect.x;
  45624. z = tmpVect.z;
  45625. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45626. return this.position.y;
  45627. }
  45628. if (!this._heightQuads || this._heightQuads.length == 0) {
  45629. this._initHeightQuads();
  45630. this._computeHeightQuads();
  45631. }
  45632. var facet = this._getFacetAt(x, z);
  45633. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45634. // return y in the World system
  45635. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45636. return tmpVect.y;
  45637. };
  45638. /**
  45639. * Returns a normalized vector (Vector3) orthogonal to the ground
  45640. * at the ground coordinates (x, z) expressed in the World system.
  45641. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  45642. */
  45643. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  45644. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  45645. this.getNormalAtCoordinatesToRef(x, z, normal);
  45646. return normal;
  45647. };
  45648. /**
  45649. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  45650. * at the ground coordinates (x, z) expressed in the World system.
  45651. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  45652. * Returns the GroundMesh.
  45653. */
  45654. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  45655. var world = this.getWorldMatrix();
  45656. var tmpMat = BABYLON.Tmp.Matrix[5];
  45657. world.invertToRef(tmpMat);
  45658. var tmpVect = BABYLON.Tmp.Vector3[8];
  45659. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  45660. x = tmpVect.x;
  45661. z = tmpVect.z;
  45662. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45663. return this;
  45664. }
  45665. if (!this._heightQuads || this._heightQuads.length == 0) {
  45666. this._initHeightQuads();
  45667. this._computeHeightQuads();
  45668. }
  45669. var facet = this._getFacetAt(x, z);
  45670. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  45671. return this;
  45672. };
  45673. /**
  45674. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  45675. * if the ground has been updated.
  45676. * This can be used in the render loop.
  45677. * Returns the GroundMesh.
  45678. */
  45679. GroundMesh.prototype.updateCoordinateHeights = function () {
  45680. if (!this._heightQuads || this._heightQuads.length == 0) {
  45681. this._initHeightQuads();
  45682. }
  45683. this._computeHeightQuads();
  45684. return this;
  45685. };
  45686. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  45687. GroundMesh.prototype._getFacetAt = function (x, z) {
  45688. // retrieve col and row from x, z coordinates in the ground local system
  45689. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  45690. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  45691. var quad = this._heightQuads[row * this._subdivisionsX + col];
  45692. var facet;
  45693. if (z < quad.slope.x * x + quad.slope.y) {
  45694. facet = quad.facet1;
  45695. }
  45696. else {
  45697. facet = quad.facet2;
  45698. }
  45699. return facet;
  45700. };
  45701. // Creates and populates the heightMap array with "facet" elements :
  45702. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  45703. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45704. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45705. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45706. // Returns the GroundMesh.
  45707. GroundMesh.prototype._initHeightQuads = function () {
  45708. var subdivisionsX = this._subdivisionsX;
  45709. var subdivisionsY = this._subdivisionsY;
  45710. this._heightQuads = new Array();
  45711. for (var row = 0; row < subdivisionsY; row++) {
  45712. for (var col = 0; col < subdivisionsX; col++) {
  45713. 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) };
  45714. this._heightQuads[row * subdivisionsX + col] = quad;
  45715. }
  45716. }
  45717. return this;
  45718. };
  45719. // Compute each quad element values and update the the heightMap array :
  45720. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  45721. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  45722. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  45723. // Returns the GroundMesh.
  45724. GroundMesh.prototype._computeHeightQuads = function () {
  45725. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45726. if (!positions) {
  45727. return this;
  45728. }
  45729. var v1 = BABYLON.Tmp.Vector3[3];
  45730. var v2 = BABYLON.Tmp.Vector3[2];
  45731. var v3 = BABYLON.Tmp.Vector3[1];
  45732. var v4 = BABYLON.Tmp.Vector3[0];
  45733. var v1v2 = BABYLON.Tmp.Vector3[4];
  45734. var v1v3 = BABYLON.Tmp.Vector3[5];
  45735. var v1v4 = BABYLON.Tmp.Vector3[6];
  45736. var norm1 = BABYLON.Tmp.Vector3[7];
  45737. var norm2 = BABYLON.Tmp.Vector3[8];
  45738. var i = 0;
  45739. var j = 0;
  45740. var k = 0;
  45741. var cd = 0; // 2D slope coefficient : z = cd * x + h
  45742. var h = 0;
  45743. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  45744. var d2 = 0;
  45745. var subdivisionsX = this._subdivisionsX;
  45746. var subdivisionsY = this._subdivisionsY;
  45747. for (var row = 0; row < subdivisionsY; row++) {
  45748. for (var col = 0; col < subdivisionsX; col++) {
  45749. i = col * 3;
  45750. j = row * (subdivisionsX + 1) * 3;
  45751. k = (row + 1) * (subdivisionsX + 1) * 3;
  45752. v1.x = positions[j + i];
  45753. v1.y = positions[j + i + 1];
  45754. v1.z = positions[j + i + 2];
  45755. v2.x = positions[j + i + 3];
  45756. v2.y = positions[j + i + 4];
  45757. v2.z = positions[j + i + 5];
  45758. v3.x = positions[k + i];
  45759. v3.y = positions[k + i + 1];
  45760. v3.z = positions[k + i + 2];
  45761. v4.x = positions[k + i + 3];
  45762. v4.y = positions[k + i + 4];
  45763. v4.z = positions[k + i + 5];
  45764. // 2D slope V1V4
  45765. cd = (v4.z - v1.z) / (v4.x - v1.x);
  45766. h = v1.z - cd * v1.x; // v1 belongs to the slope
  45767. // facet equations :
  45768. // we compute each facet normal vector
  45769. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  45770. // we compute the value d by applying the equation to v1 which belongs to the plane
  45771. // then we store the facet equation in a Vector4
  45772. v2.subtractToRef(v1, v1v2);
  45773. v3.subtractToRef(v1, v1v3);
  45774. v4.subtractToRef(v1, v1v4);
  45775. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  45776. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  45777. norm1.normalize();
  45778. norm2.normalize();
  45779. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  45780. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  45781. var quad = this._heightQuads[row * subdivisionsX + col];
  45782. quad.slope.copyFromFloats(cd, h);
  45783. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  45784. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  45785. }
  45786. }
  45787. return this;
  45788. };
  45789. GroundMesh.prototype.serialize = function (serializationObject) {
  45790. _super.prototype.serialize.call(this, serializationObject);
  45791. serializationObject.subdivisionsX = this._subdivisionsX;
  45792. serializationObject.subdivisionsY = this._subdivisionsY;
  45793. serializationObject.minX = this._minX;
  45794. serializationObject.maxX = this._maxX;
  45795. serializationObject.minZ = this._minZ;
  45796. serializationObject.maxZ = this._maxZ;
  45797. serializationObject.width = this._width;
  45798. serializationObject.height = this._height;
  45799. };
  45800. GroundMesh.Parse = function (parsedMesh, scene) {
  45801. var result = new GroundMesh(parsedMesh.name, scene);
  45802. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  45803. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  45804. result._minX = parsedMesh.minX;
  45805. result._maxX = parsedMesh.maxX;
  45806. result._minZ = parsedMesh.minZ;
  45807. result._maxZ = parsedMesh.maxZ;
  45808. result._width = parsedMesh.width;
  45809. result._height = parsedMesh.height;
  45810. return result;
  45811. };
  45812. return GroundMesh;
  45813. }(BABYLON.Mesh));
  45814. BABYLON.GroundMesh = GroundMesh;
  45815. })(BABYLON || (BABYLON = {}));
  45816. //# sourceMappingURL=babylon.groundMesh.js.map
  45817. var BABYLON;
  45818. (function (BABYLON) {
  45819. /**
  45820. * Creates an instance based on a source mesh.
  45821. */
  45822. var InstancedMesh = /** @class */ (function (_super) {
  45823. __extends(InstancedMesh, _super);
  45824. function InstancedMesh(name, source) {
  45825. var _this = _super.call(this, name, source.getScene()) || this;
  45826. source.instances.push(_this);
  45827. _this._sourceMesh = source;
  45828. _this.position.copyFrom(source.position);
  45829. _this.rotation.copyFrom(source.rotation);
  45830. _this.scaling.copyFrom(source.scaling);
  45831. if (source.rotationQuaternion) {
  45832. _this.rotationQuaternion = source.rotationQuaternion.clone();
  45833. }
  45834. _this.infiniteDistance = source.infiniteDistance;
  45835. _this.setPivotMatrix(source.getPivotMatrix());
  45836. _this.refreshBoundingInfo();
  45837. _this._syncSubMeshes();
  45838. return _this;
  45839. }
  45840. /**
  45841. * Returns the string "InstancedMesh".
  45842. */
  45843. InstancedMesh.prototype.getClassName = function () {
  45844. return "InstancedMesh";
  45845. };
  45846. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  45847. // Methods
  45848. get: function () {
  45849. return this._sourceMesh.receiveShadows;
  45850. },
  45851. enumerable: true,
  45852. configurable: true
  45853. });
  45854. Object.defineProperty(InstancedMesh.prototype, "material", {
  45855. get: function () {
  45856. return this._sourceMesh.material;
  45857. },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  45862. get: function () {
  45863. return this._sourceMesh.visibility;
  45864. },
  45865. enumerable: true,
  45866. configurable: true
  45867. });
  45868. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  45869. get: function () {
  45870. return this._sourceMesh.skeleton;
  45871. },
  45872. enumerable: true,
  45873. configurable: true
  45874. });
  45875. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  45876. get: function () {
  45877. return this._sourceMesh.renderingGroupId;
  45878. },
  45879. enumerable: true,
  45880. configurable: true
  45881. });
  45882. /**
  45883. * Returns the total number of vertices (integer).
  45884. */
  45885. InstancedMesh.prototype.getTotalVertices = function () {
  45886. return this._sourceMesh.getTotalVertices();
  45887. };
  45888. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  45889. get: function () {
  45890. return this._sourceMesh;
  45891. },
  45892. enumerable: true,
  45893. configurable: true
  45894. });
  45895. /**
  45896. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  45897. */
  45898. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  45899. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  45900. };
  45901. /**
  45902. * Sets the vertex data of the mesh geometry for the requested `kind`.
  45903. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  45904. * The `data` are either a numeric array either a Float32Array.
  45905. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  45906. * 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).
  45907. * Note that a new underlying VertexBuffer object is created each call.
  45908. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  45909. *
  45910. * Possible `kind` values :
  45911. * - BABYLON.VertexBuffer.PositionKind
  45912. * - BABYLON.VertexBuffer.UVKind
  45913. * - BABYLON.VertexBuffer.UV2Kind
  45914. * - BABYLON.VertexBuffer.UV3Kind
  45915. * - BABYLON.VertexBuffer.UV4Kind
  45916. * - BABYLON.VertexBuffer.UV5Kind
  45917. * - BABYLON.VertexBuffer.UV6Kind
  45918. * - BABYLON.VertexBuffer.ColorKind
  45919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45923. *
  45924. * Returns the Mesh.
  45925. */
  45926. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  45927. if (this.sourceMesh) {
  45928. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  45929. }
  45930. return this.sourceMesh;
  45931. };
  45932. /**
  45933. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  45934. * If the mesh has no geometry, it is simply returned as it is.
  45935. * The `data` are either a numeric array either a Float32Array.
  45936. * No new underlying VertexBuffer object is created.
  45937. * 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.
  45938. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  45939. *
  45940. * Possible `kind` values :
  45941. * - BABYLON.VertexBuffer.PositionKind
  45942. * - BABYLON.VertexBuffer.UVKind
  45943. * - BABYLON.VertexBuffer.UV2Kind
  45944. * - BABYLON.VertexBuffer.UV3Kind
  45945. * - BABYLON.VertexBuffer.UV4Kind
  45946. * - BABYLON.VertexBuffer.UV5Kind
  45947. * - BABYLON.VertexBuffer.UV6Kind
  45948. * - BABYLON.VertexBuffer.ColorKind
  45949. * - BABYLON.VertexBuffer.MatricesIndicesKind
  45950. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  45951. * - BABYLON.VertexBuffer.MatricesWeightsKind
  45952. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  45953. *
  45954. * Returns the Mesh.
  45955. */
  45956. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  45957. if (this.sourceMesh) {
  45958. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  45959. }
  45960. return this.sourceMesh;
  45961. };
  45962. /**
  45963. * Sets the mesh indices.
  45964. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  45965. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  45966. * This method creates a new index buffer each call.
  45967. * Returns the Mesh.
  45968. */
  45969. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  45970. if (totalVertices === void 0) { totalVertices = null; }
  45971. if (this.sourceMesh) {
  45972. this.sourceMesh.setIndices(indices, totalVertices);
  45973. }
  45974. return this.sourceMesh;
  45975. };
  45976. /**
  45977. * Boolean : True if the mesh owns the requested kind of data.
  45978. */
  45979. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  45980. return this._sourceMesh.isVerticesDataPresent(kind);
  45981. };
  45982. /**
  45983. * Returns an array of indices (IndicesArray).
  45984. */
  45985. InstancedMesh.prototype.getIndices = function () {
  45986. return this._sourceMesh.getIndices();
  45987. };
  45988. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  45989. get: function () {
  45990. return this._sourceMesh._positions;
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. /**
  45996. * Sets a new updated BoundingInfo to the mesh.
  45997. * Returns the mesh.
  45998. */
  45999. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46000. var meshBB = this._sourceMesh.getBoundingInfo();
  46001. if (meshBB) {
  46002. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46003. }
  46004. this._updateBoundingInfo();
  46005. return this;
  46006. };
  46007. InstancedMesh.prototype._preActivate = function () {
  46008. if (this._currentLOD) {
  46009. this._currentLOD._preActivate();
  46010. }
  46011. return this;
  46012. };
  46013. InstancedMesh.prototype._activate = function (renderId) {
  46014. if (this._currentLOD) {
  46015. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46016. }
  46017. return this;
  46018. };
  46019. /**
  46020. * Returns the current associated LOD AbstractMesh.
  46021. */
  46022. InstancedMesh.prototype.getLOD = function (camera) {
  46023. if (!camera) {
  46024. return this;
  46025. }
  46026. var boundingInfo = this.getBoundingInfo();
  46027. if (!boundingInfo) {
  46028. return this;
  46029. }
  46030. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46031. if (this._currentLOD === this.sourceMesh) {
  46032. return this;
  46033. }
  46034. return this._currentLOD;
  46035. };
  46036. InstancedMesh.prototype._syncSubMeshes = function () {
  46037. this.releaseSubMeshes();
  46038. if (this._sourceMesh.subMeshes) {
  46039. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46040. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46041. }
  46042. }
  46043. return this;
  46044. };
  46045. InstancedMesh.prototype._generatePointsArray = function () {
  46046. return this._sourceMesh._generatePointsArray();
  46047. };
  46048. /**
  46049. * Creates a new InstancedMesh from the current mesh.
  46050. * - name (string) : the cloned mesh name
  46051. * - newParent (optional Node) : the optional Node to parent the clone to.
  46052. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46053. *
  46054. * Returns the clone.
  46055. */
  46056. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46057. var result = this._sourceMesh.createInstance(name);
  46058. // Deep copy
  46059. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46060. // Bounding info
  46061. this.refreshBoundingInfo();
  46062. // Parent
  46063. if (newParent) {
  46064. result.parent = newParent;
  46065. }
  46066. if (!doNotCloneChildren) {
  46067. // Children
  46068. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46069. var mesh = this.getScene().meshes[index];
  46070. if (mesh.parent === this) {
  46071. mesh.clone(mesh.name, result);
  46072. }
  46073. }
  46074. }
  46075. result.computeWorldMatrix(true);
  46076. return result;
  46077. };
  46078. /**
  46079. * Disposes the InstancedMesh.
  46080. * Returns nothing.
  46081. */
  46082. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46083. // Remove from mesh
  46084. var index = this._sourceMesh.instances.indexOf(this);
  46085. this._sourceMesh.instances.splice(index, 1);
  46086. _super.prototype.dispose.call(this, doNotRecurse);
  46087. };
  46088. return InstancedMesh;
  46089. }(BABYLON.AbstractMesh));
  46090. BABYLON.InstancedMesh = InstancedMesh;
  46091. })(BABYLON || (BABYLON = {}));
  46092. //# sourceMappingURL=babylon.instancedMesh.js.map
  46093. var BABYLON;
  46094. (function (BABYLON) {
  46095. var LinesMesh = /** @class */ (function (_super) {
  46096. __extends(LinesMesh, _super);
  46097. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46098. if (scene === void 0) { scene = null; }
  46099. if (parent === void 0) { parent = null; }
  46100. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46101. _this.useVertexColor = useVertexColor;
  46102. _this.color = new BABYLON.Color3(1, 1, 1);
  46103. _this.alpha = 1;
  46104. if (source) {
  46105. _this.color = source.color.clone();
  46106. _this.alpha = source.alpha;
  46107. _this.useVertexColor = source.useVertexColor;
  46108. }
  46109. _this._intersectionThreshold = 0.1;
  46110. var options = {
  46111. attributes: [BABYLON.VertexBuffer.PositionKind],
  46112. uniforms: ["world", "viewProjection"],
  46113. needAlphaBlending: false,
  46114. };
  46115. if (!useVertexColor) {
  46116. options.uniforms.push("color");
  46117. options.needAlphaBlending = true;
  46118. }
  46119. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46120. return _this;
  46121. }
  46122. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46123. /**
  46124. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46125. * This margin is expressed in world space coordinates, so its value may vary.
  46126. * Default value is 0.1
  46127. * @returns the intersection Threshold value.
  46128. */
  46129. get: function () {
  46130. return this._intersectionThreshold;
  46131. },
  46132. /**
  46133. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46134. * This margin is expressed in world space coordinates, so its value may vary.
  46135. * @param value the new threshold to apply
  46136. */
  46137. set: function (value) {
  46138. if (this._intersectionThreshold === value) {
  46139. return;
  46140. }
  46141. this._intersectionThreshold = value;
  46142. if (this.geometry) {
  46143. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46144. }
  46145. },
  46146. enumerable: true,
  46147. configurable: true
  46148. });
  46149. /**
  46150. * Returns the string "LineMesh"
  46151. */
  46152. LinesMesh.prototype.getClassName = function () {
  46153. return "LinesMesh";
  46154. };
  46155. Object.defineProperty(LinesMesh.prototype, "material", {
  46156. get: function () {
  46157. return this._colorShader;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46163. get: function () {
  46164. return false;
  46165. },
  46166. enumerable: true,
  46167. configurable: true
  46168. });
  46169. LinesMesh.prototype.createInstance = function (name) {
  46170. throw new Error("LinesMeshes do not support createInstance.");
  46171. };
  46172. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46173. if (!this._geometry) {
  46174. return this;
  46175. }
  46176. // VBOs
  46177. this._geometry._bind(this._colorShader.getEffect());
  46178. // Color
  46179. if (!this.useVertexColor) {
  46180. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46181. }
  46182. return this;
  46183. };
  46184. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46185. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46186. return this;
  46187. }
  46188. var engine = this.getScene().getEngine();
  46189. // Draw order
  46190. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46191. return this;
  46192. };
  46193. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46194. this._colorShader.dispose();
  46195. _super.prototype.dispose.call(this, doNotRecurse);
  46196. };
  46197. /**
  46198. * Returns a new LineMesh object cloned from the current one.
  46199. */
  46200. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46201. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46202. };
  46203. return LinesMesh;
  46204. }(BABYLON.Mesh));
  46205. BABYLON.LinesMesh = LinesMesh;
  46206. })(BABYLON || (BABYLON = {}));
  46207. //# sourceMappingURL=babylon.linesMesh.js.map
  46208. var BABYLON;
  46209. (function (BABYLON) {
  46210. var ShaderMaterial = /** @class */ (function (_super) {
  46211. __extends(ShaderMaterial, _super);
  46212. function ShaderMaterial(name, scene, shaderPath, options) {
  46213. var _this = _super.call(this, name, scene) || this;
  46214. _this._textures = {};
  46215. _this._textureArrays = {};
  46216. _this._floats = {};
  46217. _this._floatsArrays = {};
  46218. _this._colors3 = {};
  46219. _this._colors3Arrays = {};
  46220. _this._colors4 = {};
  46221. _this._vectors2 = {};
  46222. _this._vectors3 = {};
  46223. _this._vectors4 = {};
  46224. _this._matrices = {};
  46225. _this._matrices3x3 = {};
  46226. _this._matrices2x2 = {};
  46227. _this._vectors3Arrays = {};
  46228. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46229. _this._shaderPath = shaderPath;
  46230. options.needAlphaBlending = options.needAlphaBlending || false;
  46231. options.needAlphaTesting = options.needAlphaTesting || false;
  46232. options.attributes = options.attributes || ["position", "normal", "uv"];
  46233. options.uniforms = options.uniforms || ["worldViewProjection"];
  46234. options.uniformBuffers = options.uniformBuffers || [];
  46235. options.samplers = options.samplers || [];
  46236. options.defines = options.defines || [];
  46237. _this._options = options;
  46238. return _this;
  46239. }
  46240. ShaderMaterial.prototype.getClassName = function () {
  46241. return "ShaderMaterial";
  46242. };
  46243. ShaderMaterial.prototype.needAlphaBlending = function () {
  46244. return this._options.needAlphaBlending;
  46245. };
  46246. ShaderMaterial.prototype.needAlphaTesting = function () {
  46247. return this._options.needAlphaTesting;
  46248. };
  46249. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46250. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46251. this._options.uniforms.push(uniformName);
  46252. }
  46253. };
  46254. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46255. if (this._options.samplers.indexOf(name) === -1) {
  46256. this._options.samplers.push(name);
  46257. }
  46258. this._textures[name] = texture;
  46259. return this;
  46260. };
  46261. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46262. if (this._options.samplers.indexOf(name) === -1) {
  46263. this._options.samplers.push(name);
  46264. }
  46265. this._checkUniform(name);
  46266. this._textureArrays[name] = textures;
  46267. return this;
  46268. };
  46269. ShaderMaterial.prototype.setFloat = function (name, value) {
  46270. this._checkUniform(name);
  46271. this._floats[name] = value;
  46272. return this;
  46273. };
  46274. ShaderMaterial.prototype.setFloats = function (name, value) {
  46275. this._checkUniform(name);
  46276. this._floatsArrays[name] = value;
  46277. return this;
  46278. };
  46279. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46280. this._checkUniform(name);
  46281. this._colors3[name] = value;
  46282. return this;
  46283. };
  46284. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46285. this._checkUniform(name);
  46286. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46287. color.toArray(arr, arr.length);
  46288. return arr;
  46289. }, []);
  46290. return this;
  46291. };
  46292. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46293. this._checkUniform(name);
  46294. this._colors4[name] = value;
  46295. return this;
  46296. };
  46297. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46298. this._checkUniform(name);
  46299. this._vectors2[name] = value;
  46300. return this;
  46301. };
  46302. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46303. this._checkUniform(name);
  46304. this._vectors3[name] = value;
  46305. return this;
  46306. };
  46307. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46308. this._checkUniform(name);
  46309. this._vectors4[name] = value;
  46310. return this;
  46311. };
  46312. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46313. this._checkUniform(name);
  46314. this._matrices[name] = value;
  46315. return this;
  46316. };
  46317. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46318. this._checkUniform(name);
  46319. this._matrices3x3[name] = value;
  46320. return this;
  46321. };
  46322. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46323. this._checkUniform(name);
  46324. this._matrices2x2[name] = value;
  46325. return this;
  46326. };
  46327. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46328. this._checkUniform(name);
  46329. this._vectors3Arrays[name] = value;
  46330. return this;
  46331. };
  46332. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46333. if (!mesh) {
  46334. return true;
  46335. }
  46336. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46337. return false;
  46338. }
  46339. return false;
  46340. };
  46341. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46342. var scene = this.getScene();
  46343. var engine = scene.getEngine();
  46344. if (!this.checkReadyOnEveryCall) {
  46345. if (this._renderId === scene.getRenderId()) {
  46346. if (this._checkCache(scene, mesh, useInstances)) {
  46347. return true;
  46348. }
  46349. }
  46350. }
  46351. // Instances
  46352. var defines = [];
  46353. var attribs = [];
  46354. var fallbacks = new BABYLON.EffectFallbacks();
  46355. if (useInstances) {
  46356. defines.push("#define INSTANCES");
  46357. }
  46358. for (var index = 0; index < this._options.defines.length; index++) {
  46359. defines.push(this._options.defines[index]);
  46360. }
  46361. for (var index = 0; index < this._options.attributes.length; index++) {
  46362. attribs.push(this._options.attributes[index]);
  46363. }
  46364. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46365. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46366. defines.push("#define VERTEXCOLOR");
  46367. }
  46368. // Bones
  46369. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46370. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46371. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46372. if (mesh.numBoneInfluencers > 4) {
  46373. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46374. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46375. }
  46376. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46377. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46378. fallbacks.addCPUSkinningFallback(0, mesh);
  46379. if (this._options.uniforms.indexOf("mBones") === -1) {
  46380. this._options.uniforms.push("mBones");
  46381. }
  46382. }
  46383. else {
  46384. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46385. }
  46386. // Textures
  46387. for (var name in this._textures) {
  46388. if (!this._textures[name].isReady()) {
  46389. return false;
  46390. }
  46391. }
  46392. // Alpha test
  46393. if (engine.getAlphaTesting()) {
  46394. defines.push("#define ALPHATEST");
  46395. }
  46396. var previousEffect = this._effect;
  46397. var join = defines.join("\n");
  46398. this._effect = engine.createEffect(this._shaderPath, {
  46399. attributes: attribs,
  46400. uniformsNames: this._options.uniforms,
  46401. uniformBuffersNames: this._options.uniformBuffers,
  46402. samplers: this._options.samplers,
  46403. defines: join,
  46404. fallbacks: fallbacks,
  46405. onCompiled: this.onCompiled,
  46406. onError: this.onError
  46407. }, engine);
  46408. if (!this._effect.isReady()) {
  46409. return false;
  46410. }
  46411. if (previousEffect !== this._effect) {
  46412. scene.resetCachedMaterial();
  46413. }
  46414. this._renderId = scene.getRenderId();
  46415. return true;
  46416. };
  46417. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46418. var scene = this.getScene();
  46419. if (!this._effect) {
  46420. return;
  46421. }
  46422. if (this._options.uniforms.indexOf("world") !== -1) {
  46423. this._effect.setMatrix("world", world);
  46424. }
  46425. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46426. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46427. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46428. }
  46429. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46430. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46431. }
  46432. };
  46433. ShaderMaterial.prototype.bind = function (world, mesh) {
  46434. // Std values
  46435. this.bindOnlyWorldMatrix(world);
  46436. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46437. if (this._options.uniforms.indexOf("view") !== -1) {
  46438. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46439. }
  46440. if (this._options.uniforms.indexOf("projection") !== -1) {
  46441. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46442. }
  46443. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46444. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46445. }
  46446. // Bones
  46447. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46448. var name;
  46449. // Texture
  46450. for (name in this._textures) {
  46451. this._effect.setTexture(name, this._textures[name]);
  46452. }
  46453. // Texture arrays
  46454. for (name in this._textureArrays) {
  46455. this._effect.setTextureArray(name, this._textureArrays[name]);
  46456. }
  46457. // Float
  46458. for (name in this._floats) {
  46459. this._effect.setFloat(name, this._floats[name]);
  46460. }
  46461. // Float s
  46462. for (name in this._floatsArrays) {
  46463. this._effect.setArray(name, this._floatsArrays[name]);
  46464. }
  46465. // Color3
  46466. for (name in this._colors3) {
  46467. this._effect.setColor3(name, this._colors3[name]);
  46468. }
  46469. for (name in this._colors3Arrays) {
  46470. this._effect.setArray3(name, this._colors3Arrays[name]);
  46471. }
  46472. // Color4
  46473. for (name in this._colors4) {
  46474. var color = this._colors4[name];
  46475. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46476. }
  46477. // Vector2
  46478. for (name in this._vectors2) {
  46479. this._effect.setVector2(name, this._vectors2[name]);
  46480. }
  46481. // Vector3
  46482. for (name in this._vectors3) {
  46483. this._effect.setVector3(name, this._vectors3[name]);
  46484. }
  46485. // Vector4
  46486. for (name in this._vectors4) {
  46487. this._effect.setVector4(name, this._vectors4[name]);
  46488. }
  46489. // Matrix
  46490. for (name in this._matrices) {
  46491. this._effect.setMatrix(name, this._matrices[name]);
  46492. }
  46493. // Matrix 3x3
  46494. for (name in this._matrices3x3) {
  46495. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46496. }
  46497. // Matrix 2x2
  46498. for (name in this._matrices2x2) {
  46499. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46500. }
  46501. // Vector3Array
  46502. for (name in this._vectors3Arrays) {
  46503. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46504. }
  46505. }
  46506. this._afterBind(mesh);
  46507. };
  46508. ShaderMaterial.prototype.getActiveTextures = function () {
  46509. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46510. for (var name in this._textures) {
  46511. activeTextures.push(this._textures[name]);
  46512. }
  46513. for (var name in this._textureArrays) {
  46514. var array = this._textureArrays[name];
  46515. for (var index = 0; index < array.length; index++) {
  46516. activeTextures.push(array[index]);
  46517. }
  46518. }
  46519. return activeTextures;
  46520. };
  46521. ShaderMaterial.prototype.hasTexture = function (texture) {
  46522. if (_super.prototype.hasTexture.call(this, texture)) {
  46523. return true;
  46524. }
  46525. for (var name in this._textures) {
  46526. if (this._textures[name] === texture) {
  46527. return true;
  46528. }
  46529. }
  46530. for (var name in this._textureArrays) {
  46531. var array = this._textureArrays[name];
  46532. for (var index = 0; index < array.length; index++) {
  46533. if (array[index] === texture) {
  46534. return true;
  46535. }
  46536. }
  46537. }
  46538. return false;
  46539. };
  46540. ShaderMaterial.prototype.clone = function (name) {
  46541. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46542. return newShaderMaterial;
  46543. };
  46544. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46545. if (forceDisposeTextures) {
  46546. var name;
  46547. for (name in this._textures) {
  46548. this._textures[name].dispose();
  46549. }
  46550. for (name in this._textureArrays) {
  46551. var array = this._textureArrays[name];
  46552. for (var index = 0; index < array.length; index++) {
  46553. array[index].dispose();
  46554. }
  46555. }
  46556. }
  46557. this._textures = {};
  46558. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46559. };
  46560. ShaderMaterial.prototype.serialize = function () {
  46561. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46562. serializationObject.customType = "BABYLON.ShaderMaterial";
  46563. serializationObject.options = this._options;
  46564. serializationObject.shaderPath = this._shaderPath;
  46565. var name;
  46566. // Texture
  46567. serializationObject.textures = {};
  46568. for (name in this._textures) {
  46569. serializationObject.textures[name] = this._textures[name].serialize();
  46570. }
  46571. // Texture arrays
  46572. serializationObject.textureArrays = {};
  46573. for (name in this._textureArrays) {
  46574. serializationObject.textureArrays[name] = [];
  46575. var array = this._textureArrays[name];
  46576. for (var index = 0; index < array.length; index++) {
  46577. serializationObject.textureArrays[name].push(array[index].serialize());
  46578. }
  46579. }
  46580. // Float
  46581. serializationObject.floats = {};
  46582. for (name in this._floats) {
  46583. serializationObject.floats[name] = this._floats[name];
  46584. }
  46585. // Float s
  46586. serializationObject.FloatArrays = {};
  46587. for (name in this._floatsArrays) {
  46588. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46589. }
  46590. // Color3
  46591. serializationObject.colors3 = {};
  46592. for (name in this._colors3) {
  46593. serializationObject.colors3[name] = this._colors3[name].asArray();
  46594. }
  46595. // Color3 array
  46596. serializationObject.colors3Arrays = {};
  46597. for (name in this._colors3Arrays) {
  46598. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46599. }
  46600. // Color4
  46601. serializationObject.colors4 = {};
  46602. for (name in this._colors4) {
  46603. serializationObject.colors4[name] = this._colors4[name].asArray();
  46604. }
  46605. // Vector2
  46606. serializationObject.vectors2 = {};
  46607. for (name in this._vectors2) {
  46608. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46609. }
  46610. // Vector3
  46611. serializationObject.vectors3 = {};
  46612. for (name in this._vectors3) {
  46613. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46614. }
  46615. // Vector4
  46616. serializationObject.vectors4 = {};
  46617. for (name in this._vectors4) {
  46618. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46619. }
  46620. // Matrix
  46621. serializationObject.matrices = {};
  46622. for (name in this._matrices) {
  46623. serializationObject.matrices[name] = this._matrices[name].asArray();
  46624. }
  46625. // Matrix 3x3
  46626. serializationObject.matrices3x3 = {};
  46627. for (name in this._matrices3x3) {
  46628. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46629. }
  46630. // Matrix 2x2
  46631. serializationObject.matrices2x2 = {};
  46632. for (name in this._matrices2x2) {
  46633. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46634. }
  46635. // Vector3Array
  46636. serializationObject.vectors3Arrays = {};
  46637. for (name in this._vectors3Arrays) {
  46638. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  46639. }
  46640. return serializationObject;
  46641. };
  46642. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  46643. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  46644. var name;
  46645. // Texture
  46646. for (name in source.textures) {
  46647. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  46648. }
  46649. // Texture arrays
  46650. for (name in source.textureArrays) {
  46651. var array = source.textureArrays[name];
  46652. var textureArray = new Array();
  46653. for (var index = 0; index < array.length; index++) {
  46654. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  46655. }
  46656. material.setTextureArray(name, textureArray);
  46657. }
  46658. // Float
  46659. for (name in source.floats) {
  46660. material.setFloat(name, source.floats[name]);
  46661. }
  46662. // Float s
  46663. for (name in source.floatsArrays) {
  46664. material.setFloats(name, source.floatsArrays[name]);
  46665. }
  46666. // Color3
  46667. for (name in source.colors3) {
  46668. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  46669. }
  46670. // Color3 arrays
  46671. for (name in source.colors3Arrays) {
  46672. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  46673. if (i % 3 === 0) {
  46674. arr.push([num]);
  46675. }
  46676. else {
  46677. arr[arr.length - 1].push(num);
  46678. }
  46679. return arr;
  46680. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  46681. material.setColor3Array(name, colors);
  46682. }
  46683. // Color4
  46684. for (name in source.colors4) {
  46685. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  46686. }
  46687. // Vector2
  46688. for (name in source.vectors2) {
  46689. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  46690. }
  46691. // Vector3
  46692. for (name in source.vectors3) {
  46693. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  46694. }
  46695. // Vector4
  46696. for (name in source.vectors4) {
  46697. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  46698. }
  46699. // Matrix
  46700. for (name in source.matrices) {
  46701. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  46702. }
  46703. // Matrix 3x3
  46704. for (name in source.matrices3x3) {
  46705. material.setMatrix3x3(name, source.matrices3x3[name]);
  46706. }
  46707. // Matrix 2x2
  46708. for (name in source.matrices2x2) {
  46709. material.setMatrix2x2(name, source.matrices2x2[name]);
  46710. }
  46711. // Vector3Array
  46712. for (name in source.vectors3Arrays) {
  46713. material.setArray3(name, source.vectors3Arrays[name]);
  46714. }
  46715. return material;
  46716. };
  46717. return ShaderMaterial;
  46718. }(BABYLON.Material));
  46719. BABYLON.ShaderMaterial = ShaderMaterial;
  46720. })(BABYLON || (BABYLON = {}));
  46721. //# sourceMappingURL=babylon.shaderMaterial.js.map
  46722. var BABYLON;
  46723. (function (BABYLON) {
  46724. var MeshBuilder = /** @class */ (function () {
  46725. function MeshBuilder() {
  46726. }
  46727. MeshBuilder.updateSideOrientation = function (orientation) {
  46728. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  46729. return BABYLON.Mesh.DOUBLESIDE;
  46730. }
  46731. if (orientation === undefined || orientation === null) {
  46732. return BABYLON.Mesh.FRONTSIDE;
  46733. }
  46734. return orientation;
  46735. };
  46736. /**
  46737. * Creates a box mesh.
  46738. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  46739. * The parameter `size` sets the size (float) of each box side (default 1).
  46740. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  46741. * 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).
  46742. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46744. * 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).
  46745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46747. */
  46748. MeshBuilder.CreateBox = function (name, options, scene) {
  46749. if (scene === void 0) { scene = null; }
  46750. var box = new BABYLON.Mesh(name, scene);
  46751. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46752. box._originalBuilderSideOrientation = options.sideOrientation;
  46753. var vertexData = BABYLON.VertexData.CreateBox(options);
  46754. vertexData.applyToMesh(box, options.updatable);
  46755. return box;
  46756. };
  46757. /**
  46758. * Creates a sphere mesh.
  46759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  46760. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  46761. * 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`).
  46762. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  46763. * 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
  46764. * 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).
  46765. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46766. * 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).
  46767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46769. */
  46770. MeshBuilder.CreateSphere = function (name, options, scene) {
  46771. var sphere = new BABYLON.Mesh(name, scene);
  46772. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46773. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46774. var vertexData = BABYLON.VertexData.CreateSphere(options);
  46775. vertexData.applyToMesh(sphere, options.updatable);
  46776. return sphere;
  46777. };
  46778. /**
  46779. * Creates a plane polygonal mesh. By default, this is a disc.
  46780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  46781. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  46782. * 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.
  46783. * 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
  46784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46785. * 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).
  46786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46788. */
  46789. MeshBuilder.CreateDisc = function (name, options, scene) {
  46790. if (scene === void 0) { scene = null; }
  46791. var disc = new BABYLON.Mesh(name, scene);
  46792. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46793. disc._originalBuilderSideOrientation = options.sideOrientation;
  46794. var vertexData = BABYLON.VertexData.CreateDisc(options);
  46795. vertexData.applyToMesh(disc, options.updatable);
  46796. return disc;
  46797. };
  46798. /**
  46799. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  46800. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  46801. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  46802. * 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`).
  46803. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  46804. * 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.
  46805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46806. * 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).
  46807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46809. */
  46810. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  46811. var sphere = new BABYLON.Mesh(name, scene);
  46812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46813. sphere._originalBuilderSideOrientation = options.sideOrientation;
  46814. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  46815. vertexData.applyToMesh(sphere, options.updatable);
  46816. return sphere;
  46817. };
  46818. ;
  46819. /**
  46820. * Creates a ribbon mesh.
  46821. * 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.
  46822. *
  46823. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  46824. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  46825. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  46826. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  46827. * 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.
  46828. * 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.
  46829. * 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
  46830. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46831. * 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).
  46832. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46833. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46834. * 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.
  46835. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  46836. * 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
  46837. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  46838. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  46839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46840. */
  46841. MeshBuilder.CreateRibbon = function (name, options, scene) {
  46842. if (scene === void 0) { scene = null; }
  46843. var pathArray = options.pathArray;
  46844. var closeArray = options.closeArray;
  46845. var closePath = options.closePath;
  46846. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46847. var instance = options.instance;
  46848. var updatable = options.updatable;
  46849. if (instance) {
  46850. // positionFunction : ribbon case
  46851. // only pathArray and sideOrientation parameters are taken into account for positions update
  46852. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  46853. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  46854. var positionFunction = function (positions) {
  46855. var minlg = pathArray[0].length;
  46856. var i = 0;
  46857. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  46858. for (var si = 1; si <= ns; si++) {
  46859. for (var p = 0; p < pathArray.length; p++) {
  46860. var path = pathArray[p];
  46861. var l = path.length;
  46862. minlg = (minlg < l) ? minlg : l;
  46863. var j = 0;
  46864. while (j < minlg) {
  46865. positions[i] = path[j].x;
  46866. positions[i + 1] = path[j].y;
  46867. positions[i + 2] = path[j].z;
  46868. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  46869. BABYLON.Tmp.Vector3[0].x = path[j].x;
  46870. }
  46871. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  46872. BABYLON.Tmp.Vector3[1].x = path[j].x;
  46873. }
  46874. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  46875. BABYLON.Tmp.Vector3[0].y = path[j].y;
  46876. }
  46877. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  46878. BABYLON.Tmp.Vector3[1].y = path[j].y;
  46879. }
  46880. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  46881. BABYLON.Tmp.Vector3[0].z = path[j].z;
  46882. }
  46883. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  46884. BABYLON.Tmp.Vector3[1].z = path[j].z;
  46885. }
  46886. j++;
  46887. i += 3;
  46888. }
  46889. if (instance._closePath) {
  46890. positions[i] = path[0].x;
  46891. positions[i + 1] = path[0].y;
  46892. positions[i + 2] = path[0].z;
  46893. i += 3;
  46894. }
  46895. }
  46896. }
  46897. };
  46898. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46899. positionFunction(positions);
  46900. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  46901. instance._boundingInfo.update(instance._worldMatrix);
  46902. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  46903. if (options.colors) {
  46904. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46905. for (var c = 0; c < options.colors.length; c++) {
  46906. colors[c * 4] = options.colors[c].r;
  46907. colors[c * 4 + 1] = options.colors[c].g;
  46908. colors[c * 4 + 2] = options.colors[c].b;
  46909. colors[c * 4 + 3] = options.colors[c].a;
  46910. }
  46911. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  46912. }
  46913. if (options.uvs) {
  46914. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46915. for (var i = 0; i < options.uvs.length; i++) {
  46916. uvs[i * 2] = options.uvs[i].x;
  46917. uvs[i * 2 + 1] = options.uvs[i].y;
  46918. }
  46919. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  46920. }
  46921. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  46922. var indices = instance.getIndices();
  46923. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46924. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  46925. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  46926. if (instance._closePath) {
  46927. var indexFirst = 0;
  46928. var indexLast = 0;
  46929. for (var p = 0; p < pathArray.length; p++) {
  46930. indexFirst = instance._idx[p] * 3;
  46931. if (p + 1 < pathArray.length) {
  46932. indexLast = (instance._idx[p + 1] - 1) * 3;
  46933. }
  46934. else {
  46935. indexLast = normals.length - 3;
  46936. }
  46937. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  46938. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  46939. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  46940. normals[indexLast] = normals[indexFirst];
  46941. normals[indexLast + 1] = normals[indexFirst + 1];
  46942. normals[indexLast + 2] = normals[indexFirst + 2];
  46943. }
  46944. }
  46945. if (!(instance.areNormalsFrozen)) {
  46946. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  46947. }
  46948. }
  46949. return instance;
  46950. }
  46951. else {
  46952. var ribbon = new BABYLON.Mesh(name, scene);
  46953. ribbon._originalBuilderSideOrientation = sideOrientation;
  46954. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  46955. if (closePath) {
  46956. ribbon._idx = vertexData._idx;
  46957. }
  46958. ribbon._closePath = closePath;
  46959. ribbon._closeArray = closeArray;
  46960. vertexData.applyToMesh(ribbon, updatable);
  46961. return ribbon;
  46962. }
  46963. };
  46964. /**
  46965. * Creates a cylinder or a cone mesh.
  46966. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  46967. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  46968. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  46969. * 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.
  46970. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  46971. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  46972. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  46973. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  46974. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  46975. * 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).
  46976. * 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
  46977. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  46978. * 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
  46979. * 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.
  46980. * If `enclose` is false, a ring surface is one element.
  46981. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  46982. * 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
  46983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46984. * 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).
  46985. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46987. */
  46988. MeshBuilder.CreateCylinder = function (name, options, scene) {
  46989. var cylinder = new BABYLON.Mesh(name, scene);
  46990. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  46991. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  46992. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  46993. vertexData.applyToMesh(cylinder, options.updatable);
  46994. return cylinder;
  46995. };
  46996. /**
  46997. * Creates a torus mesh.
  46998. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  46999. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47000. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47001. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47002. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47003. * 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).
  47004. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47006. */
  47007. MeshBuilder.CreateTorus = function (name, options, scene) {
  47008. var torus = new BABYLON.Mesh(name, scene);
  47009. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47010. torus._originalBuilderSideOrientation = options.sideOrientation;
  47011. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47012. vertexData.applyToMesh(torus, options.updatable);
  47013. return torus;
  47014. };
  47015. /**
  47016. * Creates a torus knot mesh.
  47017. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47018. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47019. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47020. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47021. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47023. * 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).
  47024. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47025. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47026. */
  47027. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47028. var torusKnot = new BABYLON.Mesh(name, scene);
  47029. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47030. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47031. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47032. vertexData.applyToMesh(torusKnot, options.updatable);
  47033. return torusKnot;
  47034. };
  47035. /**
  47036. * Creates a line system mesh.
  47037. * A line system is a pool of many lines gathered in a single mesh.
  47038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47039. * 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.
  47040. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47041. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47042. * 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
  47043. * 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
  47044. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47046. */
  47047. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47048. var instance = options.instance;
  47049. var lines = options.lines;
  47050. if (instance) {
  47051. var positionFunction = function (positions) {
  47052. var i = 0;
  47053. for (var l = 0; l < lines.length; l++) {
  47054. var points = lines[l];
  47055. for (var p = 0; p < points.length; p++) {
  47056. positions[i] = points[p].x;
  47057. positions[i + 1] = points[p].y;
  47058. positions[i + 2] = points[p].z;
  47059. i += 3;
  47060. }
  47061. }
  47062. };
  47063. instance.updateMeshPositions(positionFunction, false);
  47064. return instance;
  47065. }
  47066. // line system creation
  47067. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47068. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47069. vertexData.applyToMesh(lineSystem, options.updatable);
  47070. return lineSystem;
  47071. };
  47072. /**
  47073. * Creates a line mesh.
  47074. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47075. * 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.
  47076. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47077. * The parameter `points` is an array successive Vector3.
  47078. * 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
  47079. * When updating an instance, remember that only point positions can change, not the number of points.
  47080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47081. */
  47082. MeshBuilder.CreateLines = function (name, options, scene) {
  47083. if (scene === void 0) { scene = null; }
  47084. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47085. return lines;
  47086. };
  47087. /**
  47088. * Creates a dashed line mesh.
  47089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47090. * 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.
  47091. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47092. * The parameter `points` is an array successive Vector3.
  47093. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47094. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47095. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47096. * 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
  47097. * When updating an instance, remember that only point positions can change, not the number of points.
  47098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47099. */
  47100. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47101. if (scene === void 0) { scene = null; }
  47102. var points = options.points;
  47103. var instance = options.instance;
  47104. var gapSize = options.gapSize || 1;
  47105. var dashSize = options.dashSize || 3;
  47106. if (instance) {
  47107. var positionFunction = function (positions) {
  47108. var curvect = BABYLON.Vector3.Zero();
  47109. var nbSeg = positions.length / 6;
  47110. var lg = 0;
  47111. var nb = 0;
  47112. var shft = 0;
  47113. var dashshft = 0;
  47114. var curshft = 0;
  47115. var p = 0;
  47116. var i = 0;
  47117. var j = 0;
  47118. for (i = 0; i < points.length - 1; i++) {
  47119. points[i + 1].subtractToRef(points[i], curvect);
  47120. lg += curvect.length();
  47121. }
  47122. shft = lg / nbSeg;
  47123. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47124. for (i = 0; i < points.length - 1; i++) {
  47125. points[i + 1].subtractToRef(points[i], curvect);
  47126. nb = Math.floor(curvect.length() / shft);
  47127. curvect.normalize();
  47128. j = 0;
  47129. while (j < nb && p < positions.length) {
  47130. curshft = shft * j;
  47131. positions[p] = points[i].x + curshft * curvect.x;
  47132. positions[p + 1] = points[i].y + curshft * curvect.y;
  47133. positions[p + 2] = points[i].z + curshft * curvect.z;
  47134. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47135. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47136. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47137. p += 6;
  47138. j++;
  47139. }
  47140. }
  47141. while (p < positions.length) {
  47142. positions[p] = points[i].x;
  47143. positions[p + 1] = points[i].y;
  47144. positions[p + 2] = points[i].z;
  47145. p += 3;
  47146. }
  47147. };
  47148. instance.updateMeshPositions(positionFunction, false);
  47149. return instance;
  47150. }
  47151. // dashed lines creation
  47152. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47153. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47154. vertexData.applyToMesh(dashedLines, options.updatable);
  47155. dashedLines.dashSize = dashSize;
  47156. dashedLines.gapSize = gapSize;
  47157. return dashedLines;
  47158. };
  47159. /**
  47160. * Creates an extruded shape mesh.
  47161. * 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.
  47162. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47163. *
  47164. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47165. * 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
  47166. * extruded along the Z axis.
  47167. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47168. * 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.
  47169. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47170. * 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
  47171. * 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
  47172. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47174. * 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).
  47175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47176. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47178. */
  47179. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47180. if (scene === void 0) { scene = null; }
  47181. var path = options.path;
  47182. var shape = options.shape;
  47183. var scale = options.scale || 1;
  47184. var rotation = options.rotation || 0;
  47185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47186. var updatable = options.updatable;
  47187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47188. var instance = options.instance || null;
  47189. var invertUV = options.invertUV || false;
  47190. 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);
  47191. };
  47192. /**
  47193. * Creates an custom extruded shape mesh.
  47194. * 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.
  47195. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47196. *
  47197. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47198. * 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
  47199. * extruded along the Z axis.
  47200. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47201. * 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
  47202. * and the distance of this point from the begining of the path :
  47203. * ```javascript
  47204. * var rotationFunction = function(i, distance) {
  47205. * // do things
  47206. * return rotationValue; }
  47207. * ```
  47208. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47209. * 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
  47210. * and the distance of this point from the begining of the path :
  47211. * ```javascript
  47212. * var scaleFunction = function(i, distance) {
  47213. * // do things
  47214. * return scaleValue;}
  47215. * ```
  47216. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47217. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47218. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47219. * 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
  47220. * 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
  47221. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47223. * 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).
  47224. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47225. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47227. */
  47228. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47229. var path = options.path;
  47230. var shape = options.shape;
  47231. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47232. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47233. var ribbonCloseArray = options.ribbonCloseArray || false;
  47234. var ribbonClosePath = options.ribbonClosePath || false;
  47235. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47236. var updatable = options.updatable;
  47237. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47238. var instance = options.instance;
  47239. var invertUV = options.invertUV || false;
  47240. 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);
  47241. };
  47242. /**
  47243. * Creates lathe mesh.
  47244. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47246. *
  47247. * 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
  47248. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47249. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47250. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47251. * 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.
  47252. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47253. * 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
  47254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47255. * 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).
  47256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47257. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47259. */
  47260. MeshBuilder.CreateLathe = function (name, options, scene) {
  47261. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47262. var closed = (options.closed === undefined) ? true : options.closed;
  47263. var shape = options.shape;
  47264. var radius = options.radius || 1;
  47265. var tessellation = options.tessellation || 64;
  47266. var updatable = options.updatable;
  47267. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47268. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47269. var pi2 = Math.PI * 2;
  47270. var paths = new Array();
  47271. var invertUV = options.invertUV || false;
  47272. var i = 0;
  47273. var p = 0;
  47274. var step = pi2 / tessellation * arc;
  47275. var rotated;
  47276. var path = new Array();
  47277. ;
  47278. for (i = 0; i <= tessellation; i++) {
  47279. var path = [];
  47280. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47281. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47282. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47283. }
  47284. for (p = 0; p < shape.length; p++) {
  47285. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47286. path.push(rotated);
  47287. }
  47288. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47289. 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));
  47290. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47291. }
  47292. paths.push(path);
  47293. }
  47294. // lathe ribbon
  47295. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47296. return lathe;
  47297. };
  47298. /**
  47299. * Creates a plane mesh.
  47300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47301. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47302. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47303. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47305. * 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).
  47306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47308. */
  47309. MeshBuilder.CreatePlane = function (name, options, scene) {
  47310. var plane = new BABYLON.Mesh(name, scene);
  47311. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47312. plane._originalBuilderSideOrientation = options.sideOrientation;
  47313. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47314. vertexData.applyToMesh(plane, options.updatable);
  47315. if (options.sourcePlane) {
  47316. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47317. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47318. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47319. plane.rotate(vectorProduct, product);
  47320. }
  47321. return plane;
  47322. };
  47323. /**
  47324. * Creates a ground mesh.
  47325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47326. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47327. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47329. */
  47330. MeshBuilder.CreateGround = function (name, options, scene) {
  47331. var ground = new BABYLON.GroundMesh(name, scene);
  47332. ground._setReady(false);
  47333. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47334. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47335. ground._width = options.width || 1;
  47336. ground._height = options.height || 1;
  47337. ground._maxX = ground._width / 2;
  47338. ground._maxZ = ground._height / 2;
  47339. ground._minX = -ground._maxX;
  47340. ground._minZ = -ground._maxZ;
  47341. var vertexData = BABYLON.VertexData.CreateGround(options);
  47342. vertexData.applyToMesh(ground, options.updatable);
  47343. ground._setReady(true);
  47344. return ground;
  47345. };
  47346. /**
  47347. * Creates a tiled ground mesh.
  47348. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47349. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47350. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47351. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47352. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47353. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47354. * numbers of subdivisions on the ground width and height of each tile.
  47355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47356. */
  47357. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47358. var tiledGround = new BABYLON.Mesh(name, scene);
  47359. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47360. vertexData.applyToMesh(tiledGround, options.updatable);
  47361. return tiledGround;
  47362. };
  47363. /**
  47364. * Creates a ground mesh from a height map.
  47365. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47366. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47367. * The parameter `url` sets the URL of the height map image resource.
  47368. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47369. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47370. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47371. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47372. * 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.
  47373. * 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).
  47374. * This function is passed the newly built mesh :
  47375. * ```javascript
  47376. * function(mesh) { // do things
  47377. * return; }
  47378. * ```
  47379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47380. */
  47381. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47382. var width = options.width || 10.0;
  47383. var height = options.height || 10.0;
  47384. var subdivisions = options.subdivisions || 1 | 0;
  47385. var minHeight = options.minHeight || 0.0;
  47386. var maxHeight = options.maxHeight || 1.0;
  47387. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47388. var updatable = options.updatable;
  47389. var onReady = options.onReady;
  47390. var ground = new BABYLON.GroundMesh(name, scene);
  47391. ground._subdivisionsX = subdivisions;
  47392. ground._subdivisionsY = subdivisions;
  47393. ground._width = width;
  47394. ground._height = height;
  47395. ground._maxX = ground._width / 2.0;
  47396. ground._maxZ = ground._height / 2.0;
  47397. ground._minX = -ground._maxX;
  47398. ground._minZ = -ground._maxZ;
  47399. ground._setReady(false);
  47400. var onload = function (img) {
  47401. // Getting height map data
  47402. var canvas = document.createElement("canvas");
  47403. var context = canvas.getContext("2d");
  47404. if (!context) {
  47405. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47406. }
  47407. var bufferWidth = img.width;
  47408. var bufferHeight = img.height;
  47409. canvas.width = bufferWidth;
  47410. canvas.height = bufferHeight;
  47411. context.drawImage(img, 0, 0);
  47412. // Create VertexData from map data
  47413. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47414. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47415. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47416. width: width, height: height,
  47417. subdivisions: subdivisions,
  47418. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47419. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47420. });
  47421. vertexData.applyToMesh(ground, updatable);
  47422. ground._setReady(true);
  47423. //execute ready callback, if set
  47424. if (onReady) {
  47425. onReady(ground);
  47426. }
  47427. };
  47428. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47429. return ground;
  47430. };
  47431. /**
  47432. * Creates a polygon mesh.
  47433. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47434. * 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.
  47435. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47437. * 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).
  47438. * Remember you can only change the shape positions, not their number when updating a polygon.
  47439. */
  47440. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47441. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47442. var shape = options.shape;
  47443. var holes = options.holes || [];
  47444. var depth = options.depth || 0;
  47445. var contours = [];
  47446. var hole = [];
  47447. for (var i = 0; i < shape.length; i++) {
  47448. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47449. }
  47450. var epsilon = 0.00000001;
  47451. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47452. contours.pop();
  47453. }
  47454. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47455. for (var hNb = 0; hNb < holes.length; hNb++) {
  47456. hole = [];
  47457. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47458. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47459. }
  47460. polygonTriangulation.addHole(hole);
  47461. }
  47462. var polygon = polygonTriangulation.build(options.updatable, depth);
  47463. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47464. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47465. vertexData.applyToMesh(polygon, options.updatable);
  47466. return polygon;
  47467. };
  47468. ;
  47469. /**
  47470. * Creates an extruded polygon mesh, with depth in the Y direction.
  47471. * 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).
  47472. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47473. */
  47474. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47475. return MeshBuilder.CreatePolygon(name, options, scene);
  47476. };
  47477. ;
  47478. /**
  47479. * Creates a tube mesh.
  47480. * 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.
  47481. *
  47482. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47483. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47484. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47485. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47486. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47487. * 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.
  47488. * It must return a radius value (positive float) :
  47489. * ```javascript
  47490. * var radiusFunction = function(i, distance) {
  47491. * // do things
  47492. * return radius; }
  47493. * ```
  47494. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47495. * 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
  47496. * 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
  47497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47498. * 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).
  47499. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47500. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47502. */
  47503. MeshBuilder.CreateTube = function (name, options, scene) {
  47504. var path = options.path;
  47505. var instance = options.instance;
  47506. var radius = 1.0;
  47507. if (instance) {
  47508. radius = instance.radius;
  47509. }
  47510. if (options.radius !== undefined) {
  47511. radius = options.radius;
  47512. }
  47513. ;
  47514. var tessellation = options.tessellation || 64 | 0;
  47515. var radiusFunction = options.radiusFunction || null;
  47516. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47517. var invertUV = options.invertUV || false;
  47518. var updatable = options.updatable;
  47519. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47520. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47521. // tube geometry
  47522. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47523. var tangents = path3D.getTangents();
  47524. var normals = path3D.getNormals();
  47525. var distances = path3D.getDistances();
  47526. var pi2 = Math.PI * 2;
  47527. var step = pi2 / tessellation * arc;
  47528. var returnRadius = function () { return radius; };
  47529. var radiusFunctionFinal = radiusFunction || returnRadius;
  47530. var circlePath;
  47531. var rad;
  47532. var normal;
  47533. var rotated;
  47534. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47535. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47536. for (var i = 0; i < path.length; i++) {
  47537. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47538. circlePath = Array(); // current circle array
  47539. normal = normals[i]; // current normal
  47540. for (var t = 0; t < tessellation; t++) {
  47541. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47542. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47543. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47544. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47545. circlePath[t] = rotated;
  47546. }
  47547. circlePaths[index] = circlePath;
  47548. index++;
  47549. }
  47550. // cap
  47551. var capPath = function (nbPoints, pathIndex) {
  47552. var pointCap = Array();
  47553. for (var i = 0; i < nbPoints; i++) {
  47554. pointCap.push(path[pathIndex]);
  47555. }
  47556. return pointCap;
  47557. };
  47558. switch (cap) {
  47559. case BABYLON.Mesh.NO_CAP:
  47560. break;
  47561. case BABYLON.Mesh.CAP_START:
  47562. circlePaths[0] = capPath(tessellation, 0);
  47563. circlePaths[1] = circlePaths[2].slice(0);
  47564. break;
  47565. case BABYLON.Mesh.CAP_END:
  47566. circlePaths[index] = circlePaths[index - 1].slice(0);
  47567. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47568. break;
  47569. case BABYLON.Mesh.CAP_ALL:
  47570. circlePaths[0] = capPath(tessellation, 0);
  47571. circlePaths[1] = circlePaths[2].slice(0);
  47572. circlePaths[index] = circlePaths[index - 1].slice(0);
  47573. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47574. break;
  47575. default:
  47576. break;
  47577. }
  47578. return circlePaths;
  47579. };
  47580. var path3D;
  47581. var pathArray;
  47582. if (instance) {
  47583. var arc = options.arc || instance.arc;
  47584. path3D = (instance.path3D).update(path);
  47585. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47586. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47587. instance.path3D = path3D;
  47588. instance.pathArray = pathArray;
  47589. instance.arc = arc;
  47590. instance.radius = radius;
  47591. return instance;
  47592. }
  47593. // tube creation
  47594. path3D = new BABYLON.Path3D(path);
  47595. var newPathArray = new Array();
  47596. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47597. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47598. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47599. tube.pathArray = pathArray;
  47600. tube.path3D = path3D;
  47601. tube.tessellation = tessellation;
  47602. tube.cap = cap;
  47603. tube.arc = options.arc;
  47604. tube.radius = radius;
  47605. return tube;
  47606. };
  47607. /**
  47608. * Creates a polyhedron mesh.
  47609. *
  47610. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47611. * 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
  47612. * to choose the wanted type.
  47613. * The parameter `size` (positive float, default 1) sets the polygon size.
  47614. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47615. * 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`.
  47616. * 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
  47617. * 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)`).
  47618. * 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
  47619. * 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.
  47620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47621. * 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).
  47622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47624. */
  47625. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47626. var polyhedron = new BABYLON.Mesh(name, scene);
  47627. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47628. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47629. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47630. vertexData.applyToMesh(polyhedron, options.updatable);
  47631. return polyhedron;
  47632. };
  47633. /**
  47634. * Creates a decal mesh.
  47635. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  47636. * 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.
  47637. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  47638. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  47639. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  47640. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  47641. */
  47642. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  47643. var indices = sourceMesh.getIndices();
  47644. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47645. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47646. var position = options.position || BABYLON.Vector3.Zero();
  47647. var normal = options.normal || BABYLON.Vector3.Up();
  47648. var size = options.size || BABYLON.Vector3.One();
  47649. var angle = options.angle || 0;
  47650. // Getting correct rotation
  47651. if (!normal) {
  47652. var target = new BABYLON.Vector3(0, 0, 1);
  47653. var camera = sourceMesh.getScene().activeCamera;
  47654. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  47655. normal = camera.globalPosition.subtract(cameraWorldTarget);
  47656. }
  47657. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  47658. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  47659. var pitch = Math.atan2(normal.y, len);
  47660. // Matrix
  47661. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  47662. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  47663. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  47664. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  47665. var vertexData = new BABYLON.VertexData();
  47666. vertexData.indices = [];
  47667. vertexData.positions = [];
  47668. vertexData.normals = [];
  47669. vertexData.uvs = [];
  47670. var currentVertexDataIndex = 0;
  47671. var extractDecalVector3 = function (indexId) {
  47672. var result = new BABYLON.PositionNormalVertex();
  47673. if (!indices || !positions || !normals) {
  47674. return result;
  47675. }
  47676. var vertexId = indices[indexId];
  47677. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  47678. // Send vector to decal local world
  47679. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  47680. // Get normal
  47681. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  47682. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  47683. return result;
  47684. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  47685. var clip = function (vertices, axis) {
  47686. if (vertices.length === 0) {
  47687. return vertices;
  47688. }
  47689. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  47690. var clipVertices = function (v0, v1) {
  47691. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  47692. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  47693. };
  47694. var result = new Array();
  47695. for (var index = 0; index < vertices.length; index += 3) {
  47696. var v1Out;
  47697. var v2Out;
  47698. var v3Out;
  47699. var total = 0;
  47700. var nV1 = null;
  47701. var nV2 = null;
  47702. var nV3 = null;
  47703. var nV4 = null;
  47704. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  47705. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  47706. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  47707. v1Out = d1 > 0;
  47708. v2Out = d2 > 0;
  47709. v3Out = d3 > 0;
  47710. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  47711. switch (total) {
  47712. case 0:
  47713. result.push(vertices[index]);
  47714. result.push(vertices[index + 1]);
  47715. result.push(vertices[index + 2]);
  47716. break;
  47717. case 1:
  47718. if (v1Out) {
  47719. nV1 = vertices[index + 1];
  47720. nV2 = vertices[index + 2];
  47721. nV3 = clipVertices(vertices[index], nV1);
  47722. nV4 = clipVertices(vertices[index], nV2);
  47723. }
  47724. if (v2Out) {
  47725. nV1 = vertices[index];
  47726. nV2 = vertices[index + 2];
  47727. nV3 = clipVertices(vertices[index + 1], nV1);
  47728. nV4 = clipVertices(vertices[index + 1], nV2);
  47729. result.push(nV3);
  47730. result.push(nV2.clone());
  47731. result.push(nV1.clone());
  47732. result.push(nV2.clone());
  47733. result.push(nV3.clone());
  47734. result.push(nV4);
  47735. break;
  47736. }
  47737. if (v3Out) {
  47738. nV1 = vertices[index];
  47739. nV2 = vertices[index + 1];
  47740. nV3 = clipVertices(vertices[index + 2], nV1);
  47741. nV4 = clipVertices(vertices[index + 2], nV2);
  47742. }
  47743. if (nV1 && nV2 && nV3 && nV4) {
  47744. result.push(nV1.clone());
  47745. result.push(nV2.clone());
  47746. result.push(nV3);
  47747. result.push(nV4);
  47748. result.push(nV3.clone());
  47749. result.push(nV2.clone());
  47750. }
  47751. break;
  47752. case 2:
  47753. if (!v1Out) {
  47754. nV1 = vertices[index].clone();
  47755. nV2 = clipVertices(nV1, vertices[index + 1]);
  47756. nV3 = clipVertices(nV1, vertices[index + 2]);
  47757. result.push(nV1);
  47758. result.push(nV2);
  47759. result.push(nV3);
  47760. }
  47761. if (!v2Out) {
  47762. nV1 = vertices[index + 1].clone();
  47763. nV2 = clipVertices(nV1, vertices[index + 2]);
  47764. nV3 = clipVertices(nV1, vertices[index]);
  47765. result.push(nV1);
  47766. result.push(nV2);
  47767. result.push(nV3);
  47768. }
  47769. if (!v3Out) {
  47770. nV1 = vertices[index + 2].clone();
  47771. nV2 = clipVertices(nV1, vertices[index]);
  47772. nV3 = clipVertices(nV1, vertices[index + 1]);
  47773. result.push(nV1);
  47774. result.push(nV2);
  47775. result.push(nV3);
  47776. }
  47777. break;
  47778. case 3:
  47779. break;
  47780. }
  47781. }
  47782. return result;
  47783. };
  47784. for (var index = 0; index < indices.length; index += 3) {
  47785. var faceVertices = new Array();
  47786. faceVertices.push(extractDecalVector3(index));
  47787. faceVertices.push(extractDecalVector3(index + 1));
  47788. faceVertices.push(extractDecalVector3(index + 2));
  47789. // Clip
  47790. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  47791. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  47792. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  47793. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  47794. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  47795. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  47796. if (faceVertices.length === 0) {
  47797. continue;
  47798. }
  47799. // Add UVs and get back to world
  47800. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  47801. var vertex = faceVertices[vIndex];
  47802. //TODO check for Int32Array | Uint32Array | Uint16Array
  47803. vertexData.indices.push(currentVertexDataIndex);
  47804. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  47805. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  47806. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  47807. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  47808. currentVertexDataIndex++;
  47809. }
  47810. }
  47811. // Return mesh
  47812. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  47813. vertexData.applyToMesh(decal);
  47814. decal.position = position.clone();
  47815. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  47816. return decal;
  47817. };
  47818. // Privates
  47819. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  47820. // extrusion geometry
  47821. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  47822. var tangents = path3D.getTangents();
  47823. var normals = path3D.getNormals();
  47824. var binormals = path3D.getBinormals();
  47825. var distances = path3D.getDistances();
  47826. var angle = 0;
  47827. var returnScale = function () { return scale !== null ? scale : 1; };
  47828. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  47829. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  47830. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  47831. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47832. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47833. for (var i = 0; i < curve.length; i++) {
  47834. var shapePath = new Array();
  47835. var angleStep = rotate(i, distances[i]);
  47836. var scaleRatio = scl(i, distances[i]);
  47837. for (var p = 0; p < shape.length; p++) {
  47838. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  47839. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  47840. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  47841. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  47842. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  47843. shapePath[p] = rotated;
  47844. }
  47845. shapePaths[index] = shapePath;
  47846. angle += angleStep;
  47847. index++;
  47848. }
  47849. // cap
  47850. var capPath = function (shapePath) {
  47851. var pointCap = Array();
  47852. var barycenter = BABYLON.Vector3.Zero();
  47853. var i;
  47854. for (i = 0; i < shapePath.length; i++) {
  47855. barycenter.addInPlace(shapePath[i]);
  47856. }
  47857. barycenter.scaleInPlace(1.0 / shapePath.length);
  47858. for (i = 0; i < shapePath.length; i++) {
  47859. pointCap.push(barycenter);
  47860. }
  47861. return pointCap;
  47862. };
  47863. switch (cap) {
  47864. case BABYLON.Mesh.NO_CAP:
  47865. break;
  47866. case BABYLON.Mesh.CAP_START:
  47867. shapePaths[0] = capPath(shapePaths[2]);
  47868. shapePaths[1] = shapePaths[2];
  47869. break;
  47870. case BABYLON.Mesh.CAP_END:
  47871. shapePaths[index] = shapePaths[index - 1];
  47872. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47873. break;
  47874. case BABYLON.Mesh.CAP_ALL:
  47875. shapePaths[0] = capPath(shapePaths[2]);
  47876. shapePaths[1] = shapePaths[2];
  47877. shapePaths[index] = shapePaths[index - 1];
  47878. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  47879. break;
  47880. default:
  47881. break;
  47882. }
  47883. return shapePaths;
  47884. };
  47885. var path3D;
  47886. var pathArray;
  47887. if (instance) {
  47888. path3D = (instance.path3D).update(curve);
  47889. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  47890. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  47891. return instance;
  47892. }
  47893. // extruded shape creation
  47894. path3D = new BABYLON.Path3D(curve);
  47895. var newShapePaths = new Array();
  47896. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47897. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  47898. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  47899. extrudedGeneric.pathArray = pathArray;
  47900. extrudedGeneric.path3D = path3D;
  47901. extrudedGeneric.cap = cap;
  47902. return extrudedGeneric;
  47903. };
  47904. return MeshBuilder;
  47905. }());
  47906. BABYLON.MeshBuilder = MeshBuilder;
  47907. })(BABYLON || (BABYLON = {}));
  47908. //# sourceMappingURL=babylon.meshBuilder.js.map
  47909. var BABYLON;
  47910. (function (BABYLON) {
  47911. var AudioEngine = /** @class */ (function () {
  47912. function AudioEngine() {
  47913. this._audioContext = null;
  47914. this._audioContextInitialized = false;
  47915. this.canUseWebAudio = false;
  47916. this.WarnedWebAudioUnsupported = false;
  47917. this.unlocked = false;
  47918. this.isMP3supported = false;
  47919. this.isOGGsupported = false;
  47920. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  47921. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  47922. this.canUseWebAudio = true;
  47923. }
  47924. var audioElem = document.createElement('audio');
  47925. try {
  47926. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  47927. this.isMP3supported = true;
  47928. }
  47929. }
  47930. catch (e) {
  47931. // protect error during capability check.
  47932. }
  47933. try {
  47934. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  47935. this.isOGGsupported = true;
  47936. }
  47937. }
  47938. catch (e) {
  47939. // protect error during capability check.
  47940. }
  47941. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  47942. this._unlockiOSaudio();
  47943. }
  47944. else {
  47945. this.unlocked = true;
  47946. }
  47947. }
  47948. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  47949. get: function () {
  47950. if (!this._audioContextInitialized) {
  47951. this._initializeAudioContext();
  47952. }
  47953. return this._audioContext;
  47954. },
  47955. enumerable: true,
  47956. configurable: true
  47957. });
  47958. AudioEngine.prototype._unlockiOSaudio = function () {
  47959. var _this = this;
  47960. var unlockaudio = function () {
  47961. if (!_this.audioContext) {
  47962. return;
  47963. }
  47964. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  47965. var source = _this.audioContext.createBufferSource();
  47966. source.buffer = buffer;
  47967. source.connect(_this.audioContext.destination);
  47968. source.start(0);
  47969. setTimeout(function () {
  47970. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  47971. _this.unlocked = true;
  47972. window.removeEventListener('touchend', unlockaudio, false);
  47973. if (_this.onAudioUnlocked) {
  47974. _this.onAudioUnlocked();
  47975. }
  47976. }
  47977. }, 0);
  47978. };
  47979. window.addEventListener('touchend', unlockaudio, false);
  47980. };
  47981. AudioEngine.prototype._initializeAudioContext = function () {
  47982. try {
  47983. if (this.canUseWebAudio) {
  47984. this._audioContext = new AudioContext();
  47985. // create a global volume gain node
  47986. this.masterGain = this._audioContext.createGain();
  47987. this.masterGain.gain.value = 1;
  47988. this.masterGain.connect(this._audioContext.destination);
  47989. this._audioContextInitialized = true;
  47990. }
  47991. }
  47992. catch (e) {
  47993. this.canUseWebAudio = false;
  47994. BABYLON.Tools.Error("Web Audio: " + e.message);
  47995. }
  47996. };
  47997. AudioEngine.prototype.dispose = function () {
  47998. if (this.canUseWebAudio && this._audioContextInitialized) {
  47999. if (this._connectedAnalyser && this._audioContext) {
  48000. this._connectedAnalyser.stopDebugCanvas();
  48001. this._connectedAnalyser.dispose();
  48002. this.masterGain.disconnect();
  48003. this.masterGain.connect(this._audioContext.destination);
  48004. this._connectedAnalyser = null;
  48005. }
  48006. this.masterGain.gain.value = 1;
  48007. }
  48008. this.WarnedWebAudioUnsupported = false;
  48009. };
  48010. AudioEngine.prototype.getGlobalVolume = function () {
  48011. if (this.canUseWebAudio && this._audioContextInitialized) {
  48012. return this.masterGain.gain.value;
  48013. }
  48014. else {
  48015. return -1;
  48016. }
  48017. };
  48018. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48019. if (this.canUseWebAudio && this._audioContextInitialized) {
  48020. this.masterGain.gain.value = newVolume;
  48021. }
  48022. };
  48023. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48024. if (this._connectedAnalyser) {
  48025. this._connectedAnalyser.stopDebugCanvas();
  48026. }
  48027. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48028. this._connectedAnalyser = analyser;
  48029. this.masterGain.disconnect();
  48030. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48031. }
  48032. };
  48033. return AudioEngine;
  48034. }());
  48035. BABYLON.AudioEngine = AudioEngine;
  48036. })(BABYLON || (BABYLON = {}));
  48037. //# sourceMappingURL=babylon.audioEngine.js.map
  48038. var BABYLON;
  48039. (function (BABYLON) {
  48040. var Sound = /** @class */ (function () {
  48041. /**
  48042. * Create a sound and attach it to a scene
  48043. * @param name Name of your sound
  48044. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48045. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48046. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48047. */
  48048. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48049. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48050. var _this = this;
  48051. this.autoplay = false;
  48052. this.loop = false;
  48053. this.useCustomAttenuation = false;
  48054. this.spatialSound = false;
  48055. this.refDistance = 1;
  48056. this.rolloffFactor = 1;
  48057. this.maxDistance = 100;
  48058. this.distanceModel = "linear";
  48059. this._panningModel = "equalpower";
  48060. this._playbackRate = 1;
  48061. this._streaming = false;
  48062. this._startTime = 0;
  48063. this._startOffset = 0;
  48064. this._position = BABYLON.Vector3.Zero();
  48065. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48066. this._volume = 1;
  48067. this._isLoaded = false;
  48068. this._isReadyToPlay = false;
  48069. this.isPlaying = false;
  48070. this.isPaused = false;
  48071. this._isDirectional = false;
  48072. // Used if you'd like to create a directional sound.
  48073. // If not set, the sound will be omnidirectional
  48074. this._coneInnerAngle = 360;
  48075. this._coneOuterAngle = 360;
  48076. this._coneOuterGain = 0;
  48077. this._isOutputConnected = false;
  48078. this._urlType = "Unknown";
  48079. this.name = name;
  48080. this._scene = scene;
  48081. this._readyToPlayCallback = readyToPlayCallback;
  48082. // Default custom attenuation function is a linear attenuation
  48083. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48084. if (currentDistance < maxDistance) {
  48085. return currentVolume * (1 - currentDistance / maxDistance);
  48086. }
  48087. else {
  48088. return 0;
  48089. }
  48090. };
  48091. if (options) {
  48092. this.autoplay = options.autoplay || false;
  48093. this.loop = options.loop || false;
  48094. // if volume === 0, we need another way to check this option
  48095. if (options.volume !== undefined) {
  48096. this._volume = options.volume;
  48097. }
  48098. this.spatialSound = options.spatialSound || false;
  48099. this.maxDistance = options.maxDistance || 100;
  48100. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48101. this.rolloffFactor = options.rolloffFactor || 1;
  48102. this.refDistance = options.refDistance || 1;
  48103. this.distanceModel = options.distanceModel || "linear";
  48104. this._playbackRate = options.playbackRate || 1;
  48105. this._streaming = options.streaming || false;
  48106. }
  48107. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48108. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48109. this._soundGain.gain.value = this._volume;
  48110. this._inputAudioNode = this._soundGain;
  48111. this._ouputAudioNode = this._soundGain;
  48112. if (this.spatialSound) {
  48113. this._createSpatialParameters();
  48114. }
  48115. this._scene.mainSoundTrack.AddSound(this);
  48116. var validParameter = true;
  48117. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48118. if (urlOrArrayBuffer) {
  48119. if (typeof (urlOrArrayBuffer) === "string")
  48120. this._urlType = "String";
  48121. if (Array.isArray(urlOrArrayBuffer))
  48122. this._urlType = "Array";
  48123. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48124. this._urlType = "ArrayBuffer";
  48125. var urls = [];
  48126. var codecSupportedFound = false;
  48127. switch (this._urlType) {
  48128. case "ArrayBuffer":
  48129. if (urlOrArrayBuffer.byteLength > 0) {
  48130. codecSupportedFound = true;
  48131. this._soundLoaded(urlOrArrayBuffer);
  48132. }
  48133. break;
  48134. case "String":
  48135. urls.push(urlOrArrayBuffer);
  48136. case "Array":
  48137. if (urls.length === 0)
  48138. urls = urlOrArrayBuffer;
  48139. // If we found a supported format, we load it immediately and stop the loop
  48140. for (var i = 0; i < urls.length; i++) {
  48141. var url = urls[i];
  48142. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48143. codecSupportedFound = true;
  48144. }
  48145. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48146. codecSupportedFound = true;
  48147. }
  48148. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48149. codecSupportedFound = true;
  48150. }
  48151. if (url.indexOf("blob:") !== -1) {
  48152. codecSupportedFound = true;
  48153. }
  48154. if (codecSupportedFound) {
  48155. // Loading sound using XHR2
  48156. if (!this._streaming) {
  48157. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48158. }
  48159. else {
  48160. this._htmlAudioElement = new Audio(url);
  48161. this._htmlAudioElement.controls = false;
  48162. this._htmlAudioElement.loop = this.loop;
  48163. this._htmlAudioElement.crossOrigin = "anonymous";
  48164. this._htmlAudioElement.preload = "auto";
  48165. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48166. _this._isReadyToPlay = true;
  48167. if (_this.autoplay) {
  48168. _this.play();
  48169. }
  48170. if (_this._readyToPlayCallback) {
  48171. _this._readyToPlayCallback();
  48172. }
  48173. });
  48174. document.body.appendChild(this._htmlAudioElement);
  48175. }
  48176. break;
  48177. }
  48178. }
  48179. break;
  48180. default:
  48181. validParameter = false;
  48182. break;
  48183. }
  48184. if (!validParameter) {
  48185. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48186. }
  48187. else {
  48188. if (!codecSupportedFound) {
  48189. this._isReadyToPlay = true;
  48190. // Simulating a ready to play event to avoid breaking code path
  48191. if (this._readyToPlayCallback) {
  48192. window.setTimeout(function () {
  48193. if (_this._readyToPlayCallback) {
  48194. _this._readyToPlayCallback();
  48195. }
  48196. }, 1000);
  48197. }
  48198. }
  48199. }
  48200. }
  48201. }
  48202. else {
  48203. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48204. this._scene.mainSoundTrack.AddSound(this);
  48205. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48206. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48207. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48208. }
  48209. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48210. if (this._readyToPlayCallback) {
  48211. window.setTimeout(function () {
  48212. if (_this._readyToPlayCallback) {
  48213. _this._readyToPlayCallback();
  48214. }
  48215. }, 1000);
  48216. }
  48217. }
  48218. }
  48219. Sound.prototype.dispose = function () {
  48220. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48221. if (this.isPlaying) {
  48222. this.stop();
  48223. }
  48224. this._isReadyToPlay = false;
  48225. if (this.soundTrackId === -1) {
  48226. this._scene.mainSoundTrack.RemoveSound(this);
  48227. }
  48228. else {
  48229. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48230. }
  48231. if (this._soundGain) {
  48232. this._soundGain.disconnect();
  48233. this._soundGain = null;
  48234. }
  48235. if (this._soundPanner) {
  48236. this._soundPanner.disconnect();
  48237. this._soundPanner = null;
  48238. }
  48239. if (this._soundSource) {
  48240. this._soundSource.disconnect();
  48241. this._soundSource = null;
  48242. }
  48243. this._audioBuffer = null;
  48244. if (this._htmlAudioElement) {
  48245. this._htmlAudioElement.pause();
  48246. this._htmlAudioElement.src = "";
  48247. document.body.removeChild(this._htmlAudioElement);
  48248. }
  48249. if (this._connectedMesh && this._registerFunc) {
  48250. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48251. this._connectedMesh = null;
  48252. }
  48253. }
  48254. };
  48255. Sound.prototype.isReady = function () {
  48256. return this._isReadyToPlay;
  48257. };
  48258. Sound.prototype._soundLoaded = function (audioData) {
  48259. var _this = this;
  48260. this._isLoaded = true;
  48261. if (!BABYLON.Engine.audioEngine.audioContext) {
  48262. return;
  48263. }
  48264. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48265. _this._audioBuffer = buffer;
  48266. _this._isReadyToPlay = true;
  48267. if (_this.autoplay) {
  48268. _this.play();
  48269. }
  48270. if (_this._readyToPlayCallback) {
  48271. _this._readyToPlayCallback();
  48272. }
  48273. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48274. };
  48275. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48276. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48277. this._audioBuffer = audioBuffer;
  48278. this._isReadyToPlay = true;
  48279. }
  48280. };
  48281. Sound.prototype.updateOptions = function (options) {
  48282. if (options) {
  48283. this.loop = options.loop || this.loop;
  48284. this.maxDistance = options.maxDistance || this.maxDistance;
  48285. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48286. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48287. this.refDistance = options.refDistance || this.refDistance;
  48288. this.distanceModel = options.distanceModel || this.distanceModel;
  48289. this._playbackRate = options.playbackRate || this._playbackRate;
  48290. this._updateSpatialParameters();
  48291. if (this.isPlaying) {
  48292. if (this._streaming) {
  48293. this._htmlAudioElement.playbackRate = this._playbackRate;
  48294. }
  48295. else {
  48296. if (this._soundSource) {
  48297. this._soundSource.playbackRate.value = this._playbackRate;
  48298. }
  48299. }
  48300. }
  48301. }
  48302. };
  48303. Sound.prototype._createSpatialParameters = function () {
  48304. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48305. if (this._scene.headphone) {
  48306. this._panningModel = "HRTF";
  48307. }
  48308. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48309. this._updateSpatialParameters();
  48310. this._soundPanner.connect(this._ouputAudioNode);
  48311. this._inputAudioNode = this._soundPanner;
  48312. }
  48313. };
  48314. Sound.prototype._updateSpatialParameters = function () {
  48315. if (this.spatialSound && this._soundPanner) {
  48316. if (this.useCustomAttenuation) {
  48317. // Tricks to disable in a way embedded Web Audio attenuation
  48318. this._soundPanner.distanceModel = "linear";
  48319. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48320. this._soundPanner.refDistance = 1;
  48321. this._soundPanner.rolloffFactor = 1;
  48322. this._soundPanner.panningModel = this._panningModel;
  48323. }
  48324. else {
  48325. this._soundPanner.distanceModel = this.distanceModel;
  48326. this._soundPanner.maxDistance = this.maxDistance;
  48327. this._soundPanner.refDistance = this.refDistance;
  48328. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48329. this._soundPanner.panningModel = this._panningModel;
  48330. }
  48331. }
  48332. };
  48333. Sound.prototype.switchPanningModelToHRTF = function () {
  48334. this._panningModel = "HRTF";
  48335. this._switchPanningModel();
  48336. };
  48337. Sound.prototype.switchPanningModelToEqualPower = function () {
  48338. this._panningModel = "equalpower";
  48339. this._switchPanningModel();
  48340. };
  48341. Sound.prototype._switchPanningModel = function () {
  48342. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48343. this._soundPanner.panningModel = this._panningModel;
  48344. }
  48345. };
  48346. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48348. if (this._isOutputConnected) {
  48349. this._ouputAudioNode.disconnect();
  48350. }
  48351. this._ouputAudioNode.connect(soundTrackAudioNode);
  48352. this._isOutputConnected = true;
  48353. }
  48354. };
  48355. /**
  48356. * Transform this sound into a directional source
  48357. * @param coneInnerAngle Size of the inner cone in degree
  48358. * @param coneOuterAngle Size of the outer cone in degree
  48359. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48360. */
  48361. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48362. if (coneOuterAngle < coneInnerAngle) {
  48363. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48364. return;
  48365. }
  48366. this._coneInnerAngle = coneInnerAngle;
  48367. this._coneOuterAngle = coneOuterAngle;
  48368. this._coneOuterGain = coneOuterGain;
  48369. this._isDirectional = true;
  48370. if (this.isPlaying && this.loop) {
  48371. this.stop();
  48372. this.play();
  48373. }
  48374. };
  48375. Sound.prototype.setPosition = function (newPosition) {
  48376. this._position = newPosition;
  48377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48378. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48379. }
  48380. };
  48381. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48382. this._localDirection = newLocalDirection;
  48383. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48384. this._updateDirection();
  48385. }
  48386. };
  48387. Sound.prototype._updateDirection = function () {
  48388. if (!this._connectedMesh || !this._soundPanner) {
  48389. return;
  48390. }
  48391. var mat = this._connectedMesh.getWorldMatrix();
  48392. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48393. direction.normalize();
  48394. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48395. };
  48396. Sound.prototype.updateDistanceFromListener = function () {
  48397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48398. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48399. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48400. }
  48401. };
  48402. Sound.prototype.setAttenuationFunction = function (callback) {
  48403. this._customAttenuationFunction = callback;
  48404. };
  48405. /**
  48406. * Play the sound
  48407. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48408. * @param offset (optional) Start the sound setting it at a specific time
  48409. */
  48410. Sound.prototype.play = function (time, offset) {
  48411. var _this = this;
  48412. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48413. try {
  48414. if (this._startOffset < 0) {
  48415. time = -this._startOffset;
  48416. this._startOffset = 0;
  48417. }
  48418. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48419. if (!this._soundSource || !this._streamingSource) {
  48420. if (this.spatialSound && this._soundPanner) {
  48421. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48422. if (this._isDirectional) {
  48423. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48424. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48425. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48426. if (this._connectedMesh) {
  48427. this._updateDirection();
  48428. }
  48429. else {
  48430. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48431. }
  48432. }
  48433. }
  48434. }
  48435. if (this._streaming) {
  48436. if (!this._streamingSource) {
  48437. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48438. this._htmlAudioElement.onended = function () { _this._onended(); };
  48439. this._htmlAudioElement.playbackRate = this._playbackRate;
  48440. }
  48441. this._streamingSource.disconnect();
  48442. this._streamingSource.connect(this._inputAudioNode);
  48443. this._htmlAudioElement.play();
  48444. }
  48445. else {
  48446. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48447. this._soundSource.buffer = this._audioBuffer;
  48448. this._soundSource.connect(this._inputAudioNode);
  48449. this._soundSource.loop = this.loop;
  48450. this._soundSource.playbackRate.value = this._playbackRate;
  48451. this._soundSource.onended = function () { _this._onended(); };
  48452. if (this._soundSource.buffer) {
  48453. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48454. }
  48455. }
  48456. this._startTime = startTime;
  48457. this.isPlaying = true;
  48458. this.isPaused = false;
  48459. }
  48460. catch (ex) {
  48461. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48462. }
  48463. }
  48464. };
  48465. Sound.prototype._onended = function () {
  48466. this.isPlaying = false;
  48467. if (this.onended) {
  48468. this.onended();
  48469. }
  48470. };
  48471. /**
  48472. * Stop the sound
  48473. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48474. */
  48475. Sound.prototype.stop = function (time) {
  48476. if (this.isPlaying) {
  48477. if (this._streaming) {
  48478. this._htmlAudioElement.pause();
  48479. // Test needed for Firefox or it will generate an Invalid State Error
  48480. if (this._htmlAudioElement.currentTime > 0) {
  48481. this._htmlAudioElement.currentTime = 0;
  48482. }
  48483. }
  48484. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48485. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48486. this._soundSource.stop(stopTime);
  48487. this._soundSource.onended = function () { };
  48488. if (!this.isPaused) {
  48489. this._startOffset = 0;
  48490. }
  48491. }
  48492. this.isPlaying = false;
  48493. }
  48494. };
  48495. Sound.prototype.pause = function () {
  48496. if (this.isPlaying) {
  48497. this.isPaused = true;
  48498. if (this._streaming) {
  48499. this._htmlAudioElement.pause();
  48500. }
  48501. else if (BABYLON.Engine.audioEngine.audioContext) {
  48502. this.stop(0);
  48503. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48504. }
  48505. }
  48506. };
  48507. Sound.prototype.setVolume = function (newVolume, time) {
  48508. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48509. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48510. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48511. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48512. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48513. }
  48514. else {
  48515. this._soundGain.gain.value = newVolume;
  48516. }
  48517. }
  48518. this._volume = newVolume;
  48519. };
  48520. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48521. this._playbackRate = newPlaybackRate;
  48522. if (this.isPlaying) {
  48523. if (this._streaming) {
  48524. this._htmlAudioElement.playbackRate = this._playbackRate;
  48525. }
  48526. else if (this._soundSource) {
  48527. this._soundSource.playbackRate.value = this._playbackRate;
  48528. }
  48529. }
  48530. };
  48531. Sound.prototype.getVolume = function () {
  48532. return this._volume;
  48533. };
  48534. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48535. var _this = this;
  48536. if (this._connectedMesh && this._registerFunc) {
  48537. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48538. this._registerFunc = null;
  48539. }
  48540. this._connectedMesh = meshToConnectTo;
  48541. if (!this.spatialSound) {
  48542. this.spatialSound = true;
  48543. this._createSpatialParameters();
  48544. if (this.isPlaying && this.loop) {
  48545. this.stop();
  48546. this.play();
  48547. }
  48548. }
  48549. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48550. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48551. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48552. };
  48553. Sound.prototype.detachFromMesh = function () {
  48554. if (this._connectedMesh && this._registerFunc) {
  48555. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48556. this._registerFunc = null;
  48557. this._connectedMesh = null;
  48558. }
  48559. };
  48560. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48561. var boundingInfo = connectedMesh.getBoundingInfo();
  48562. if (!boundingInfo) {
  48563. return;
  48564. }
  48565. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48566. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48567. this._updateDirection();
  48568. }
  48569. };
  48570. Sound.prototype.clone = function () {
  48571. var _this = this;
  48572. if (!this._streaming) {
  48573. var setBufferAndRun = function () {
  48574. if (_this._isReadyToPlay) {
  48575. clonedSound._audioBuffer = _this.getAudioBuffer();
  48576. clonedSound._isReadyToPlay = true;
  48577. if (clonedSound.autoplay) {
  48578. clonedSound.play();
  48579. }
  48580. }
  48581. else {
  48582. window.setTimeout(setBufferAndRun, 300);
  48583. }
  48584. };
  48585. var currentOptions = {
  48586. autoplay: this.autoplay, loop: this.loop,
  48587. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48588. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48589. refDistance: this.refDistance, distanceModel: this.distanceModel
  48590. };
  48591. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48592. if (this.useCustomAttenuation) {
  48593. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48594. }
  48595. clonedSound.setPosition(this._position);
  48596. clonedSound.setPlaybackRate(this._playbackRate);
  48597. setBufferAndRun();
  48598. return clonedSound;
  48599. }
  48600. else {
  48601. return null;
  48602. }
  48603. };
  48604. Sound.prototype.getAudioBuffer = function () {
  48605. return this._audioBuffer;
  48606. };
  48607. Sound.prototype.serialize = function () {
  48608. var serializationObject = {
  48609. name: this.name,
  48610. url: this.name,
  48611. autoplay: this.autoplay,
  48612. loop: this.loop,
  48613. volume: this._volume,
  48614. spatialSound: this.spatialSound,
  48615. maxDistance: this.maxDistance,
  48616. rolloffFactor: this.rolloffFactor,
  48617. refDistance: this.refDistance,
  48618. distanceModel: this.distanceModel,
  48619. playbackRate: this._playbackRate,
  48620. panningModel: this._panningModel,
  48621. soundTrackId: this.soundTrackId
  48622. };
  48623. if (this.spatialSound) {
  48624. if (this._connectedMesh)
  48625. serializationObject.connectedMeshId = this._connectedMesh.id;
  48626. serializationObject.position = this._position.asArray();
  48627. serializationObject.refDistance = this.refDistance;
  48628. serializationObject.distanceModel = this.distanceModel;
  48629. serializationObject.isDirectional = this._isDirectional;
  48630. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48631. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48632. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48633. serializationObject.coneOuterGain = this._coneOuterGain;
  48634. }
  48635. return serializationObject;
  48636. };
  48637. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  48638. var soundName = parsedSound.name;
  48639. var soundUrl;
  48640. if (parsedSound.url) {
  48641. soundUrl = rootUrl + parsedSound.url;
  48642. }
  48643. else {
  48644. soundUrl = rootUrl + soundName;
  48645. }
  48646. var options = {
  48647. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  48648. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  48649. rolloffFactor: parsedSound.rolloffFactor,
  48650. refDistance: parsedSound.refDistance,
  48651. distanceModel: parsedSound.distanceModel,
  48652. playbackRate: parsedSound.playbackRate
  48653. };
  48654. var newSound;
  48655. if (!sourceSound) {
  48656. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  48657. scene._addPendingData(newSound);
  48658. }
  48659. else {
  48660. var setBufferAndRun = function () {
  48661. if (sourceSound._isReadyToPlay) {
  48662. newSound._audioBuffer = sourceSound.getAudioBuffer();
  48663. newSound._isReadyToPlay = true;
  48664. if (newSound.autoplay) {
  48665. newSound.play();
  48666. }
  48667. }
  48668. else {
  48669. window.setTimeout(setBufferAndRun, 300);
  48670. }
  48671. };
  48672. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  48673. setBufferAndRun();
  48674. }
  48675. if (parsedSound.position) {
  48676. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  48677. newSound.setPosition(soundPosition);
  48678. }
  48679. if (parsedSound.isDirectional) {
  48680. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  48681. if (parsedSound.localDirectionToMesh) {
  48682. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  48683. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  48684. }
  48685. }
  48686. if (parsedSound.connectedMeshId) {
  48687. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  48688. if (connectedMesh) {
  48689. newSound.attachToMesh(connectedMesh);
  48690. }
  48691. }
  48692. return newSound;
  48693. };
  48694. return Sound;
  48695. }());
  48696. BABYLON.Sound = Sound;
  48697. })(BABYLON || (BABYLON = {}));
  48698. //# sourceMappingURL=babylon.sound.js.map
  48699. var BABYLON;
  48700. (function (BABYLON) {
  48701. var SoundTrack = /** @class */ (function () {
  48702. function SoundTrack(scene, options) {
  48703. this.id = -1;
  48704. this._isMainTrack = false;
  48705. this._isInitialized = false;
  48706. this._scene = scene;
  48707. this.soundCollection = new Array();
  48708. this._options = options;
  48709. if (!this._isMainTrack) {
  48710. this._scene.soundTracks.push(this);
  48711. this.id = this._scene.soundTracks.length - 1;
  48712. }
  48713. }
  48714. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  48715. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48716. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  48717. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  48718. if (this._options) {
  48719. if (this._options.volume) {
  48720. this._outputAudioNode.gain.value = this._options.volume;
  48721. }
  48722. if (this._options.mainTrack) {
  48723. this._isMainTrack = this._options.mainTrack;
  48724. }
  48725. }
  48726. this._isInitialized = true;
  48727. }
  48728. };
  48729. SoundTrack.prototype.dispose = function () {
  48730. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48731. if (this._connectedAnalyser) {
  48732. this._connectedAnalyser.stopDebugCanvas();
  48733. }
  48734. while (this.soundCollection.length) {
  48735. this.soundCollection[0].dispose();
  48736. }
  48737. if (this._outputAudioNode) {
  48738. this._outputAudioNode.disconnect();
  48739. }
  48740. this._outputAudioNode = null;
  48741. }
  48742. };
  48743. SoundTrack.prototype.AddSound = function (sound) {
  48744. if (!this._isInitialized) {
  48745. this._initializeSoundTrackAudioGraph();
  48746. }
  48747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48748. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  48749. }
  48750. if (sound.soundTrackId) {
  48751. if (sound.soundTrackId === -1) {
  48752. this._scene.mainSoundTrack.RemoveSound(sound);
  48753. }
  48754. else {
  48755. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  48756. }
  48757. }
  48758. this.soundCollection.push(sound);
  48759. sound.soundTrackId = this.id;
  48760. };
  48761. SoundTrack.prototype.RemoveSound = function (sound) {
  48762. var index = this.soundCollection.indexOf(sound);
  48763. if (index !== -1) {
  48764. this.soundCollection.splice(index, 1);
  48765. }
  48766. };
  48767. SoundTrack.prototype.setVolume = function (newVolume) {
  48768. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48769. this._outputAudioNode.gain.value = newVolume;
  48770. }
  48771. };
  48772. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  48773. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48774. for (var i = 0; i < this.soundCollection.length; i++) {
  48775. this.soundCollection[i].switchPanningModelToHRTF();
  48776. }
  48777. }
  48778. };
  48779. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  48780. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48781. for (var i = 0; i < this.soundCollection.length; i++) {
  48782. this.soundCollection[i].switchPanningModelToEqualPower();
  48783. }
  48784. }
  48785. };
  48786. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  48787. if (this._connectedAnalyser) {
  48788. this._connectedAnalyser.stopDebugCanvas();
  48789. }
  48790. this._connectedAnalyser = analyser;
  48791. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  48792. this._outputAudioNode.disconnect();
  48793. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  48794. }
  48795. };
  48796. return SoundTrack;
  48797. }());
  48798. BABYLON.SoundTrack = SoundTrack;
  48799. })(BABYLON || (BABYLON = {}));
  48800. //# sourceMappingURL=babylon.soundtrack.js.map
  48801. var BABYLON;
  48802. (function (BABYLON) {
  48803. var Analyser = /** @class */ (function () {
  48804. function Analyser(scene) {
  48805. this.SMOOTHING = 0.75;
  48806. this.FFT_SIZE = 512;
  48807. this.BARGRAPHAMPLITUDE = 256;
  48808. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  48809. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  48810. this._scene = scene;
  48811. this._audioEngine = BABYLON.Engine.audioEngine;
  48812. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  48813. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  48814. this._webAudioAnalyser.minDecibels = -140;
  48815. this._webAudioAnalyser.maxDecibels = 0;
  48816. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48817. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  48818. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  48819. }
  48820. }
  48821. Analyser.prototype.getFrequencyBinCount = function () {
  48822. if (this._audioEngine.canUseWebAudio) {
  48823. return this._webAudioAnalyser.frequencyBinCount;
  48824. }
  48825. else {
  48826. return 0;
  48827. }
  48828. };
  48829. Analyser.prototype.getByteFrequencyData = function () {
  48830. if (this._audioEngine.canUseWebAudio) {
  48831. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48832. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48833. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  48834. }
  48835. return this._byteFreqs;
  48836. };
  48837. Analyser.prototype.getByteTimeDomainData = function () {
  48838. if (this._audioEngine.canUseWebAudio) {
  48839. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48840. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48841. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  48842. }
  48843. return this._byteTime;
  48844. };
  48845. Analyser.prototype.getFloatFrequencyData = function () {
  48846. if (this._audioEngine.canUseWebAudio) {
  48847. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  48848. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  48849. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  48850. }
  48851. return this._floatFreqs;
  48852. };
  48853. Analyser.prototype.drawDebugCanvas = function () {
  48854. var _this = this;
  48855. if (this._audioEngine.canUseWebAudio) {
  48856. if (!this._debugCanvas) {
  48857. this._debugCanvas = document.createElement("canvas");
  48858. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  48859. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  48860. this._debugCanvas.style.position = "absolute";
  48861. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  48862. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  48863. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  48864. document.body.appendChild(this._debugCanvas);
  48865. this._registerFunc = function () {
  48866. _this.drawDebugCanvas();
  48867. };
  48868. this._scene.registerBeforeRender(this._registerFunc);
  48869. }
  48870. if (this._registerFunc && this._debugCanvasContext) {
  48871. var workingArray = this.getByteFrequencyData();
  48872. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  48873. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  48874. // Draw the frequency domain chart.
  48875. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  48876. var value = workingArray[i];
  48877. var percent = value / this.BARGRAPHAMPLITUDE;
  48878. var height = this.DEBUGCANVASSIZE.height * percent;
  48879. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  48880. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  48881. var hue = i / this.getFrequencyBinCount() * 360;
  48882. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  48883. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  48884. }
  48885. }
  48886. }
  48887. };
  48888. Analyser.prototype.stopDebugCanvas = function () {
  48889. if (this._debugCanvas) {
  48890. if (this._registerFunc) {
  48891. this._scene.unregisterBeforeRender(this._registerFunc);
  48892. this._registerFunc = null;
  48893. }
  48894. document.body.removeChild(this._debugCanvas);
  48895. this._debugCanvas = null;
  48896. this._debugCanvasContext = null;
  48897. }
  48898. };
  48899. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  48900. if (this._audioEngine.canUseWebAudio) {
  48901. inputAudioNode.connect(this._webAudioAnalyser);
  48902. this._webAudioAnalyser.connect(outputAudioNode);
  48903. }
  48904. };
  48905. Analyser.prototype.dispose = function () {
  48906. if (this._audioEngine.canUseWebAudio) {
  48907. this._webAudioAnalyser.disconnect();
  48908. }
  48909. };
  48910. return Analyser;
  48911. }());
  48912. BABYLON.Analyser = Analyser;
  48913. })(BABYLON || (BABYLON = {}));
  48914. //# sourceMappingURL=babylon.analyser.js.map
  48915. var BABYLON;
  48916. (function (BABYLON) {
  48917. var CubeTexture = /** @class */ (function (_super) {
  48918. __extends(CubeTexture, _super);
  48919. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  48920. if (extensions === void 0) { extensions = null; }
  48921. if (noMipmap === void 0) { noMipmap = false; }
  48922. if (files === void 0) { files = null; }
  48923. if (onLoad === void 0) { onLoad = null; }
  48924. if (onError === void 0) { onError = null; }
  48925. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48926. if (prefiltered === void 0) { prefiltered = false; }
  48927. if (forcedExtension === void 0) { forcedExtension = null; }
  48928. var _this = _super.call(this, scene) || this;
  48929. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  48930. _this.name = rootUrl;
  48931. _this.url = rootUrl;
  48932. _this._noMipmap = noMipmap;
  48933. _this.hasAlpha = false;
  48934. _this._format = format;
  48935. _this._prefiltered = prefiltered;
  48936. _this.isCube = true;
  48937. _this._textureMatrix = BABYLON.Matrix.Identity();
  48938. if (prefiltered) {
  48939. _this.gammaSpace = false;
  48940. }
  48941. if (!rootUrl && !files) {
  48942. return _this;
  48943. }
  48944. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  48945. if (!files) {
  48946. if (!extensions) {
  48947. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  48948. }
  48949. files = [];
  48950. for (var index = 0; index < extensions.length; index++) {
  48951. files.push(rootUrl + extensions[index]);
  48952. }
  48953. _this._extensions = extensions;
  48954. }
  48955. _this._files = files;
  48956. if (!_this._texture) {
  48957. if (!scene.useDelayedTextureLoading) {
  48958. if (prefiltered) {
  48959. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  48960. }
  48961. else {
  48962. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  48963. }
  48964. }
  48965. else {
  48966. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  48967. }
  48968. }
  48969. else if (onLoad) {
  48970. if (_this._texture.isReady) {
  48971. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  48972. }
  48973. else {
  48974. _this._texture.onLoadedObservable.add(onLoad);
  48975. }
  48976. }
  48977. return _this;
  48978. }
  48979. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  48980. return new CubeTexture("", scene, null, noMipmap, files);
  48981. };
  48982. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  48983. if (forcedExtension === void 0) { forcedExtension = null; }
  48984. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  48985. };
  48986. // Methods
  48987. CubeTexture.prototype.delayLoad = function () {
  48988. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  48989. return;
  48990. }
  48991. var scene = this.getScene();
  48992. if (!scene) {
  48993. return;
  48994. }
  48995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  48996. this._texture = this._getFromCache(this.url, this._noMipmap);
  48997. if (!this._texture) {
  48998. if (this._prefiltered) {
  48999. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49000. }
  49001. else {
  49002. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49003. }
  49004. }
  49005. };
  49006. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49007. return this._textureMatrix;
  49008. };
  49009. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49010. this._textureMatrix = value;
  49011. };
  49012. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49013. var texture = BABYLON.SerializationHelper.Parse(function () {
  49014. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49015. }, parsedTexture, scene);
  49016. // Animations
  49017. if (parsedTexture.animations) {
  49018. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49019. var parsedAnimation = parsedTexture.animations[animationIndex];
  49020. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49021. }
  49022. }
  49023. return texture;
  49024. };
  49025. CubeTexture.prototype.clone = function () {
  49026. var _this = this;
  49027. return BABYLON.SerializationHelper.Clone(function () {
  49028. var scene = _this.getScene();
  49029. if (!scene) {
  49030. return _this;
  49031. }
  49032. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49033. }, this);
  49034. };
  49035. return CubeTexture;
  49036. }(BABYLON.BaseTexture));
  49037. BABYLON.CubeTexture = CubeTexture;
  49038. })(BABYLON || (BABYLON = {}));
  49039. //# sourceMappingURL=babylon.cubeTexture.js.map
  49040. var BABYLON;
  49041. (function (BABYLON) {
  49042. var RenderTargetTexture = /** @class */ (function (_super) {
  49043. __extends(RenderTargetTexture, _super);
  49044. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49045. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49046. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49047. if (isCube === void 0) { isCube = false; }
  49048. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49049. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49050. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49051. if (isMulti === void 0) { isMulti = false; }
  49052. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49053. _this.isCube = isCube;
  49054. /**
  49055. * Use this list to define the list of mesh you want to render.
  49056. */
  49057. _this.renderList = new Array();
  49058. _this.renderParticles = true;
  49059. _this.renderSprites = false;
  49060. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49061. _this.ignoreCameraViewport = false;
  49062. // Events
  49063. /**
  49064. * An event triggered when the texture is unbind.
  49065. * @type {BABYLON.Observable}
  49066. */
  49067. _this.onBeforeBindObservable = new BABYLON.Observable();
  49068. /**
  49069. * An event triggered when the texture is unbind.
  49070. * @type {BABYLON.Observable}
  49071. */
  49072. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49073. /**
  49074. * An event triggered before rendering the texture
  49075. * @type {BABYLON.Observable}
  49076. */
  49077. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49078. /**
  49079. * An event triggered after rendering the texture
  49080. * @type {BABYLON.Observable}
  49081. */
  49082. _this.onAfterRenderObservable = new BABYLON.Observable();
  49083. /**
  49084. * An event triggered after the texture clear
  49085. * @type {BABYLON.Observable}
  49086. */
  49087. _this.onClearObservable = new BABYLON.Observable();
  49088. _this._currentRefreshId = -1;
  49089. _this._refreshRate = 1;
  49090. _this._samples = 1;
  49091. scene = _this.getScene();
  49092. if (!scene) {
  49093. return _this;
  49094. }
  49095. _this.name = name;
  49096. _this.isRenderTarget = true;
  49097. _this._size = size;
  49098. _this._generateMipMaps = generateMipMaps ? true : false;
  49099. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49100. // Rendering groups
  49101. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49102. if (isMulti) {
  49103. return _this;
  49104. }
  49105. _this._renderTargetOptions = {
  49106. generateMipMaps: generateMipMaps,
  49107. type: type,
  49108. samplingMode: samplingMode,
  49109. generateDepthBuffer: generateDepthBuffer,
  49110. generateStencilBuffer: generateStencilBuffer
  49111. };
  49112. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49113. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49114. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49115. }
  49116. if (isCube) {
  49117. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  49118. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49119. _this._textureMatrix = BABYLON.Matrix.Identity();
  49120. }
  49121. else {
  49122. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  49123. }
  49124. return _this;
  49125. }
  49126. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49127. get: function () {
  49128. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49129. },
  49130. enumerable: true,
  49131. configurable: true
  49132. });
  49133. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49134. get: function () {
  49135. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49136. },
  49137. enumerable: true,
  49138. configurable: true
  49139. });
  49140. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49141. get: function () {
  49142. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49143. },
  49144. enumerable: true,
  49145. configurable: true
  49146. });
  49147. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49148. set: function (callback) {
  49149. if (this._onAfterUnbindObserver) {
  49150. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49151. }
  49152. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49153. },
  49154. enumerable: true,
  49155. configurable: true
  49156. });
  49157. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49158. set: function (callback) {
  49159. if (this._onBeforeRenderObserver) {
  49160. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49161. }
  49162. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49163. },
  49164. enumerable: true,
  49165. configurable: true
  49166. });
  49167. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49168. set: function (callback) {
  49169. if (this._onAfterRenderObserver) {
  49170. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49171. }
  49172. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49173. },
  49174. enumerable: true,
  49175. configurable: true
  49176. });
  49177. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49178. set: function (callback) {
  49179. if (this._onClearObserver) {
  49180. this.onClearObservable.remove(this._onClearObserver);
  49181. }
  49182. this._onClearObserver = this.onClearObservable.add(callback);
  49183. },
  49184. enumerable: true,
  49185. configurable: true
  49186. });
  49187. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49188. get: function () {
  49189. return this._renderTargetOptions;
  49190. },
  49191. enumerable: true,
  49192. configurable: true
  49193. });
  49194. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49195. get: function () {
  49196. return this._samples;
  49197. },
  49198. set: function (value) {
  49199. if (this._samples === value) {
  49200. return;
  49201. }
  49202. var scene = this.getScene();
  49203. if (!scene) {
  49204. return;
  49205. }
  49206. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49207. },
  49208. enumerable: true,
  49209. configurable: true
  49210. });
  49211. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49212. this._currentRefreshId = -1;
  49213. };
  49214. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49215. get: function () {
  49216. return this._refreshRate;
  49217. },
  49218. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49219. set: function (value) {
  49220. this._refreshRate = value;
  49221. this.resetRefreshCounter();
  49222. },
  49223. enumerable: true,
  49224. configurable: true
  49225. });
  49226. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49227. if (!this._postProcessManager) {
  49228. var scene = this.getScene();
  49229. if (!scene) {
  49230. return;
  49231. }
  49232. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49233. this._postProcesses = new Array();
  49234. }
  49235. this._postProcesses.push(postProcess);
  49236. this._postProcesses[0].autoClear = false;
  49237. };
  49238. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49239. if (!this._postProcesses) {
  49240. return;
  49241. }
  49242. if (dispose) {
  49243. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49244. var postProcess = _a[_i];
  49245. postProcess.dispose();
  49246. }
  49247. }
  49248. this._postProcesses = [];
  49249. };
  49250. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49251. if (!this._postProcesses) {
  49252. return;
  49253. }
  49254. var index = this._postProcesses.indexOf(postProcess);
  49255. if (index === -1) {
  49256. return;
  49257. }
  49258. this._postProcesses.splice(index, 1);
  49259. if (this._postProcesses.length > 0) {
  49260. this._postProcesses[0].autoClear = false;
  49261. }
  49262. };
  49263. RenderTargetTexture.prototype._shouldRender = function () {
  49264. if (this._currentRefreshId === -1) {
  49265. this._currentRefreshId = 1;
  49266. return true;
  49267. }
  49268. if (this.refreshRate === this._currentRefreshId) {
  49269. this._currentRefreshId = 1;
  49270. return true;
  49271. }
  49272. this._currentRefreshId++;
  49273. return false;
  49274. };
  49275. RenderTargetTexture.prototype.getRenderSize = function () {
  49276. return this._size;
  49277. };
  49278. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49279. get: function () {
  49280. return true;
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. RenderTargetTexture.prototype.scale = function (ratio) {
  49286. var newSize = this._size * ratio;
  49287. this.resize(newSize);
  49288. };
  49289. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49290. if (this.isCube) {
  49291. return this._textureMatrix;
  49292. }
  49293. return _super.prototype.getReflectionTextureMatrix.call(this);
  49294. };
  49295. RenderTargetTexture.prototype.resize = function (size) {
  49296. this.releaseInternalTexture();
  49297. var scene = this.getScene();
  49298. if (!scene) {
  49299. return;
  49300. }
  49301. if (this.isCube) {
  49302. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  49303. }
  49304. else {
  49305. this._texture = scene.getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  49306. }
  49307. this._size = size;
  49308. };
  49309. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49310. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49311. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49312. var scene = this.getScene();
  49313. if (!scene) {
  49314. return;
  49315. }
  49316. var engine = scene.getEngine();
  49317. if (this.useCameraPostProcesses !== undefined) {
  49318. useCameraPostProcess = this.useCameraPostProcesses;
  49319. }
  49320. if (this._waitingRenderList) {
  49321. this.renderList = [];
  49322. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49323. var id = this._waitingRenderList[index];
  49324. var mesh_1 = scene.getMeshByID(id);
  49325. if (mesh_1) {
  49326. this.renderList.push(mesh_1);
  49327. }
  49328. }
  49329. delete this._waitingRenderList;
  49330. }
  49331. // Is predicate defined?
  49332. if (this.renderListPredicate) {
  49333. if (this.renderList) {
  49334. this.renderList.splice(0); // Clear previous renderList
  49335. }
  49336. else {
  49337. this.renderList = [];
  49338. }
  49339. var scene = this.getScene();
  49340. if (!scene) {
  49341. return;
  49342. }
  49343. var sceneMeshes = scene.meshes;
  49344. for (var index = 0; index < sceneMeshes.length; index++) {
  49345. var mesh = sceneMeshes[index];
  49346. if (this.renderListPredicate(mesh)) {
  49347. this.renderList.push(mesh);
  49348. }
  49349. }
  49350. }
  49351. this.onBeforeBindObservable.notifyObservers(this);
  49352. // Set custom projection.
  49353. // Needs to be before binding to prevent changing the aspect ratio.
  49354. var camera;
  49355. if (this.activeCamera) {
  49356. camera = this.activeCamera;
  49357. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  49358. if (this.activeCamera !== scene.activeCamera) {
  49359. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49360. }
  49361. }
  49362. else {
  49363. camera = scene.activeCamera;
  49364. if (camera) {
  49365. engine.setViewport(camera.viewport, this._size, this._size);
  49366. }
  49367. }
  49368. // Prepare renderingManager
  49369. this._renderingManager.reset();
  49370. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49371. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49372. var sceneRenderId = scene.getRenderId();
  49373. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49374. var mesh = currentRenderList[meshIndex];
  49375. if (mesh) {
  49376. if (!mesh.isReady()) {
  49377. // Reset _currentRefreshId
  49378. this.resetRefreshCounter();
  49379. continue;
  49380. }
  49381. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49382. var isMasked = void 0;
  49383. if (!this.renderList && camera) {
  49384. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49385. }
  49386. else {
  49387. isMasked = false;
  49388. }
  49389. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49390. mesh._activate(sceneRenderId);
  49391. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49392. var subMesh = mesh.subMeshes[subIndex];
  49393. scene._activeIndices.addCount(subMesh.indexCount, false);
  49394. this._renderingManager.dispatch(subMesh);
  49395. }
  49396. }
  49397. }
  49398. }
  49399. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49400. var particleSystem = scene.particleSystems[particleIndex];
  49401. var emitter = particleSystem.emitter;
  49402. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49403. continue;
  49404. }
  49405. if (currentRenderList.indexOf(emitter) >= 0) {
  49406. this._renderingManager.dispatchParticles(particleSystem);
  49407. }
  49408. }
  49409. if (this.isCube) {
  49410. for (var face = 0; face < 6; face++) {
  49411. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49412. scene.incrementRenderId();
  49413. scene.resetCachedMaterial();
  49414. }
  49415. }
  49416. else {
  49417. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49418. }
  49419. this.onAfterUnbindObservable.notifyObservers(this);
  49420. if (scene.activeCamera) {
  49421. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49422. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49423. }
  49424. engine.setViewport(scene.activeCamera.viewport);
  49425. }
  49426. scene.resetCachedMaterial();
  49427. };
  49428. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49429. var _this = this;
  49430. var scene = this.getScene();
  49431. if (!scene) {
  49432. return;
  49433. }
  49434. var engine = scene.getEngine();
  49435. if (!this._texture) {
  49436. return;
  49437. }
  49438. // Bind
  49439. if (this._postProcessManager) {
  49440. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49441. }
  49442. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49443. if (this._texture) {
  49444. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49445. }
  49446. }
  49447. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49448. // Clear
  49449. if (this.onClearObservable.hasObservers()) {
  49450. this.onClearObservable.notifyObservers(engine);
  49451. }
  49452. else {
  49453. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49454. }
  49455. if (!this._doNotChangeAspectRatio) {
  49456. scene.updateTransformMatrix(true);
  49457. }
  49458. // Render
  49459. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49460. if (this._postProcessManager) {
  49461. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49462. }
  49463. else if (useCameraPostProcess) {
  49464. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49465. }
  49466. if (!this._doNotChangeAspectRatio) {
  49467. scene.updateTransformMatrix(true);
  49468. }
  49469. // Dump ?
  49470. if (dumpForDebug) {
  49471. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  49472. }
  49473. // Unbind
  49474. if (!this.isCube || faceIndex === 5) {
  49475. if (this.isCube) {
  49476. if (faceIndex === 5) {
  49477. engine.generateMipMapsForCubemap(this._texture);
  49478. }
  49479. }
  49480. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49481. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49482. });
  49483. }
  49484. else {
  49485. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49486. }
  49487. };
  49488. /**
  49489. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49490. * This allowed control for front to back rendering or reversly depending of the special needs.
  49491. *
  49492. * @param renderingGroupId The rendering group id corresponding to its index
  49493. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49494. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49495. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49496. */
  49497. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49498. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49499. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49500. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49501. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49502. };
  49503. /**
  49504. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49505. *
  49506. * @param renderingGroupId The rendering group id corresponding to its index
  49507. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49508. */
  49509. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49510. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49511. };
  49512. RenderTargetTexture.prototype.clone = function () {
  49513. var textureSize = this.getSize();
  49514. 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);
  49515. // Base texture
  49516. newTexture.hasAlpha = this.hasAlpha;
  49517. newTexture.level = this.level;
  49518. // RenderTarget Texture
  49519. newTexture.coordinatesMode = this.coordinatesMode;
  49520. if (this.renderList) {
  49521. newTexture.renderList = this.renderList.slice(0);
  49522. }
  49523. return newTexture;
  49524. };
  49525. RenderTargetTexture.prototype.serialize = function () {
  49526. if (!this.name) {
  49527. return null;
  49528. }
  49529. var serializationObject = _super.prototype.serialize.call(this);
  49530. serializationObject.renderTargetSize = this.getRenderSize();
  49531. serializationObject.renderList = [];
  49532. if (this.renderList) {
  49533. for (var index = 0; index < this.renderList.length; index++) {
  49534. serializationObject.renderList.push(this.renderList[index].id);
  49535. }
  49536. }
  49537. return serializationObject;
  49538. };
  49539. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49540. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49541. var objBuffer = this.getInternalTexture();
  49542. var scene = this.getScene();
  49543. if (objBuffer && scene) {
  49544. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49545. }
  49546. };
  49547. RenderTargetTexture.prototype.dispose = function () {
  49548. if (this._postProcessManager) {
  49549. this._postProcessManager.dispose();
  49550. this._postProcessManager = null;
  49551. }
  49552. this.clearPostProcesses(true);
  49553. this.renderList = null;
  49554. // Remove from custom render targets
  49555. var scene = this.getScene();
  49556. if (!scene) {
  49557. return;
  49558. }
  49559. var index = scene.customRenderTargets.indexOf(this);
  49560. if (index >= 0) {
  49561. scene.customRenderTargets.splice(index, 1);
  49562. }
  49563. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49564. var camera = _a[_i];
  49565. index = camera.customRenderTargets.indexOf(this);
  49566. if (index >= 0) {
  49567. camera.customRenderTargets.splice(index, 1);
  49568. }
  49569. }
  49570. _super.prototype.dispose.call(this);
  49571. };
  49572. RenderTargetTexture.prototype._rebuild = function () {
  49573. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49574. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49575. }
  49576. if (this._postProcessManager) {
  49577. this._postProcessManager._rebuild();
  49578. }
  49579. };
  49580. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49581. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49582. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49583. return RenderTargetTexture;
  49584. }(BABYLON.Texture));
  49585. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49586. })(BABYLON || (BABYLON = {}));
  49587. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49588. var BABYLON;
  49589. (function (BABYLON) {
  49590. ;
  49591. var MultiRenderTarget = /** @class */ (function (_super) {
  49592. __extends(MultiRenderTarget, _super);
  49593. function MultiRenderTarget(name, size, count, scene, options) {
  49594. var _this = this;
  49595. options = options || {};
  49596. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  49597. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  49598. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  49599. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  49600. _this._engine = scene.getEngine();
  49601. if (!_this.isSupported) {
  49602. _this.dispose();
  49603. return;
  49604. }
  49605. var types = [];
  49606. var samplingModes = [];
  49607. for (var i = 0; i < count; i++) {
  49608. if (options.types && options.types[i]) {
  49609. types.push(options.types[i]);
  49610. }
  49611. else {
  49612. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  49613. }
  49614. if (options.samplingModes && options.samplingModes[i]) {
  49615. samplingModes.push(options.samplingModes[i]);
  49616. }
  49617. else {
  49618. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49619. }
  49620. }
  49621. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  49622. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  49623. _this._count = count;
  49624. _this._size = size;
  49625. _this._multiRenderTargetOptions = {
  49626. samplingModes: samplingModes,
  49627. generateMipMaps: generateMipMaps,
  49628. generateDepthBuffer: generateDepthBuffer,
  49629. generateStencilBuffer: generateStencilBuffer,
  49630. generateDepthTexture: generateDepthTexture,
  49631. types: types,
  49632. textureCount: count
  49633. };
  49634. _this._createInternalTextures();
  49635. _this._createTextures();
  49636. return _this;
  49637. }
  49638. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  49639. get: function () {
  49640. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  49641. },
  49642. enumerable: true,
  49643. configurable: true
  49644. });
  49645. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  49646. get: function () {
  49647. return this._textures;
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  49653. get: function () {
  49654. return this._textures[this._textures.length - 1];
  49655. },
  49656. enumerable: true,
  49657. configurable: true
  49658. });
  49659. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  49660. set: function (wrap) {
  49661. if (this._textures) {
  49662. for (var i = 0; i < this._textures.length; i++) {
  49663. this._textures[i].wrapU = wrap;
  49664. }
  49665. }
  49666. },
  49667. enumerable: true,
  49668. configurable: true
  49669. });
  49670. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  49671. set: function (wrap) {
  49672. if (this._textures) {
  49673. for (var i = 0; i < this._textures.length; i++) {
  49674. this._textures[i].wrapV = wrap;
  49675. }
  49676. }
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. MultiRenderTarget.prototype._rebuild = function () {
  49682. this.releaseInternalTextures();
  49683. this._createInternalTextures();
  49684. for (var i = 0; i < this._internalTextures.length; i++) {
  49685. var texture = this._textures[i];
  49686. texture._texture = this._internalTextures[i];
  49687. }
  49688. // Keeps references to frame buffer and stencil/depth buffer
  49689. this._texture = this._internalTextures[0];
  49690. };
  49691. MultiRenderTarget.prototype._createInternalTextures = function () {
  49692. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  49693. };
  49694. MultiRenderTarget.prototype._createTextures = function () {
  49695. this._textures = [];
  49696. for (var i = 0; i < this._internalTextures.length; i++) {
  49697. var texture = new BABYLON.Texture(null, this.getScene());
  49698. texture._texture = this._internalTextures[i];
  49699. this._textures.push(texture);
  49700. }
  49701. // Keeps references to frame buffer and stencil/depth buffer
  49702. this._texture = this._internalTextures[0];
  49703. };
  49704. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  49705. get: function () {
  49706. return this._samples;
  49707. },
  49708. set: function (value) {
  49709. if (this._samples === value) {
  49710. return;
  49711. }
  49712. for (var i = 0; i < this._internalTextures.length; i++) {
  49713. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  49714. }
  49715. },
  49716. enumerable: true,
  49717. configurable: true
  49718. });
  49719. MultiRenderTarget.prototype.resize = function (size) {
  49720. this.releaseInternalTextures();
  49721. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  49722. this._createInternalTextures();
  49723. };
  49724. MultiRenderTarget.prototype.dispose = function () {
  49725. this.releaseInternalTextures();
  49726. _super.prototype.dispose.call(this);
  49727. };
  49728. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  49729. if (!this._internalTextures) {
  49730. return;
  49731. }
  49732. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  49733. if (this._internalTextures[i] !== undefined) {
  49734. this._internalTextures[i].dispose();
  49735. this._internalTextures.splice(i, 1);
  49736. }
  49737. }
  49738. };
  49739. return MultiRenderTarget;
  49740. }(BABYLON.RenderTargetTexture));
  49741. BABYLON.MultiRenderTarget = MultiRenderTarget;
  49742. })(BABYLON || (BABYLON = {}));
  49743. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  49744. var BABYLON;
  49745. (function (BABYLON) {
  49746. var MirrorTexture = /** @class */ (function (_super) {
  49747. __extends(MirrorTexture, _super);
  49748. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  49749. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49751. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49752. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  49753. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  49754. _this._transformMatrix = BABYLON.Matrix.Zero();
  49755. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  49756. _this._blurKernelX = 0;
  49757. _this._blurKernelY = 0;
  49758. _this._blurRatio = 1.0;
  49759. _this.ignoreCameraViewport = true;
  49760. _this.onBeforeRenderObservable.add(function () {
  49761. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  49762. _this._savedViewMatrix = scene.getViewMatrix();
  49763. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  49764. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  49765. scene.clipPlane = _this.mirrorPlane;
  49766. scene.getEngine().cullBackFaces = false;
  49767. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  49768. });
  49769. _this.onAfterRenderObservable.add(function () {
  49770. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  49771. scene.getEngine().cullBackFaces = true;
  49772. scene._mirroredCameraPosition = null;
  49773. delete scene.clipPlane;
  49774. });
  49775. return _this;
  49776. }
  49777. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  49778. get: function () {
  49779. return this._blurRatio;
  49780. },
  49781. set: function (value) {
  49782. if (this._blurRatio === value) {
  49783. return;
  49784. }
  49785. this._blurRatio = value;
  49786. this._preparePostProcesses();
  49787. },
  49788. enumerable: true,
  49789. configurable: true
  49790. });
  49791. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  49792. set: function (value) {
  49793. this.blurKernelX = value;
  49794. this.blurKernelY = value;
  49795. },
  49796. enumerable: true,
  49797. configurable: true
  49798. });
  49799. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  49800. get: function () {
  49801. return this._blurKernelX;
  49802. },
  49803. set: function (value) {
  49804. if (this._blurKernelX === value) {
  49805. return;
  49806. }
  49807. this._blurKernelX = value;
  49808. this._preparePostProcesses();
  49809. },
  49810. enumerable: true,
  49811. configurable: true
  49812. });
  49813. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  49814. get: function () {
  49815. return this._blurKernelY;
  49816. },
  49817. set: function (value) {
  49818. if (this._blurKernelY === value) {
  49819. return;
  49820. }
  49821. this._blurKernelY = value;
  49822. this._preparePostProcesses();
  49823. },
  49824. enumerable: true,
  49825. configurable: true
  49826. });
  49827. MirrorTexture.prototype._preparePostProcesses = function () {
  49828. this.clearPostProcesses(true);
  49829. if (this._blurKernelX && this._blurKernelY) {
  49830. var engine = this.getScene().getEngine();
  49831. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49832. 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);
  49833. this._blurX.autoClear = false;
  49834. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  49835. this._blurX.outputTexture = this._texture;
  49836. }
  49837. else {
  49838. this._blurX.alwaysForcePOT = true;
  49839. }
  49840. 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);
  49841. this._blurY.autoClear = false;
  49842. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  49843. this.addPostProcess(this._blurX);
  49844. this.addPostProcess(this._blurY);
  49845. }
  49846. };
  49847. MirrorTexture.prototype.clone = function () {
  49848. var scene = this.getScene();
  49849. if (!scene) {
  49850. return this;
  49851. }
  49852. var textureSize = this.getSize();
  49853. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  49854. // Base texture
  49855. newTexture.hasAlpha = this.hasAlpha;
  49856. newTexture.level = this.level;
  49857. // Mirror Texture
  49858. newTexture.mirrorPlane = this.mirrorPlane.clone();
  49859. if (this.renderList) {
  49860. newTexture.renderList = this.renderList.slice(0);
  49861. }
  49862. return newTexture;
  49863. };
  49864. MirrorTexture.prototype.serialize = function () {
  49865. if (!this.name) {
  49866. return null;
  49867. }
  49868. var serializationObject = _super.prototype.serialize.call(this);
  49869. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  49870. return serializationObject;
  49871. };
  49872. return MirrorTexture;
  49873. }(BABYLON.RenderTargetTexture));
  49874. BABYLON.MirrorTexture = MirrorTexture;
  49875. })(BABYLON || (BABYLON = {}));
  49876. //# sourceMappingURL=babylon.mirrorTexture.js.map
  49877. var BABYLON;
  49878. (function (BABYLON) {
  49879. /**
  49880. * Creates a refraction texture used by refraction channel of the standard material.
  49881. * @param name the texture name
  49882. * @param size size of the underlying texture
  49883. * @param scene root scene
  49884. */
  49885. var RefractionTexture = /** @class */ (function (_super) {
  49886. __extends(RefractionTexture, _super);
  49887. function RefractionTexture(name, size, scene, generateMipMaps) {
  49888. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  49889. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  49890. _this.depth = 2.0;
  49891. _this.onBeforeRenderObservable.add(function () {
  49892. scene.clipPlane = _this.refractionPlane;
  49893. });
  49894. _this.onAfterRenderObservable.add(function () {
  49895. delete scene.clipPlane;
  49896. });
  49897. return _this;
  49898. }
  49899. RefractionTexture.prototype.clone = function () {
  49900. var scene = this.getScene();
  49901. if (!scene) {
  49902. return this;
  49903. }
  49904. var textureSize = this.getSize();
  49905. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  49906. // Base texture
  49907. newTexture.hasAlpha = this.hasAlpha;
  49908. newTexture.level = this.level;
  49909. // Refraction Texture
  49910. newTexture.refractionPlane = this.refractionPlane.clone();
  49911. if (this.renderList) {
  49912. newTexture.renderList = this.renderList.slice(0);
  49913. }
  49914. newTexture.depth = this.depth;
  49915. return newTexture;
  49916. };
  49917. RefractionTexture.prototype.serialize = function () {
  49918. if (!this.name) {
  49919. return null;
  49920. }
  49921. var serializationObject = _super.prototype.serialize.call(this);
  49922. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  49923. serializationObject.depth = this.depth;
  49924. return serializationObject;
  49925. };
  49926. return RefractionTexture;
  49927. }(BABYLON.RenderTargetTexture));
  49928. BABYLON.RefractionTexture = RefractionTexture;
  49929. })(BABYLON || (BABYLON = {}));
  49930. //# sourceMappingURL=babylon.refractionTexture.js.map
  49931. var BABYLON;
  49932. (function (BABYLON) {
  49933. var DynamicTexture = /** @class */ (function (_super) {
  49934. __extends(DynamicTexture, _super);
  49935. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  49936. if (scene === void 0) { scene = null; }
  49937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49938. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49939. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  49940. _this.name = name;
  49941. _this._engine = _this.getScene().getEngine();
  49942. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49943. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49944. _this._generateMipMaps = generateMipMaps;
  49945. if (options.getContext) {
  49946. _this._canvas = options;
  49947. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49948. }
  49949. else {
  49950. _this._canvas = document.createElement("canvas");
  49951. if (options.width) {
  49952. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  49953. }
  49954. else {
  49955. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  49956. }
  49957. }
  49958. var textureSize = _this.getSize();
  49959. _this._canvas.width = textureSize.width;
  49960. _this._canvas.height = textureSize.height;
  49961. _this._context = _this._canvas.getContext("2d");
  49962. return _this;
  49963. }
  49964. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  49965. get: function () {
  49966. return true;
  49967. },
  49968. enumerable: true,
  49969. configurable: true
  49970. });
  49971. DynamicTexture.prototype._recreate = function (textureSize) {
  49972. this._canvas.width = textureSize.width;
  49973. this._canvas.height = textureSize.height;
  49974. this.releaseInternalTexture();
  49975. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  49976. };
  49977. DynamicTexture.prototype.scale = function (ratio) {
  49978. var textureSize = this.getSize();
  49979. textureSize.width *= ratio;
  49980. textureSize.height *= ratio;
  49981. this._recreate(textureSize);
  49982. };
  49983. DynamicTexture.prototype.scaleTo = function (width, height) {
  49984. var textureSize = this.getSize();
  49985. textureSize.width = width;
  49986. textureSize.height = height;
  49987. this._recreate(textureSize);
  49988. };
  49989. DynamicTexture.prototype.getContext = function () {
  49990. return this._context;
  49991. };
  49992. DynamicTexture.prototype.clear = function () {
  49993. var size = this.getSize();
  49994. this._context.fillRect(0, 0, size.width, size.height);
  49995. };
  49996. DynamicTexture.prototype.update = function (invertY) {
  49997. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  49998. };
  49999. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50000. if (update === void 0) { update = true; }
  50001. var size = this.getSize();
  50002. if (clearColor) {
  50003. this._context.fillStyle = clearColor;
  50004. this._context.fillRect(0, 0, size.width, size.height);
  50005. }
  50006. this._context.font = font;
  50007. if (x === null || x === undefined) {
  50008. var textSize = this._context.measureText(text);
  50009. x = (size.width - textSize.width) / 2;
  50010. }
  50011. if (y === null || y === undefined) {
  50012. var fontSize = parseInt((font.replace(/\D/g, '')));
  50013. ;
  50014. y = (size.height / 2) + (fontSize / 3.65);
  50015. }
  50016. this._context.fillStyle = color;
  50017. this._context.fillText(text, x, y);
  50018. if (update) {
  50019. this.update(invertY);
  50020. }
  50021. };
  50022. DynamicTexture.prototype.clone = function () {
  50023. var scene = this.getScene();
  50024. if (!scene) {
  50025. return this;
  50026. }
  50027. var textureSize = this.getSize();
  50028. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50029. // Base texture
  50030. newTexture.hasAlpha = this.hasAlpha;
  50031. newTexture.level = this.level;
  50032. // Dynamic Texture
  50033. newTexture.wrapU = this.wrapU;
  50034. newTexture.wrapV = this.wrapV;
  50035. return newTexture;
  50036. };
  50037. DynamicTexture.prototype._rebuild = function () {
  50038. this.update();
  50039. };
  50040. return DynamicTexture;
  50041. }(BABYLON.Texture));
  50042. BABYLON.DynamicTexture = DynamicTexture;
  50043. })(BABYLON || (BABYLON = {}));
  50044. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50045. var BABYLON;
  50046. (function (BABYLON) {
  50047. var VideoTexture = /** @class */ (function (_super) {
  50048. __extends(VideoTexture, _super);
  50049. /**
  50050. * Creates a video texture.
  50051. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50052. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50053. * @param {BABYLON.Scene} scene is obviously the current scene.
  50054. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50055. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50056. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50057. */
  50058. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50059. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50060. if (invertY === void 0) { invertY = false; }
  50061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50062. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50063. _this._autoLaunch = true;
  50064. var urls = null;
  50065. _this.name = name;
  50066. if (urlsOrVideo instanceof HTMLVideoElement) {
  50067. _this.video = urlsOrVideo;
  50068. }
  50069. else {
  50070. urls = urlsOrVideo;
  50071. _this.video = document.createElement("video");
  50072. _this.video.autoplay = false;
  50073. _this.video.loop = true;
  50074. }
  50075. _this._engine = _this.getScene().getEngine();
  50076. _this._generateMipMaps = generateMipMaps;
  50077. _this._samplingMode = samplingMode;
  50078. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50079. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50080. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50081. }
  50082. else {
  50083. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50084. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50085. _this._generateMipMaps = false;
  50086. }
  50087. if (urls) {
  50088. _this.video.addEventListener("canplay", function () {
  50089. _this._createTexture();
  50090. });
  50091. urls.forEach(function (url) {
  50092. var source = document.createElement("source");
  50093. source.src = url;
  50094. _this.video.appendChild(source);
  50095. });
  50096. }
  50097. else {
  50098. _this._createTexture();
  50099. }
  50100. _this._lastUpdate = BABYLON.Tools.Now;
  50101. return _this;
  50102. }
  50103. VideoTexture.prototype.__setTextureReady = function () {
  50104. if (this._texture) {
  50105. this._texture.isReady = true;
  50106. }
  50107. };
  50108. VideoTexture.prototype._createTexture = function () {
  50109. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50110. if (this._autoLaunch) {
  50111. this._autoLaunch = false;
  50112. this.video.play();
  50113. }
  50114. this._setTextureReady = this.__setTextureReady.bind(this);
  50115. this.video.addEventListener("playing", this._setTextureReady);
  50116. };
  50117. VideoTexture.prototype._rebuild = function () {
  50118. this.update();
  50119. };
  50120. VideoTexture.prototype.update = function () {
  50121. var now = BABYLON.Tools.Now;
  50122. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50123. return false;
  50124. }
  50125. this._lastUpdate = now;
  50126. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50127. return true;
  50128. };
  50129. VideoTexture.prototype.dispose = function () {
  50130. _super.prototype.dispose.call(this);
  50131. this.video.removeEventListener("playing", this._setTextureReady);
  50132. };
  50133. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50134. var video = document.createElement("video");
  50135. var constraintsDeviceId;
  50136. if (constraints && constraints.deviceId) {
  50137. constraintsDeviceId = {
  50138. exact: constraints.deviceId
  50139. };
  50140. }
  50141. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50142. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50143. if (navigator.getUserMedia) {
  50144. navigator.getUserMedia({
  50145. video: {
  50146. deviceId: constraintsDeviceId,
  50147. width: {
  50148. min: (constraints && constraints.minWidth) || 256,
  50149. max: (constraints && constraints.maxWidth) || 640
  50150. },
  50151. height: {
  50152. min: (constraints && constraints.minHeight) || 256,
  50153. max: (constraints && constraints.maxHeight) || 480
  50154. }
  50155. }
  50156. }, function (stream) {
  50157. if (video.mozSrcObject !== undefined) {
  50158. video.mozSrcObject = stream;
  50159. }
  50160. else {
  50161. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50162. }
  50163. video.play();
  50164. if (onReady) {
  50165. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50166. }
  50167. }, function (e) {
  50168. BABYLON.Tools.Error(e.name);
  50169. });
  50170. }
  50171. };
  50172. return VideoTexture;
  50173. }(BABYLON.Texture));
  50174. BABYLON.VideoTexture = VideoTexture;
  50175. })(BABYLON || (BABYLON = {}));
  50176. //# sourceMappingURL=babylon.videoTexture.js.map
  50177. var BABYLON;
  50178. (function (BABYLON) {
  50179. var RawTexture = /** @class */ (function (_super) {
  50180. __extends(RawTexture, _super);
  50181. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50183. if (invertY === void 0) { invertY = false; }
  50184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50185. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50186. _this.format = format;
  50187. _this._engine = scene.getEngine();
  50188. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50189. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50190. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50191. return _this;
  50192. }
  50193. RawTexture.prototype.update = function (data) {
  50194. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50195. };
  50196. // Statics
  50197. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50198. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50199. if (invertY === void 0) { invertY = false; }
  50200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50201. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50202. };
  50203. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50204. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50205. if (invertY === void 0) { invertY = false; }
  50206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50207. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50208. };
  50209. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50210. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50211. if (invertY === void 0) { invertY = false; }
  50212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50213. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50214. };
  50215. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50216. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50217. if (invertY === void 0) { invertY = false; }
  50218. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50219. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50220. };
  50221. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50222. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50223. if (invertY === void 0) { invertY = false; }
  50224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50225. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50226. };
  50227. return RawTexture;
  50228. }(BABYLON.Texture));
  50229. BABYLON.RawTexture = RawTexture;
  50230. })(BABYLON || (BABYLON = {}));
  50231. //# sourceMappingURL=babylon.rawTexture.js.map
  50232. var BABYLON;
  50233. (function (BABYLON) {
  50234. var PostProcess = /** @class */ (function () {
  50235. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50236. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50237. if (defines === void 0) { defines = null; }
  50238. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50239. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50240. if (blockCompilation === void 0) { blockCompilation = false; }
  50241. this.name = name;
  50242. this.width = -1;
  50243. this.height = -1;
  50244. this.autoClear = true;
  50245. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50246. /*
  50247. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50248. Can only be used on a single postprocess or on the last one of a chain.
  50249. */
  50250. this.enablePixelPerfectMode = false;
  50251. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50252. this.alwaysForcePOT = false;
  50253. this.samples = 1;
  50254. this.adaptScaleToCurrentViewport = false;
  50255. this._reusable = false;
  50256. this._textures = new BABYLON.SmartArray(2);
  50257. this._currentRenderTextureInd = 0;
  50258. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50259. this._texelSize = BABYLON.Vector2.Zero();
  50260. // Events
  50261. /**
  50262. * An event triggered when the postprocess is activated.
  50263. * @type {BABYLON.Observable}
  50264. */
  50265. this.onActivateObservable = new BABYLON.Observable();
  50266. /**
  50267. * An event triggered when the postprocess changes its size.
  50268. * @type {BABYLON.Observable}
  50269. */
  50270. this.onSizeChangedObservable = new BABYLON.Observable();
  50271. /**
  50272. * An event triggered when the postprocess applies its effect.
  50273. * @type {BABYLON.Observable}
  50274. */
  50275. this.onApplyObservable = new BABYLON.Observable();
  50276. /**
  50277. * An event triggered before rendering the postprocess
  50278. * @type {BABYLON.Observable}
  50279. */
  50280. this.onBeforeRenderObservable = new BABYLON.Observable();
  50281. /**
  50282. * An event triggered after rendering the postprocess
  50283. * @type {BABYLON.Observable}
  50284. */
  50285. this.onAfterRenderObservable = new BABYLON.Observable();
  50286. if (camera != null) {
  50287. this._camera = camera;
  50288. this._scene = camera.getScene();
  50289. camera.attachPostProcess(this);
  50290. this._engine = this._scene.getEngine();
  50291. this._scene.postProcesses.push(this);
  50292. }
  50293. else if (engine) {
  50294. this._engine = engine;
  50295. this._engine.postProcesses.push(this);
  50296. }
  50297. this._options = options;
  50298. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50299. this._reusable = reusable || false;
  50300. this._textureType = textureType;
  50301. this._samplers = samplers || [];
  50302. this._samplers.push("textureSampler");
  50303. this._fragmentUrl = fragmentUrl;
  50304. this._vertexUrl = vertexUrl;
  50305. this._parameters = parameters || [];
  50306. this._parameters.push("scale");
  50307. this._indexParameters = indexParameters;
  50308. if (!blockCompilation) {
  50309. this.updateEffect(defines);
  50310. }
  50311. }
  50312. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50313. set: function (callback) {
  50314. if (this._onActivateObserver) {
  50315. this.onActivateObservable.remove(this._onActivateObserver);
  50316. }
  50317. if (callback) {
  50318. this._onActivateObserver = this.onActivateObservable.add(callback);
  50319. }
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50325. set: function (callback) {
  50326. if (this._onSizeChangedObserver) {
  50327. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50328. }
  50329. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. Object.defineProperty(PostProcess.prototype, "onApply", {
  50335. set: function (callback) {
  50336. if (this._onApplyObserver) {
  50337. this.onApplyObservable.remove(this._onApplyObserver);
  50338. }
  50339. this._onApplyObserver = this.onApplyObservable.add(callback);
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50345. set: function (callback) {
  50346. if (this._onBeforeRenderObserver) {
  50347. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50348. }
  50349. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50355. set: function (callback) {
  50356. if (this._onAfterRenderObserver) {
  50357. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50358. }
  50359. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50360. },
  50361. enumerable: true,
  50362. configurable: true
  50363. });
  50364. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50365. get: function () {
  50366. return this._textures.data[this._currentRenderTextureInd];
  50367. },
  50368. set: function (value) {
  50369. this._forcedOutputTexture = value;
  50370. },
  50371. enumerable: true,
  50372. configurable: true
  50373. });
  50374. PostProcess.prototype.getCamera = function () {
  50375. return this._camera;
  50376. };
  50377. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50378. get: function () {
  50379. if (this._shareOutputWithPostProcess) {
  50380. return this._shareOutputWithPostProcess.texelSize;
  50381. }
  50382. if (this._forcedOutputTexture) {
  50383. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50384. }
  50385. return this._texelSize;
  50386. },
  50387. enumerable: true,
  50388. configurable: true
  50389. });
  50390. PostProcess.prototype.getEngine = function () {
  50391. return this._engine;
  50392. };
  50393. PostProcess.prototype.getEffect = function () {
  50394. return this._effect;
  50395. };
  50396. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50397. this._disposeTextures();
  50398. this._shareOutputWithPostProcess = postProcess;
  50399. return this;
  50400. };
  50401. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50402. if (defines === void 0) { defines = null; }
  50403. if (uniforms === void 0) { uniforms = null; }
  50404. if (samplers === void 0) { samplers = null; }
  50405. 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);
  50406. };
  50407. PostProcess.prototype.isReusable = function () {
  50408. return this._reusable;
  50409. };
  50410. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50411. PostProcess.prototype.markTextureDirty = function () {
  50412. this.width = -1;
  50413. };
  50414. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50415. var _this = this;
  50416. if (sourceTexture === void 0) { sourceTexture = null; }
  50417. camera = camera || this._camera;
  50418. var scene = camera.getScene();
  50419. var engine = scene.getEngine();
  50420. var maxSize = engine.getCaps().maxTextureSize;
  50421. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50422. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50423. var desiredWidth = (this._options.width || requiredWidth);
  50424. var desiredHeight = this._options.height || requiredHeight;
  50425. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50426. if (this.adaptScaleToCurrentViewport) {
  50427. var currentViewport = engine.currentViewport;
  50428. if (currentViewport) {
  50429. desiredWidth *= currentViewport.width;
  50430. desiredHeight *= currentViewport.height;
  50431. }
  50432. }
  50433. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50434. if (!this._options.width) {
  50435. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50436. }
  50437. if (!this._options.height) {
  50438. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50439. }
  50440. }
  50441. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50442. if (this._textures.length > 0) {
  50443. for (var i = 0; i < this._textures.length; i++) {
  50444. this._engine._releaseTexture(this._textures.data[i]);
  50445. }
  50446. this._textures.reset();
  50447. }
  50448. this.width = desiredWidth;
  50449. this.height = desiredHeight;
  50450. var textureSize = { width: this.width, height: this.height };
  50451. var textureOptions = {
  50452. generateMipMaps: false,
  50453. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50454. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50455. samplingMode: this.renderTargetSamplingMode,
  50456. type: this._textureType
  50457. };
  50458. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50459. if (this._reusable) {
  50460. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50461. }
  50462. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50463. this.onSizeChangedObservable.notifyObservers(this);
  50464. }
  50465. this._textures.forEach(function (texture) {
  50466. if (texture.samples !== _this.samples) {
  50467. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50468. }
  50469. });
  50470. }
  50471. var target;
  50472. if (this._shareOutputWithPostProcess) {
  50473. target = this._shareOutputWithPostProcess.outputTexture;
  50474. }
  50475. else if (this._forcedOutputTexture) {
  50476. target = this._forcedOutputTexture;
  50477. this.width = this._forcedOutputTexture.width;
  50478. this.height = this._forcedOutputTexture.height;
  50479. }
  50480. else {
  50481. target = this.outputTexture;
  50482. }
  50483. if (this.enablePixelPerfectMode) {
  50484. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50485. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50486. }
  50487. else {
  50488. this._scaleRatio.copyFromFloats(1, 1);
  50489. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50490. }
  50491. this.onActivateObservable.notifyObservers(camera);
  50492. // Clear
  50493. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50494. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50495. }
  50496. if (this._reusable) {
  50497. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50498. }
  50499. };
  50500. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50501. get: function () {
  50502. return this._effect.isSupported;
  50503. },
  50504. enumerable: true,
  50505. configurable: true
  50506. });
  50507. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50508. get: function () {
  50509. if (this._shareOutputWithPostProcess) {
  50510. return this._shareOutputWithPostProcess.aspectRatio;
  50511. }
  50512. if (this._forcedOutputTexture) {
  50513. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50514. }
  50515. return this.width / this.height;
  50516. },
  50517. enumerable: true,
  50518. configurable: true
  50519. });
  50520. PostProcess.prototype.apply = function () {
  50521. // Check
  50522. if (!this._effect || !this._effect.isReady())
  50523. return null;
  50524. // States
  50525. this._engine.enableEffect(this._effect);
  50526. this._engine.setState(false);
  50527. this._engine.setDepthBuffer(false);
  50528. this._engine.setDepthWrite(false);
  50529. // Alpha
  50530. this._engine.setAlphaMode(this.alphaMode);
  50531. if (this.alphaConstants) {
  50532. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50533. }
  50534. // Texture
  50535. var source;
  50536. if (this._shareOutputWithPostProcess) {
  50537. source = this._shareOutputWithPostProcess.outputTexture;
  50538. }
  50539. else if (this._forcedOutputTexture) {
  50540. source = this._forcedOutputTexture;
  50541. }
  50542. else {
  50543. source = this.outputTexture;
  50544. }
  50545. this._effect._bindTexture("textureSampler", source);
  50546. // Parameters
  50547. this._effect.setVector2("scale", this._scaleRatio);
  50548. this.onApplyObservable.notifyObservers(this._effect);
  50549. return this._effect;
  50550. };
  50551. PostProcess.prototype._disposeTextures = function () {
  50552. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50553. return;
  50554. }
  50555. if (this._textures.length > 0) {
  50556. for (var i = 0; i < this._textures.length; i++) {
  50557. this._engine._releaseTexture(this._textures.data[i]);
  50558. }
  50559. }
  50560. this._textures.dispose();
  50561. };
  50562. PostProcess.prototype.dispose = function (camera) {
  50563. camera = camera || this._camera;
  50564. this._disposeTextures();
  50565. if (this._scene) {
  50566. var index_1 = this._scene.postProcesses.indexOf(this);
  50567. if (index_1 !== -1) {
  50568. this._scene.postProcesses.splice(index_1, 1);
  50569. }
  50570. }
  50571. else {
  50572. var index_2 = this._engine.postProcesses.indexOf(this);
  50573. if (index_2 !== -1) {
  50574. this._engine.postProcesses.splice(index_2, 1);
  50575. }
  50576. }
  50577. if (!camera) {
  50578. return;
  50579. }
  50580. camera.detachPostProcess(this);
  50581. var index = camera._postProcesses.indexOf(this);
  50582. if (index === 0 && camera._postProcesses.length > 0) {
  50583. this._camera._postProcesses[0].markTextureDirty();
  50584. }
  50585. this.onActivateObservable.clear();
  50586. this.onAfterRenderObservable.clear();
  50587. this.onApplyObservable.clear();
  50588. this.onBeforeRenderObservable.clear();
  50589. this.onSizeChangedObservable.clear();
  50590. };
  50591. return PostProcess;
  50592. }());
  50593. BABYLON.PostProcess = PostProcess;
  50594. })(BABYLON || (BABYLON = {}));
  50595. //# sourceMappingURL=babylon.postProcess.js.map
  50596. var BABYLON;
  50597. (function (BABYLON) {
  50598. var PassPostProcess = /** @class */ (function (_super) {
  50599. __extends(PassPostProcess, _super);
  50600. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50601. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50602. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  50603. }
  50604. return PassPostProcess;
  50605. }(BABYLON.PostProcess));
  50606. BABYLON.PassPostProcess = PassPostProcess;
  50607. })(BABYLON || (BABYLON = {}));
  50608. //# sourceMappingURL=babylon.passPostProcess.js.map
  50609. var BABYLON;
  50610. (function (BABYLON) {
  50611. var ShadowGenerator = /** @class */ (function () {
  50612. /**
  50613. * Creates a ShadowGenerator object.
  50614. * A ShadowGenerator is the required tool to use the shadows.
  50615. * Each light casting shadows needs to use its own ShadowGenerator.
  50616. * Required parameters :
  50617. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  50618. * - `light`: the light object generating the shadows.
  50619. * - `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.
  50620. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  50621. */
  50622. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  50623. // Members
  50624. this._bias = 0.00005;
  50625. this._blurBoxOffset = 1;
  50626. this._blurScale = 2;
  50627. this._blurKernel = 1;
  50628. this._useKernelBlur = false;
  50629. this._filter = ShadowGenerator.FILTER_NONE;
  50630. this._darkness = 0;
  50631. this._transparencyShadow = false;
  50632. /**
  50633. * Controls the extent to which the shadows fade out at the edge of the frustum
  50634. * Used only by directionals and spots
  50635. */
  50636. this.frustumEdgeFalloff = 0;
  50637. this.forceBackFacesOnly = false;
  50638. this._lightDirection = BABYLON.Vector3.Zero();
  50639. this._viewMatrix = BABYLON.Matrix.Zero();
  50640. this._projectionMatrix = BABYLON.Matrix.Zero();
  50641. this._transformMatrix = BABYLON.Matrix.Zero();
  50642. this._currentFaceIndex = 0;
  50643. this._currentFaceIndexCache = 0;
  50644. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  50645. this._mapSize = mapSize;
  50646. this._light = light;
  50647. this._scene = light.getScene();
  50648. light._shadowGenerator = this;
  50649. // Texture type fallback from float to int if not supported.
  50650. var caps = this._scene.getEngine().getCaps();
  50651. if (!useFullFloatFirst) {
  50652. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50653. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50654. }
  50655. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50656. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50657. }
  50658. else {
  50659. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50660. }
  50661. }
  50662. else {
  50663. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  50664. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  50665. }
  50666. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  50667. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50668. }
  50669. else {
  50670. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  50671. }
  50672. }
  50673. this._initializeGenerator();
  50674. }
  50675. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  50676. // Static
  50677. get: function () {
  50678. return ShadowGenerator._FILTER_NONE;
  50679. },
  50680. enumerable: true,
  50681. configurable: true
  50682. });
  50683. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  50684. get: function () {
  50685. return ShadowGenerator._FILTER_POISSONSAMPLING;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  50691. get: function () {
  50692. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  50698. get: function () {
  50699. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  50700. },
  50701. enumerable: true,
  50702. configurable: true
  50703. });
  50704. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  50705. get: function () {
  50706. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50707. },
  50708. enumerable: true,
  50709. configurable: true
  50710. });
  50711. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  50712. get: function () {
  50713. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50714. },
  50715. enumerable: true,
  50716. configurable: true
  50717. });
  50718. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  50719. get: function () {
  50720. return this._bias;
  50721. },
  50722. set: function (bias) {
  50723. this._bias = bias;
  50724. },
  50725. enumerable: true,
  50726. configurable: true
  50727. });
  50728. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  50729. get: function () {
  50730. return this._blurBoxOffset;
  50731. },
  50732. set: function (value) {
  50733. if (this._blurBoxOffset === value) {
  50734. return;
  50735. }
  50736. this._blurBoxOffset = value;
  50737. this._disposeBlurPostProcesses();
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  50743. get: function () {
  50744. return this._blurScale;
  50745. },
  50746. set: function (value) {
  50747. if (this._blurScale === value) {
  50748. return;
  50749. }
  50750. this._blurScale = value;
  50751. this._disposeBlurPostProcesses();
  50752. },
  50753. enumerable: true,
  50754. configurable: true
  50755. });
  50756. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  50757. get: function () {
  50758. return this._blurKernel;
  50759. },
  50760. set: function (value) {
  50761. if (this._blurKernel === value) {
  50762. return;
  50763. }
  50764. this._blurKernel = value;
  50765. this._disposeBlurPostProcesses();
  50766. },
  50767. enumerable: true,
  50768. configurable: true
  50769. });
  50770. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  50771. get: function () {
  50772. return this._useKernelBlur;
  50773. },
  50774. set: function (value) {
  50775. if (this._useKernelBlur === value) {
  50776. return;
  50777. }
  50778. this._useKernelBlur = value;
  50779. this._disposeBlurPostProcesses();
  50780. },
  50781. enumerable: true,
  50782. configurable: true
  50783. });
  50784. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  50785. get: function () {
  50786. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  50787. },
  50788. set: function (value) {
  50789. this._depthScale = value;
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  50795. get: function () {
  50796. return this._filter;
  50797. },
  50798. set: function (value) {
  50799. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  50800. if (this._light.needCube()) {
  50801. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50802. this.useExponentialShadowMap = true;
  50803. return;
  50804. }
  50805. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50806. this.useCloseExponentialShadowMap = true;
  50807. return;
  50808. }
  50809. }
  50810. if (this._filter === value) {
  50811. return;
  50812. }
  50813. this._filter = value;
  50814. this._disposeBlurPostProcesses();
  50815. this._applyFilterValues();
  50816. this._light._markMeshesAsLightDirty();
  50817. },
  50818. enumerable: true,
  50819. configurable: true
  50820. });
  50821. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  50822. get: function () {
  50823. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  50824. },
  50825. set: function (value) {
  50826. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  50827. return;
  50828. }
  50829. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  50830. },
  50831. enumerable: true,
  50832. configurable: true
  50833. });
  50834. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  50835. get: function () {
  50836. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50837. return this.useExponentialShadowMap;
  50838. },
  50839. set: function (value) {
  50840. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  50841. this.useExponentialShadowMap = value;
  50842. },
  50843. enumerable: true,
  50844. configurable: true
  50845. });
  50846. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  50847. get: function () {
  50848. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50849. return this.useBlurExponentialShadowMap;
  50850. },
  50851. set: function (value) {
  50852. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  50853. this.useBlurExponentialShadowMap = value;
  50854. },
  50855. enumerable: true,
  50856. configurable: true
  50857. });
  50858. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  50859. get: function () {
  50860. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  50861. },
  50862. set: function (value) {
  50863. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  50864. return;
  50865. }
  50866. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50867. },
  50868. enumerable: true,
  50869. configurable: true
  50870. });
  50871. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  50872. get: function () {
  50873. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  50874. },
  50875. set: function (value) {
  50876. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  50877. return;
  50878. }
  50879. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50880. },
  50881. enumerable: true,
  50882. configurable: true
  50883. });
  50884. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  50885. get: function () {
  50886. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  50887. },
  50888. set: function (value) {
  50889. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  50890. return;
  50891. }
  50892. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50893. },
  50894. enumerable: true,
  50895. configurable: true
  50896. });
  50897. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  50898. get: function () {
  50899. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  50900. },
  50901. set: function (value) {
  50902. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  50903. return;
  50904. }
  50905. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  50906. },
  50907. enumerable: true,
  50908. configurable: true
  50909. });
  50910. /**
  50911. * Returns the darkness value (float).
  50912. */
  50913. ShadowGenerator.prototype.getDarkness = function () {
  50914. return this._darkness;
  50915. };
  50916. /**
  50917. * Sets the ShadowGenerator darkness value (float <= 1.0).
  50918. * Returns the ShadowGenerator.
  50919. */
  50920. ShadowGenerator.prototype.setDarkness = function (darkness) {
  50921. if (darkness >= 1.0)
  50922. this._darkness = 1.0;
  50923. else if (darkness <= 0.0)
  50924. this._darkness = 0.0;
  50925. else
  50926. this._darkness = darkness;
  50927. return this;
  50928. };
  50929. /**
  50930. * Sets the ability to have transparent shadow (boolean).
  50931. * Returns the ShadowGenerator.
  50932. */
  50933. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  50934. this._transparencyShadow = hasShadow;
  50935. return this;
  50936. };
  50937. /**
  50938. * Returns a RenderTargetTexture object : the shadow map texture.
  50939. */
  50940. ShadowGenerator.prototype.getShadowMap = function () {
  50941. return this._shadowMap;
  50942. };
  50943. /**
  50944. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  50945. */
  50946. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  50947. if (this._shadowMap2) {
  50948. return this._shadowMap2;
  50949. }
  50950. return this._shadowMap;
  50951. };
  50952. /**
  50953. * Helper function to add a mesh and its descendants to the list of shadow casters
  50954. * @param mesh Mesh to add
  50955. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  50956. */
  50957. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  50958. if (includeDescendants === void 0) { includeDescendants = true; }
  50959. if (!this._shadowMap) {
  50960. return this;
  50961. }
  50962. if (!this._shadowMap.renderList) {
  50963. this._shadowMap.renderList = [];
  50964. }
  50965. this._shadowMap.renderList.push(mesh);
  50966. if (includeDescendants) {
  50967. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  50968. }
  50969. return this;
  50970. var _a;
  50971. };
  50972. /**
  50973. * Helper function to remove a mesh and its descendants from the list of shadow casters
  50974. * @param mesh Mesh to remove
  50975. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  50976. */
  50977. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  50978. if (includeDescendants === void 0) { includeDescendants = true; }
  50979. if (!this._shadowMap || !this._shadowMap.renderList) {
  50980. return this;
  50981. }
  50982. var index = this._shadowMap.renderList.indexOf(mesh);
  50983. if (index !== -1) {
  50984. this._shadowMap.renderList.splice(index, 1);
  50985. }
  50986. if (includeDescendants) {
  50987. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  50988. var child = _a[_i];
  50989. this.removeShadowCaster(child);
  50990. }
  50991. }
  50992. return this;
  50993. };
  50994. /**
  50995. * Returns the associated light object.
  50996. */
  50997. ShadowGenerator.prototype.getLight = function () {
  50998. return this._light;
  50999. };
  51000. ShadowGenerator.prototype._initializeGenerator = function () {
  51001. this._light._markMeshesAsLightDirty();
  51002. this._initializeShadowMap();
  51003. };
  51004. ShadowGenerator.prototype._initializeShadowMap = function () {
  51005. var _this = this;
  51006. // Render target
  51007. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51008. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51009. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51010. this._shadowMap.anisotropicFilteringLevel = 1;
  51011. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51012. this._shadowMap.renderParticles = false;
  51013. this._shadowMap.ignoreCameraViewport = true;
  51014. // Record Face Index before render.
  51015. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51016. _this._currentFaceIndex = faceIndex;
  51017. });
  51018. // Custom render function.
  51019. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51020. // Blur if required afer render.
  51021. this._shadowMap.onAfterUnbindObservable.add(function () {
  51022. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51023. return;
  51024. }
  51025. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51026. _this._initializeBlurRTTAndPostProcesses();
  51027. }
  51028. var shadowMap = _this.getShadowMapForRendering();
  51029. if (shadowMap) {
  51030. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51031. }
  51032. });
  51033. // Clear according to the chosen filter.
  51034. this._shadowMap.onClearObservable.add(function (engine) {
  51035. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51036. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51037. }
  51038. else {
  51039. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51040. }
  51041. });
  51042. };
  51043. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51044. var _this = this;
  51045. var engine = this._scene.getEngine();
  51046. var targetSize = this._mapSize / this.blurScale;
  51047. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51048. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51049. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51050. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51051. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51052. }
  51053. if (this.useKernelBlur) {
  51054. 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);
  51055. this._kernelBlurXPostprocess.width = targetSize;
  51056. this._kernelBlurXPostprocess.height = targetSize;
  51057. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51058. effect.setTexture("textureSampler", _this._shadowMap);
  51059. });
  51060. 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);
  51061. this._kernelBlurXPostprocess.autoClear = false;
  51062. this._kernelBlurYPostprocess.autoClear = false;
  51063. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51064. this._kernelBlurXPostprocess.packedFloat = true;
  51065. this._kernelBlurYPostprocess.packedFloat = true;
  51066. }
  51067. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51068. }
  51069. else {
  51070. 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);
  51071. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51072. effect.setFloat2("screenSize", targetSize, targetSize);
  51073. effect.setTexture("textureSampler", _this._shadowMap);
  51074. });
  51075. this._boxBlurPostprocess.autoClear = false;
  51076. this._blurPostProcesses = [this._boxBlurPostprocess];
  51077. }
  51078. };
  51079. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51080. var index;
  51081. var engine = this._scene.getEngine();
  51082. if (depthOnlySubMeshes.length) {
  51083. engine.setColorWrite(false);
  51084. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51085. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51086. }
  51087. engine.setColorWrite(true);
  51088. }
  51089. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51090. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51091. }
  51092. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51093. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51094. }
  51095. if (this._transparencyShadow) {
  51096. for (index = 0; index < transparentSubMeshes.length; index++) {
  51097. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51098. }
  51099. }
  51100. };
  51101. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51102. var _this = this;
  51103. var mesh = subMesh.getRenderingMesh();
  51104. var scene = this._scene;
  51105. var engine = scene.getEngine();
  51106. var material = subMesh.getMaterial();
  51107. if (!material) {
  51108. return;
  51109. }
  51110. // Culling
  51111. engine.setState(material.backFaceCulling);
  51112. // Managing instances
  51113. var batch = mesh._getInstancesRenderList(subMesh._id);
  51114. if (batch.mustReturn) {
  51115. return;
  51116. }
  51117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51118. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51119. engine.enableEffect(this._effect);
  51120. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51121. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51122. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51123. this._effect.setVector3("lightPosition", this.getLight().position);
  51124. if (scene.activeCamera) {
  51125. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51126. }
  51127. // Alpha test
  51128. if (material && material.needAlphaTesting()) {
  51129. var alphaTexture = material.getAlphaTestTexture();
  51130. if (alphaTexture) {
  51131. this._effect.setTexture("diffuseSampler", alphaTexture);
  51132. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51133. }
  51134. }
  51135. // Bones
  51136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51137. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51138. }
  51139. if (this.forceBackFacesOnly) {
  51140. engine.setState(true, 0, false, true);
  51141. }
  51142. // Draw
  51143. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51144. if (this.forceBackFacesOnly) {
  51145. engine.setState(true, 0, false, false);
  51146. }
  51147. }
  51148. else {
  51149. // Need to reset refresh rate of the shadowMap
  51150. if (this._shadowMap) {
  51151. this._shadowMap.resetRefreshCounter();
  51152. }
  51153. }
  51154. };
  51155. ShadowGenerator.prototype._applyFilterValues = function () {
  51156. if (!this._shadowMap) {
  51157. return;
  51158. }
  51159. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51160. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51161. }
  51162. else {
  51163. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51164. }
  51165. };
  51166. /**
  51167. * Force shader compilation including textures ready check
  51168. */
  51169. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51170. var _this = this;
  51171. var shadowMap = this.getShadowMap();
  51172. if (!shadowMap) {
  51173. return;
  51174. }
  51175. var subMeshes = new Array();
  51176. var currentIndex = 0;
  51177. var renderList = shadowMap.renderList;
  51178. if (!renderList) {
  51179. return;
  51180. }
  51181. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51182. var mesh = renderList_1[_i];
  51183. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51184. }
  51185. var checkReady = function () {
  51186. if (!_this._scene || !_this._scene.getEngine()) {
  51187. return;
  51188. }
  51189. var subMesh = subMeshes[currentIndex];
  51190. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  51191. currentIndex++;
  51192. if (currentIndex >= subMeshes.length) {
  51193. if (onCompiled) {
  51194. onCompiled(_this);
  51195. }
  51196. return;
  51197. }
  51198. }
  51199. setTimeout(checkReady, 16);
  51200. };
  51201. if (subMeshes.length > 0) {
  51202. checkReady();
  51203. }
  51204. };
  51205. /**
  51206. * Boolean : true when the ShadowGenerator is finally computed.
  51207. */
  51208. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51209. var defines = [];
  51210. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51211. defines.push("#define FLOAT");
  51212. }
  51213. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51214. defines.push("#define ESM");
  51215. }
  51216. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51217. var mesh = subMesh.getMesh();
  51218. var material = subMesh.getMaterial();
  51219. // Alpha test
  51220. if (material && material.needAlphaTesting()) {
  51221. var alphaTexture = material.getAlphaTestTexture();
  51222. if (alphaTexture) {
  51223. defines.push("#define ALPHATEST");
  51224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51225. attribs.push(BABYLON.VertexBuffer.UVKind);
  51226. defines.push("#define UV1");
  51227. }
  51228. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51229. if (alphaTexture.coordinatesIndex === 1) {
  51230. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51231. defines.push("#define UV2");
  51232. }
  51233. }
  51234. }
  51235. }
  51236. // Bones
  51237. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51240. if (mesh.numBoneInfluencers > 4) {
  51241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51243. }
  51244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51245. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51246. }
  51247. else {
  51248. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51249. }
  51250. // Instances
  51251. if (useInstances) {
  51252. defines.push("#define INSTANCES");
  51253. attribs.push("world0");
  51254. attribs.push("world1");
  51255. attribs.push("world2");
  51256. attribs.push("world3");
  51257. }
  51258. // Get correct effect
  51259. var join = defines.join("\n");
  51260. if (this._cachedDefines !== join) {
  51261. this._cachedDefines = join;
  51262. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51263. }
  51264. return this._effect.isReady();
  51265. };
  51266. /**
  51267. * This creates the defines related to the standard BJS materials.
  51268. */
  51269. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51270. var scene = this._scene;
  51271. var light = this._light;
  51272. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51273. return;
  51274. }
  51275. defines["SHADOW" + lightIndex] = true;
  51276. if (this.usePoissonSampling) {
  51277. defines["SHADOWPCF" + lightIndex] = true;
  51278. }
  51279. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51280. defines["SHADOWESM" + lightIndex] = true;
  51281. }
  51282. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51283. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51284. }
  51285. if (light.needCube()) {
  51286. defines["SHADOWCUBE" + lightIndex] = true;
  51287. }
  51288. };
  51289. /**
  51290. * This binds shadow lights related to the standard BJS materials.
  51291. * It implies the unifroms available on the materials are the standard BJS ones.
  51292. */
  51293. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51294. var light = this._light;
  51295. var scene = this._scene;
  51296. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51297. return;
  51298. }
  51299. var camera = scene.activeCamera;
  51300. if (!camera) {
  51301. return;
  51302. }
  51303. var shadowMap = this.getShadowMap();
  51304. if (!shadowMap) {
  51305. return;
  51306. }
  51307. if (!light.needCube()) {
  51308. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51309. }
  51310. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51311. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51312. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51313. };
  51314. // Methods
  51315. /**
  51316. * Returns a Matrix object : the updated transformation matrix.
  51317. */
  51318. ShadowGenerator.prototype.getTransformMatrix = function () {
  51319. var scene = this._scene;
  51320. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51321. return this._transformMatrix;
  51322. }
  51323. this._currentRenderID = scene.getRenderId();
  51324. this._currentFaceIndexCache = this._currentFaceIndex;
  51325. var lightPosition = this._light.position;
  51326. if (this._light.computeTransformedInformation()) {
  51327. lightPosition = this._light.transformedPosition;
  51328. }
  51329. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51330. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51331. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51332. }
  51333. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51334. this._cachedPosition = lightPosition.clone();
  51335. this._cachedDirection = this._lightDirection.clone();
  51336. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51337. var shadowMap = this.getShadowMap();
  51338. if (shadowMap) {
  51339. var renderList = shadowMap.renderList;
  51340. if (renderList) {
  51341. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51342. }
  51343. }
  51344. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51345. }
  51346. return this._transformMatrix;
  51347. };
  51348. ShadowGenerator.prototype.recreateShadowMap = function () {
  51349. var shadowMap = this._shadowMap;
  51350. if (!shadowMap) {
  51351. return;
  51352. }
  51353. // Track render list.
  51354. var renderList = shadowMap.renderList;
  51355. // Clean up existing data.
  51356. this._disposeRTTandPostProcesses();
  51357. // Reinitializes.
  51358. this._initializeGenerator();
  51359. // Reaffect the filter to ensure a correct fallback if necessary.
  51360. this.filter = this.filter;
  51361. // Reaffect the filter.
  51362. this._applyFilterValues();
  51363. // Reaffect Render List.
  51364. shadowMap.renderList = renderList;
  51365. };
  51366. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51367. if (this._shadowMap2) {
  51368. this._shadowMap2.dispose();
  51369. this._shadowMap2 = null;
  51370. }
  51371. if (this._downSamplePostprocess) {
  51372. this._downSamplePostprocess.dispose();
  51373. this._downSamplePostprocess = null;
  51374. }
  51375. if (this._boxBlurPostprocess) {
  51376. this._boxBlurPostprocess.dispose();
  51377. this._boxBlurPostprocess = null;
  51378. }
  51379. if (this._kernelBlurXPostprocess) {
  51380. this._kernelBlurXPostprocess.dispose();
  51381. this._kernelBlurXPostprocess = null;
  51382. }
  51383. if (this._kernelBlurYPostprocess) {
  51384. this._kernelBlurYPostprocess.dispose();
  51385. this._kernelBlurYPostprocess = null;
  51386. }
  51387. this._blurPostProcesses = [];
  51388. };
  51389. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51390. if (this._shadowMap) {
  51391. this._shadowMap.dispose();
  51392. this._shadowMap = null;
  51393. }
  51394. this._disposeBlurPostProcesses();
  51395. };
  51396. /**
  51397. * Disposes the ShadowGenerator.
  51398. * Returns nothing.
  51399. */
  51400. ShadowGenerator.prototype.dispose = function () {
  51401. this._disposeRTTandPostProcesses();
  51402. if (this._light) {
  51403. this._light._shadowGenerator = null;
  51404. this._light._markMeshesAsLightDirty();
  51405. }
  51406. };
  51407. /**
  51408. * Serializes the ShadowGenerator and returns a serializationObject.
  51409. */
  51410. ShadowGenerator.prototype.serialize = function () {
  51411. var serializationObject = {};
  51412. var shadowMap = this.getShadowMap();
  51413. if (!shadowMap) {
  51414. return serializationObject;
  51415. }
  51416. serializationObject.lightId = this._light.id;
  51417. serializationObject.mapSize = shadowMap.getRenderSize();
  51418. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51419. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51420. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51421. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51422. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51423. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51424. serializationObject.depthScale = this.depthScale;
  51425. serializationObject.darkness = this.getDarkness();
  51426. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51427. serializationObject.blurKernel = this.blurKernel;
  51428. serializationObject.blurScale = this.blurScale;
  51429. serializationObject.useKernelBlur = this.useKernelBlur;
  51430. serializationObject.transparencyShadow = this._transparencyShadow;
  51431. serializationObject.renderList = [];
  51432. if (shadowMap.renderList) {
  51433. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51434. var mesh = shadowMap.renderList[meshIndex];
  51435. serializationObject.renderList.push(mesh.id);
  51436. }
  51437. }
  51438. return serializationObject;
  51439. };
  51440. /**
  51441. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51442. */
  51443. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51444. //casting to point light, as light is missing the position attr and typescript complains.
  51445. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51446. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51447. var shadowMap = shadowGenerator.getShadowMap();
  51448. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51449. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51450. meshes.forEach(function (mesh) {
  51451. if (!shadowMap) {
  51452. return;
  51453. }
  51454. if (!shadowMap.renderList) {
  51455. shadowMap.renderList = [];
  51456. }
  51457. shadowMap.renderList.push(mesh);
  51458. });
  51459. }
  51460. if (parsedShadowGenerator.usePoissonSampling) {
  51461. shadowGenerator.usePoissonSampling = true;
  51462. }
  51463. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51464. shadowGenerator.useExponentialShadowMap = true;
  51465. }
  51466. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51467. shadowGenerator.useBlurExponentialShadowMap = true;
  51468. }
  51469. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51470. shadowGenerator.useCloseExponentialShadowMap = true;
  51471. }
  51472. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51473. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51474. }
  51475. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51476. shadowGenerator.useExponentialShadowMap = true;
  51477. }
  51478. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51479. shadowGenerator.useBlurExponentialShadowMap = true;
  51480. }
  51481. if (parsedShadowGenerator.depthScale) {
  51482. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51483. }
  51484. if (parsedShadowGenerator.blurScale) {
  51485. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51486. }
  51487. if (parsedShadowGenerator.blurBoxOffset) {
  51488. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51489. }
  51490. if (parsedShadowGenerator.useKernelBlur) {
  51491. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51492. }
  51493. if (parsedShadowGenerator.blurKernel) {
  51494. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51495. }
  51496. if (parsedShadowGenerator.bias !== undefined) {
  51497. shadowGenerator.bias = parsedShadowGenerator.bias;
  51498. }
  51499. if (parsedShadowGenerator.darkness) {
  51500. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51501. }
  51502. if (parsedShadowGenerator.transparencyShadow) {
  51503. shadowGenerator.setTransparencyShadow(true);
  51504. }
  51505. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51506. return shadowGenerator;
  51507. };
  51508. ShadowGenerator._FILTER_NONE = 0;
  51509. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51510. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51511. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51512. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51513. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51514. return ShadowGenerator;
  51515. }());
  51516. BABYLON.ShadowGenerator = ShadowGenerator;
  51517. })(BABYLON || (BABYLON = {}));
  51518. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51519. var BABYLON;
  51520. (function (BABYLON) {
  51521. var DefaultLoadingScreen = /** @class */ (function () {
  51522. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51523. if (_loadingText === void 0) { _loadingText = ""; }
  51524. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51525. var _this = this;
  51526. this._renderingCanvas = _renderingCanvas;
  51527. this._loadingText = _loadingText;
  51528. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51529. // Resize
  51530. this._resizeLoadingUI = function () {
  51531. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51532. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51533. if (!_this._loadingDiv) {
  51534. return;
  51535. }
  51536. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51537. _this._loadingDiv.style.left = canvasRect.left + "px";
  51538. _this._loadingDiv.style.top = canvasRect.top + "px";
  51539. _this._loadingDiv.style.width = canvasRect.width + "px";
  51540. _this._loadingDiv.style.height = canvasRect.height + "px";
  51541. };
  51542. }
  51543. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51544. if (this._loadingDiv) {
  51545. // Do not add a loading screen if there is already one
  51546. return;
  51547. }
  51548. this._loadingDiv = document.createElement("div");
  51549. this._loadingDiv.id = "babylonjsLoadingDiv";
  51550. this._loadingDiv.style.opacity = "0";
  51551. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51552. this._loadingDiv.style.pointerEvents = "none";
  51553. // Loading text
  51554. this._loadingTextDiv = document.createElement("div");
  51555. this._loadingTextDiv.style.position = "absolute";
  51556. this._loadingTextDiv.style.left = "0";
  51557. this._loadingTextDiv.style.top = "50%";
  51558. this._loadingTextDiv.style.marginTop = "80px";
  51559. this._loadingTextDiv.style.width = "100%";
  51560. this._loadingTextDiv.style.height = "20px";
  51561. this._loadingTextDiv.style.fontFamily = "Arial";
  51562. this._loadingTextDiv.style.fontSize = "14px";
  51563. this._loadingTextDiv.style.color = "white";
  51564. this._loadingTextDiv.style.textAlign = "center";
  51565. this._loadingTextDiv.innerHTML = "Loading";
  51566. this._loadingDiv.appendChild(this._loadingTextDiv);
  51567. //set the predefined text
  51568. this._loadingTextDiv.innerHTML = this._loadingText;
  51569. // Generating keyframes
  51570. var style = document.createElement('style');
  51571. style.type = 'text/css';
  51572. 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 }";
  51573. style.innerHTML = keyFrames;
  51574. document.getElementsByTagName('head')[0].appendChild(style);
  51575. // Loading img
  51576. var imgBack = new Image();
  51577. 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";
  51578. imgBack.style.position = "absolute";
  51579. imgBack.style.left = "50%";
  51580. imgBack.style.top = "50%";
  51581. imgBack.style.marginLeft = "-60px";
  51582. imgBack.style.marginTop = "-60px";
  51583. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  51584. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  51585. imgBack.style.transformOrigin = "50% 50%";
  51586. imgBack.style.webkitTransformOrigin = "50% 50%";
  51587. this._loadingDiv.appendChild(imgBack);
  51588. this._resizeLoadingUI();
  51589. window.addEventListener("resize", this._resizeLoadingUI);
  51590. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51591. document.body.appendChild(this._loadingDiv);
  51592. this._loadingDiv.style.opacity = "1";
  51593. };
  51594. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  51595. var _this = this;
  51596. if (!this._loadingDiv) {
  51597. return;
  51598. }
  51599. var onTransitionEnd = function () {
  51600. if (!_this._loadingDiv) {
  51601. return;
  51602. }
  51603. document.body.removeChild(_this._loadingDiv);
  51604. window.removeEventListener("resize", _this._resizeLoadingUI);
  51605. _this._loadingDiv = null;
  51606. };
  51607. this._loadingDiv.style.opacity = "0";
  51608. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  51609. };
  51610. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  51611. set: function (text) {
  51612. this._loadingText = text;
  51613. if (this._loadingTextDiv) {
  51614. this._loadingTextDiv.innerHTML = this._loadingText;
  51615. }
  51616. },
  51617. enumerable: true,
  51618. configurable: true
  51619. });
  51620. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  51621. get: function () {
  51622. return this._loadingDivBackgroundColor;
  51623. },
  51624. set: function (color) {
  51625. this._loadingDivBackgroundColor = color;
  51626. if (!this._loadingDiv) {
  51627. return;
  51628. }
  51629. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  51630. },
  51631. enumerable: true,
  51632. configurable: true
  51633. });
  51634. return DefaultLoadingScreen;
  51635. }());
  51636. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  51637. })(BABYLON || (BABYLON = {}));
  51638. //# sourceMappingURL=babylon.loadingScreen.js.map
  51639. var BABYLON;
  51640. (function (BABYLON) {
  51641. var SceneLoader = /** @class */ (function () {
  51642. function SceneLoader() {
  51643. }
  51644. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  51645. get: function () {
  51646. return 0;
  51647. },
  51648. enumerable: true,
  51649. configurable: true
  51650. });
  51651. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  51652. get: function () {
  51653. return 1;
  51654. },
  51655. enumerable: true,
  51656. configurable: true
  51657. });
  51658. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  51659. get: function () {
  51660. return 2;
  51661. },
  51662. enumerable: true,
  51663. configurable: true
  51664. });
  51665. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  51666. get: function () {
  51667. return 3;
  51668. },
  51669. enumerable: true,
  51670. configurable: true
  51671. });
  51672. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  51673. get: function () {
  51674. return SceneLoader._ForceFullSceneLoadingForIncremental;
  51675. },
  51676. set: function (value) {
  51677. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  51678. },
  51679. enumerable: true,
  51680. configurable: true
  51681. });
  51682. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  51683. get: function () {
  51684. return SceneLoader._ShowLoadingScreen;
  51685. },
  51686. set: function (value) {
  51687. SceneLoader._ShowLoadingScreen = value;
  51688. },
  51689. enumerable: true,
  51690. configurable: true
  51691. });
  51692. Object.defineProperty(SceneLoader, "loggingLevel", {
  51693. get: function () {
  51694. return SceneLoader._loggingLevel;
  51695. },
  51696. set: function (value) {
  51697. SceneLoader._loggingLevel = value;
  51698. },
  51699. enumerable: true,
  51700. configurable: true
  51701. });
  51702. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  51703. get: function () {
  51704. return SceneLoader._CleanBoneMatrixWeights;
  51705. },
  51706. set: function (value) {
  51707. SceneLoader._CleanBoneMatrixWeights = value;
  51708. },
  51709. enumerable: true,
  51710. configurable: true
  51711. });
  51712. SceneLoader._getDefaultPlugin = function () {
  51713. return SceneLoader._registeredPlugins[".babylon"];
  51714. };
  51715. SceneLoader._getPluginForExtension = function (extension) {
  51716. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  51717. if (registeredPlugin) {
  51718. return registeredPlugin;
  51719. }
  51720. return SceneLoader._getDefaultPlugin();
  51721. };
  51722. SceneLoader._getPluginForDirectLoad = function (data) {
  51723. for (var extension in SceneLoader._registeredPlugins) {
  51724. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  51725. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  51726. return SceneLoader._registeredPlugins[extension];
  51727. }
  51728. }
  51729. return SceneLoader._getDefaultPlugin();
  51730. };
  51731. SceneLoader._getPluginForFilename = function (sceneFilename) {
  51732. if (sceneFilename.name) {
  51733. sceneFilename = sceneFilename.name;
  51734. }
  51735. var dotPosition = sceneFilename.lastIndexOf(".");
  51736. var queryStringPosition = sceneFilename.indexOf("?");
  51737. if (queryStringPosition === -1) {
  51738. queryStringPosition = sceneFilename.length;
  51739. }
  51740. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  51741. return SceneLoader._getPluginForExtension(extension);
  51742. };
  51743. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  51744. SceneLoader._getDirectLoad = function (sceneFilename) {
  51745. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  51746. return sceneFilename.substr(5);
  51747. }
  51748. return null;
  51749. };
  51750. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51751. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  51752. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  51753. var plugin = registeredPlugin.plugin;
  51754. var useArrayBuffer = registeredPlugin.isBinary;
  51755. var database;
  51756. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  51757. var dataCallback = function (data) {
  51758. if (scene.isDisposed) {
  51759. onError("Scene has been disposed");
  51760. return;
  51761. }
  51762. scene.database = database;
  51763. try {
  51764. onSuccess(plugin, data);
  51765. }
  51766. catch (e) {
  51767. onError(null, e);
  51768. }
  51769. };
  51770. var manifestChecked = function (success) {
  51771. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  51772. if (request) {
  51773. onError(request.status + " " + request.statusText);
  51774. }
  51775. });
  51776. };
  51777. if (directLoad) {
  51778. dataCallback(directLoad);
  51779. return;
  51780. }
  51781. if (rootUrl.indexOf("file:") === -1) {
  51782. if (scene.getEngine().enableOfflineSupport) {
  51783. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  51784. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  51785. }
  51786. else {
  51787. manifestChecked(true);
  51788. }
  51789. }
  51790. else {
  51791. var fileOrString = sceneFilename;
  51792. if (fileOrString.name) {
  51793. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  51794. }
  51795. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  51796. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  51797. }
  51798. else {
  51799. onError("Unable to find file named " + sceneFilename);
  51800. return;
  51801. }
  51802. }
  51803. };
  51804. // Public functions
  51805. SceneLoader.GetPluginForExtension = function (extension) {
  51806. return SceneLoader._getPluginForExtension(extension).plugin;
  51807. };
  51808. SceneLoader.RegisterPlugin = function (plugin) {
  51809. if (typeof plugin.extensions === "string") {
  51810. var extension = plugin.extensions;
  51811. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51812. plugin: plugin,
  51813. isBinary: false
  51814. };
  51815. }
  51816. else {
  51817. var extensions = plugin.extensions;
  51818. Object.keys(extensions).forEach(function (extension) {
  51819. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  51820. plugin: plugin,
  51821. isBinary: extensions[extension].isBinary
  51822. };
  51823. });
  51824. }
  51825. };
  51826. /**
  51827. * Import meshes into a scene
  51828. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  51829. * @param rootUrl a string that defines the root url for scene and resources
  51830. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51831. * @param scene the instance of BABYLON.Scene to append to
  51832. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  51833. * @param onProgress a callback with a progress event for each file being loaded
  51834. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51835. */
  51836. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51837. if (onSuccess === void 0) { onSuccess = null; }
  51838. if (onProgress === void 0) { onProgress = null; }
  51839. if (onError === void 0) { onError = null; }
  51840. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51841. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51842. return;
  51843. }
  51844. var loadingToken = {};
  51845. scene._addPendingData(loadingToken);
  51846. var errorHandler = function (message, exception) {
  51847. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51848. if (onError) {
  51849. onError(scene, errorMessage, exception);
  51850. }
  51851. else {
  51852. BABYLON.Tools.Error(errorMessage);
  51853. // should the exception be thrown?
  51854. }
  51855. scene._removePendingData(loadingToken);
  51856. };
  51857. var progressHandler = function (event) {
  51858. if (onProgress) {
  51859. onProgress(event);
  51860. }
  51861. };
  51862. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51863. if (plugin.importMesh) {
  51864. var syncedPlugin = plugin;
  51865. var meshes = new Array();
  51866. var particleSystems = new Array();
  51867. var skeletons = new Array();
  51868. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  51869. return;
  51870. }
  51871. if (onSuccess) {
  51872. // wrap onSuccess with try-catch to know if something went wrong.
  51873. try {
  51874. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51875. onSuccess(meshes, particleSystems, skeletons);
  51876. scene._removePendingData(loadingToken);
  51877. }
  51878. catch (e) {
  51879. var message = 'Error in onSuccess callback.';
  51880. errorHandler(message, e);
  51881. }
  51882. }
  51883. }
  51884. else {
  51885. var asyncedPlugin = plugin;
  51886. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  51887. if (onSuccess) {
  51888. try {
  51889. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  51890. onSuccess(meshes, particleSystems, skeletons);
  51891. scene._removePendingData(loadingToken);
  51892. }
  51893. catch (e) {
  51894. var message = 'Error in onSuccess callback.';
  51895. errorHandler(message, e);
  51896. }
  51897. }
  51898. }, progressHandler, errorHandler);
  51899. }
  51900. }, progressHandler, errorHandler);
  51901. };
  51902. /**
  51903. * Load a scene
  51904. * @param rootUrl a string that defines the root url for scene and resources
  51905. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51906. * @param engine is the instance of BABYLON.Engine to use to create the scene
  51907. * @param onSuccess a callback with the scene when import succeeds
  51908. * @param onProgress a callback with a progress event for each file being loaded
  51909. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51910. */
  51911. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  51912. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  51913. };
  51914. /**
  51915. * Append a scene
  51916. * @param rootUrl a string that defines the root url for scene and resources
  51917. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  51918. * @param scene is the instance of BABYLON.Scene to append to
  51919. * @param onSuccess a callback with the scene when import succeeds
  51920. * @param onProgress a callback with a progress event for each file being loaded
  51921. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  51922. */
  51923. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  51924. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  51925. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  51926. return;
  51927. }
  51928. if (SceneLoader.ShowLoadingScreen) {
  51929. scene.getEngine().displayLoadingUI();
  51930. }
  51931. var loadingToken = {};
  51932. scene._addPendingData(loadingToken);
  51933. var errorHandler = function (message, exception) {
  51934. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  51935. if (onError) {
  51936. onError(scene, errorMessage, exception);
  51937. }
  51938. else {
  51939. BABYLON.Tools.Error(errorMessage);
  51940. // should the exception be thrown?
  51941. }
  51942. scene._removePendingData(loadingToken);
  51943. scene.getEngine().hideLoadingUI();
  51944. };
  51945. var progressHandler = function (event) {
  51946. if (onProgress) {
  51947. onProgress(event);
  51948. }
  51949. };
  51950. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  51951. if (plugin.load) {
  51952. var syncedPlugin = plugin;
  51953. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  51954. return;
  51955. }
  51956. if (onSuccess) {
  51957. try {
  51958. onSuccess(scene);
  51959. }
  51960. catch (e) {
  51961. errorHandler("Error in onSuccess callback", e);
  51962. }
  51963. }
  51964. scene.loadingPluginName = plugin.name;
  51965. scene._removePendingData(loadingToken);
  51966. }
  51967. else {
  51968. var asyncedPlugin = plugin;
  51969. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  51970. if (onSuccess) {
  51971. onSuccess(scene);
  51972. }
  51973. scene.loadingPluginName = plugin.name;
  51974. scene._removePendingData(loadingToken);
  51975. }, progressHandler, errorHandler);
  51976. }
  51977. if (SceneLoader.ShowLoadingScreen) {
  51978. scene.executeWhenReady(function () {
  51979. scene.getEngine().hideLoadingUI();
  51980. });
  51981. }
  51982. }, progressHandler, errorHandler);
  51983. };
  51984. // Flags
  51985. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  51986. SceneLoader._ShowLoadingScreen = true;
  51987. SceneLoader._CleanBoneMatrixWeights = false;
  51988. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  51989. // Members
  51990. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  51991. SceneLoader._registeredPlugins = {};
  51992. return SceneLoader;
  51993. }());
  51994. BABYLON.SceneLoader = SceneLoader;
  51995. ;
  51996. })(BABYLON || (BABYLON = {}));
  51997. //# sourceMappingURL=babylon.sceneLoader.js.map
  51998. var BABYLON;
  51999. (function (BABYLON) {
  52000. var Internals;
  52001. (function (Internals) {
  52002. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52003. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52004. var parsedMaterial = parsedData.materials[index];
  52005. if (parsedMaterial.id === id) {
  52006. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52007. }
  52008. }
  52009. return null;
  52010. };
  52011. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52012. for (var i in names) {
  52013. if (mesh.name === names[i]) {
  52014. hierarchyIds.push(mesh.id);
  52015. return true;
  52016. }
  52017. }
  52018. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52019. hierarchyIds.push(mesh.id);
  52020. return true;
  52021. }
  52022. return false;
  52023. };
  52024. var logOperation = function (operation, producer) {
  52025. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52026. };
  52027. BABYLON.SceneLoader.RegisterPlugin({
  52028. name: "babylon.js",
  52029. extensions: ".babylon",
  52030. canDirectLoad: function (data) {
  52031. if (data.indexOf("babylon") !== -1) {
  52032. return true;
  52033. }
  52034. return false;
  52035. },
  52036. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52037. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52038. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52039. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52040. // and avoid problems with multiple concurrent .babylon loads.
  52041. var log = "importMesh has failed JSON parse";
  52042. try {
  52043. var parsedData = JSON.parse(data);
  52044. log = "";
  52045. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52046. if (!meshesNames) {
  52047. meshesNames = null;
  52048. }
  52049. else if (!Array.isArray(meshesNames)) {
  52050. meshesNames = [meshesNames];
  52051. }
  52052. var hierarchyIds = new Array();
  52053. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52054. var loadedSkeletonsIds = [];
  52055. var loadedMaterialsIds = [];
  52056. var index;
  52057. var cache;
  52058. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52059. var parsedMesh = parsedData.meshes[index];
  52060. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52061. if (meshesNames !== null) {
  52062. // Remove found mesh name from list.
  52063. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52064. }
  52065. //Geometry?
  52066. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52067. //does the file contain geometries?
  52068. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52069. //find the correct geometry and add it to the scene
  52070. var found = false;
  52071. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52072. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52073. return;
  52074. }
  52075. else {
  52076. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52077. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52078. switch (geometryType) {
  52079. case "boxes":
  52080. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52081. break;
  52082. case "spheres":
  52083. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52084. break;
  52085. case "cylinders":
  52086. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52087. break;
  52088. case "toruses":
  52089. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52090. break;
  52091. case "grounds":
  52092. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52093. break;
  52094. case "planes":
  52095. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52096. break;
  52097. case "torusKnots":
  52098. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52099. break;
  52100. case "vertexData":
  52101. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52102. break;
  52103. }
  52104. found = true;
  52105. }
  52106. });
  52107. }
  52108. });
  52109. if (found === false) {
  52110. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52111. }
  52112. }
  52113. }
  52114. // Material ?
  52115. if (parsedMesh.materialId) {
  52116. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52117. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52118. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52119. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52120. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52121. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52122. var subMatId = parsedMultiMaterial.materials[matIndex];
  52123. loadedMaterialsIds.push(subMatId);
  52124. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52125. log += "\n\tMaterial " + mat.toString(fullDetails);
  52126. }
  52127. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52128. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52129. materialFound = true;
  52130. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52131. break;
  52132. }
  52133. }
  52134. }
  52135. if (materialFound === false) {
  52136. loadedMaterialsIds.push(parsedMesh.materialId);
  52137. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52138. if (!mat) {
  52139. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52140. }
  52141. else {
  52142. log += "\n\tMaterial " + mat.toString(fullDetails);
  52143. }
  52144. }
  52145. }
  52146. // Skeleton ?
  52147. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52148. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52149. if (skeletonAlreadyLoaded === false) {
  52150. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52151. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52152. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52153. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52154. skeletons.push(skeleton);
  52155. loadedSkeletonsIds.push(parsedSkeleton.id);
  52156. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52157. }
  52158. }
  52159. }
  52160. }
  52161. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52162. meshes.push(mesh);
  52163. log += "\n\tMesh " + mesh.toString(fullDetails);
  52164. }
  52165. }
  52166. // Connecting parents
  52167. var currentMesh;
  52168. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52169. currentMesh = scene.meshes[index];
  52170. if (currentMesh._waitingParentId) {
  52171. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52172. currentMesh._waitingParentId = null;
  52173. }
  52174. }
  52175. // freeze and compute world matrix application
  52176. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52177. currentMesh = scene.meshes[index];
  52178. if (currentMesh._waitingFreezeWorldMatrix) {
  52179. currentMesh.freezeWorldMatrix();
  52180. currentMesh._waitingFreezeWorldMatrix = null;
  52181. }
  52182. else {
  52183. currentMesh.computeWorldMatrix(true);
  52184. }
  52185. }
  52186. }
  52187. // Particles
  52188. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52189. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52190. var parsedParticleSystem = parsedData.particleSystems[index];
  52191. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52192. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52193. }
  52194. }
  52195. }
  52196. return true;
  52197. }
  52198. catch (err) {
  52199. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52200. if (onError) {
  52201. onError(msg, err);
  52202. }
  52203. else {
  52204. BABYLON.Tools.Log(msg);
  52205. throw err;
  52206. }
  52207. }
  52208. finally {
  52209. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52210. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52211. }
  52212. }
  52213. return false;
  52214. },
  52215. load: function (scene, data, rootUrl, onError) {
  52216. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52217. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52218. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52219. // and avoid problems with multiple concurrent .babylon loads.
  52220. var log = "importScene has failed JSON parse";
  52221. try {
  52222. var parsedData = JSON.parse(data);
  52223. log = "";
  52224. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52225. // Scene
  52226. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52227. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52228. }
  52229. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52230. scene.autoClear = parsedData.autoClear;
  52231. }
  52232. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52233. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52234. }
  52235. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52236. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52237. }
  52238. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52239. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52240. }
  52241. // Fog
  52242. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52243. scene.fogMode = parsedData.fogMode;
  52244. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52245. scene.fogStart = parsedData.fogStart;
  52246. scene.fogEnd = parsedData.fogEnd;
  52247. scene.fogDensity = parsedData.fogDensity;
  52248. log += "\tFog mode for scene: ";
  52249. switch (scene.fogMode) {
  52250. // getters not compiling, so using hardcoded
  52251. case 1:
  52252. log += "exp\n";
  52253. break;
  52254. case 2:
  52255. log += "exp2\n";
  52256. break;
  52257. case 3:
  52258. log += "linear\n";
  52259. break;
  52260. }
  52261. }
  52262. //Physics
  52263. if (parsedData.physicsEnabled) {
  52264. var physicsPlugin;
  52265. if (parsedData.physicsEngine === "cannon") {
  52266. physicsPlugin = new BABYLON.CannonJSPlugin();
  52267. }
  52268. else if (parsedData.physicsEngine === "oimo") {
  52269. physicsPlugin = new BABYLON.OimoJSPlugin();
  52270. }
  52271. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52272. //else - default engine, which is currently oimo
  52273. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52274. scene.enablePhysics(physicsGravity, physicsPlugin);
  52275. }
  52276. // Metadata
  52277. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52278. scene.metadata = parsedData.metadata;
  52279. }
  52280. //collisions, if defined. otherwise, default is true
  52281. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52282. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52283. }
  52284. scene.workerCollisions = !!parsedData.workerCollisions;
  52285. var index;
  52286. var cache;
  52287. // Lights
  52288. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52289. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52290. var parsedLight = parsedData.lights[index];
  52291. var light = BABYLON.Light.Parse(parsedLight, scene);
  52292. if (light) {
  52293. log += (index === 0 ? "\n\tLights:" : "");
  52294. log += "\n\t\t" + light.toString(fullDetails);
  52295. }
  52296. }
  52297. }
  52298. // Animations
  52299. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52300. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52301. var parsedAnimation = parsedData.animations[index];
  52302. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52303. scene.animations.push(animation);
  52304. log += (index === 0 ? "\n\tAnimations:" : "");
  52305. log += "\n\t\t" + animation.toString(fullDetails);
  52306. }
  52307. }
  52308. if (parsedData.autoAnimate) {
  52309. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52310. }
  52311. // Materials
  52312. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52313. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52314. var parsedMaterial = parsedData.materials[index];
  52315. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52316. log += (index === 0 ? "\n\tMaterials:" : "");
  52317. log += "\n\t\t" + mat.toString(fullDetails);
  52318. }
  52319. }
  52320. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52321. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52322. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52323. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52324. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52325. log += "\n\t\t" + mmat.toString(fullDetails);
  52326. }
  52327. }
  52328. // Morph targets
  52329. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52330. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52331. var managerData = _a[_i];
  52332. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52333. }
  52334. }
  52335. // Skeletons
  52336. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52337. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52338. var parsedSkeleton = parsedData.skeletons[index];
  52339. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52340. log += (index === 0 ? "\n\tSkeletons:" : "");
  52341. log += "\n\t\t" + skeleton.toString(fullDetails);
  52342. }
  52343. }
  52344. // Geometries
  52345. var geometries = parsedData.geometries;
  52346. if (geometries !== undefined && geometries !== null) {
  52347. // Boxes
  52348. var boxes = geometries.boxes;
  52349. if (boxes !== undefined && boxes !== null) {
  52350. for (index = 0, cache = boxes.length; index < cache; index++) {
  52351. var parsedBox = boxes[index];
  52352. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52353. }
  52354. }
  52355. // Spheres
  52356. var spheres = geometries.spheres;
  52357. if (spheres !== undefined && spheres !== null) {
  52358. for (index = 0, cache = spheres.length; index < cache; index++) {
  52359. var parsedSphere = spheres[index];
  52360. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52361. }
  52362. }
  52363. // Cylinders
  52364. var cylinders = geometries.cylinders;
  52365. if (cylinders !== undefined && cylinders !== null) {
  52366. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52367. var parsedCylinder = cylinders[index];
  52368. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52369. }
  52370. }
  52371. // Toruses
  52372. var toruses = geometries.toruses;
  52373. if (toruses !== undefined && toruses !== null) {
  52374. for (index = 0, cache = toruses.length; index < cache; index++) {
  52375. var parsedTorus = toruses[index];
  52376. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52377. }
  52378. }
  52379. // Grounds
  52380. var grounds = geometries.grounds;
  52381. if (grounds !== undefined && grounds !== null) {
  52382. for (index = 0, cache = grounds.length; index < cache; index++) {
  52383. var parsedGround = grounds[index];
  52384. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52385. }
  52386. }
  52387. // Planes
  52388. var planes = geometries.planes;
  52389. if (planes !== undefined && planes !== null) {
  52390. for (index = 0, cache = planes.length; index < cache; index++) {
  52391. var parsedPlane = planes[index];
  52392. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52393. }
  52394. }
  52395. // TorusKnots
  52396. var torusKnots = geometries.torusKnots;
  52397. if (torusKnots !== undefined && torusKnots !== null) {
  52398. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52399. var parsedTorusKnot = torusKnots[index];
  52400. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52401. }
  52402. }
  52403. // VertexData
  52404. var vertexData = geometries.vertexData;
  52405. if (vertexData !== undefined && vertexData !== null) {
  52406. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52407. var parsedVertexData = vertexData[index];
  52408. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52409. }
  52410. }
  52411. }
  52412. // Meshes
  52413. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52414. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52415. var parsedMesh = parsedData.meshes[index];
  52416. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52417. log += (index === 0 ? "\n\tMeshes:" : "");
  52418. log += "\n\t\t" + mesh.toString(fullDetails);
  52419. }
  52420. }
  52421. // Cameras
  52422. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52423. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52424. var parsedCamera = parsedData.cameras[index];
  52425. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52426. log += (index === 0 ? "\n\tCameras:" : "");
  52427. log += "\n\t\t" + camera.toString(fullDetails);
  52428. }
  52429. }
  52430. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52431. scene.setActiveCameraByID(parsedData.activeCameraID);
  52432. }
  52433. // Browsing all the graph to connect the dots
  52434. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52435. var camera = scene.cameras[index];
  52436. if (camera._waitingParentId) {
  52437. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52438. camera._waitingParentId = null;
  52439. }
  52440. }
  52441. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52442. var light_1 = scene.lights[index];
  52443. if (light_1 && light_1._waitingParentId) {
  52444. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52445. light_1._waitingParentId = null;
  52446. }
  52447. }
  52448. // Sounds
  52449. var loadedSounds = [];
  52450. var loadedSound;
  52451. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52452. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52453. var parsedSound = parsedData.sounds[index];
  52454. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52455. if (!parsedSound.url)
  52456. parsedSound.url = parsedSound.name;
  52457. if (!loadedSounds[parsedSound.url]) {
  52458. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52459. loadedSounds[parsedSound.url] = loadedSound;
  52460. }
  52461. else {
  52462. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52463. }
  52464. }
  52465. else {
  52466. new BABYLON.Sound(parsedSound.name, null, scene);
  52467. }
  52468. }
  52469. }
  52470. loadedSounds = [];
  52471. // Connect parents & children and parse actions
  52472. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52473. var mesh = scene.meshes[index];
  52474. if (mesh._waitingParentId) {
  52475. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52476. mesh._waitingParentId = null;
  52477. }
  52478. if (mesh._waitingActions) {
  52479. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52480. mesh._waitingActions = null;
  52481. }
  52482. }
  52483. // freeze world matrix application
  52484. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52485. var currentMesh = scene.meshes[index];
  52486. if (currentMesh._waitingFreezeWorldMatrix) {
  52487. currentMesh.freezeWorldMatrix();
  52488. currentMesh._waitingFreezeWorldMatrix = null;
  52489. }
  52490. else {
  52491. currentMesh.computeWorldMatrix(true);
  52492. }
  52493. }
  52494. // Particles Systems
  52495. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52496. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52497. var parsedParticleSystem = parsedData.particleSystems[index];
  52498. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52499. }
  52500. }
  52501. // Environment texture
  52502. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52503. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52504. if (parsedData.createDefaultSkybox === true) {
  52505. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52506. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52507. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52508. }
  52509. }
  52510. // Lens flares
  52511. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52512. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52513. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52514. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52515. }
  52516. }
  52517. // Shadows
  52518. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52519. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52520. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52521. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52522. }
  52523. }
  52524. // Lights exclusions / inclusions
  52525. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52526. var light_2 = scene.lights[index];
  52527. // Excluded check
  52528. if (light_2._excludedMeshesIds.length > 0) {
  52529. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52530. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52531. if (excludedMesh) {
  52532. light_2.excludedMeshes.push(excludedMesh);
  52533. }
  52534. }
  52535. light_2._excludedMeshesIds = [];
  52536. }
  52537. // Included check
  52538. if (light_2._includedOnlyMeshesIds.length > 0) {
  52539. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52540. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52541. if (includedOnlyMesh) {
  52542. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52543. }
  52544. }
  52545. light_2._includedOnlyMeshesIds = [];
  52546. }
  52547. }
  52548. // Actions (scene)
  52549. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52550. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52551. }
  52552. // Finish
  52553. return true;
  52554. }
  52555. catch (err) {
  52556. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52557. if (onError) {
  52558. onError(msg, err);
  52559. }
  52560. else {
  52561. BABYLON.Tools.Log(msg);
  52562. throw err;
  52563. }
  52564. }
  52565. finally {
  52566. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52567. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52568. }
  52569. }
  52570. return false;
  52571. }
  52572. });
  52573. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52574. })(BABYLON || (BABYLON = {}));
  52575. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  52576. var BABYLON;
  52577. (function (BABYLON) {
  52578. var FilesInput = /** @class */ (function () {
  52579. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  52580. this.onProcessFileCallback = function () { return true; };
  52581. this._engine = engine;
  52582. this._currentScene = scene;
  52583. this._sceneLoadedCallback = sceneLoadedCallback;
  52584. this._progressCallback = progressCallback;
  52585. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  52586. this._textureLoadingCallback = textureLoadingCallback;
  52587. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  52588. this._onReloadCallback = onReloadCallback;
  52589. this._errorCallback = errorCallback;
  52590. }
  52591. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  52592. var _this = this;
  52593. if (elementToMonitor) {
  52594. this._elementToMonitor = elementToMonitor;
  52595. this._dragEnterHandler = function (e) { _this.drag(e); };
  52596. this._dragOverHandler = function (e) { _this.drag(e); };
  52597. this._dropHandler = function (e) { _this.drop(e); };
  52598. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  52599. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  52600. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  52601. }
  52602. };
  52603. FilesInput.prototype.dispose = function () {
  52604. if (!this._elementToMonitor) {
  52605. return;
  52606. }
  52607. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  52608. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  52609. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  52610. };
  52611. FilesInput.prototype.renderFunction = function () {
  52612. if (this._additionalRenderLoopLogicCallback) {
  52613. this._additionalRenderLoopLogicCallback();
  52614. }
  52615. if (this._currentScene) {
  52616. if (this._textureLoadingCallback) {
  52617. var remaining = this._currentScene.getWaitingItemsCount();
  52618. if (remaining > 0) {
  52619. this._textureLoadingCallback(remaining);
  52620. }
  52621. }
  52622. this._currentScene.render();
  52623. }
  52624. };
  52625. FilesInput.prototype.drag = function (e) {
  52626. e.stopPropagation();
  52627. e.preventDefault();
  52628. };
  52629. FilesInput.prototype.drop = function (eventDrop) {
  52630. eventDrop.stopPropagation();
  52631. eventDrop.preventDefault();
  52632. this.loadFiles(eventDrop);
  52633. };
  52634. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  52635. var _this = this;
  52636. var reader = folder.createReader();
  52637. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  52638. reader.readEntries(function (entries) {
  52639. remaining.count += entries.length;
  52640. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  52641. var entry = entries_1[_i];
  52642. if (entry.isFile) {
  52643. entry.file(function (file) {
  52644. file.correctName = relativePath + file.name;
  52645. files.push(file);
  52646. if (--remaining.count === 0) {
  52647. callback();
  52648. }
  52649. });
  52650. }
  52651. else if (entry.isDirectory) {
  52652. _this._traverseFolder(entry, files, remaining, callback);
  52653. }
  52654. }
  52655. if (--remaining.count) {
  52656. callback();
  52657. }
  52658. });
  52659. };
  52660. FilesInput.prototype._processFiles = function (files) {
  52661. var skippedFiles = 0;
  52662. for (var i = 0; i < files.length; i++) {
  52663. var name = files[i].correctName.toLowerCase();
  52664. var extension = name.split('.').pop();
  52665. if (!this.onProcessFileCallback(files[i], name, extension)) {
  52666. skippedFiles++;
  52667. continue;
  52668. }
  52669. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  52670. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  52671. this._sceneFileToLoad = files[i];
  52672. }
  52673. else {
  52674. FilesInput.FilesToLoad[name] = files[i];
  52675. }
  52676. }
  52677. if (this._onReloadCallback) {
  52678. this._onReloadCallback(this._sceneFileToLoad);
  52679. }
  52680. else if (skippedFiles < files.length) {
  52681. this.reload();
  52682. }
  52683. };
  52684. FilesInput.prototype.loadFiles = function (event) {
  52685. var _this = this;
  52686. if (this._startingProcessingFilesCallback)
  52687. this._startingProcessingFilesCallback();
  52688. // Handling data transfer via drag'n'drop
  52689. if (event && event.dataTransfer && event.dataTransfer.files) {
  52690. this._filesToLoad = event.dataTransfer.files;
  52691. }
  52692. // Handling files from input files
  52693. if (event && event.target && event.target.files) {
  52694. this._filesToLoad = event.target.files;
  52695. }
  52696. if (this._filesToLoad && this._filesToLoad.length > 0) {
  52697. var files_1 = new Array();
  52698. var folders = [];
  52699. var items = event.dataTransfer ? event.dataTransfer.items : null;
  52700. for (var i = 0; i < this._filesToLoad.length; i++) {
  52701. var fileToLoad = this._filesToLoad[i];
  52702. var name_1 = fileToLoad.name.toLowerCase();
  52703. var entry = void 0;
  52704. fileToLoad.correctName = name_1;
  52705. if (items) {
  52706. var item = items[i];
  52707. if (item.getAsEntry) {
  52708. entry = item.getAsEntry();
  52709. }
  52710. else if (item.webkitGetAsEntry) {
  52711. entry = item.webkitGetAsEntry();
  52712. }
  52713. }
  52714. if (!entry) {
  52715. files_1.push(fileToLoad);
  52716. }
  52717. else {
  52718. if (entry.isDirectory) {
  52719. folders.push(entry);
  52720. }
  52721. else {
  52722. files_1.push(fileToLoad);
  52723. }
  52724. }
  52725. }
  52726. if (folders.length === 0) {
  52727. this._processFiles(files_1);
  52728. }
  52729. else {
  52730. var remaining = { count: folders.length };
  52731. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  52732. var folder = folders_1[_i];
  52733. this._traverseFolder(folder, files_1, remaining, function () {
  52734. _this._processFiles(files_1);
  52735. });
  52736. }
  52737. }
  52738. }
  52739. };
  52740. FilesInput.prototype.reload = function () {
  52741. var _this = this;
  52742. // If a ".babylon" file has been provided
  52743. if (this._sceneFileToLoad) {
  52744. if (this._currentScene) {
  52745. if (BABYLON.Tools.errorsCount > 0) {
  52746. BABYLON.Tools.ClearLogCache();
  52747. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  52748. }
  52749. this._engine.stopRenderLoop();
  52750. this._currentScene.dispose();
  52751. }
  52752. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  52753. _this._currentScene = newScene;
  52754. if (_this._sceneLoadedCallback) {
  52755. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  52756. }
  52757. // Wait for textures and shaders to be ready
  52758. _this._currentScene.executeWhenReady(function () {
  52759. _this._engine.runRenderLoop(function () {
  52760. _this.renderFunction();
  52761. });
  52762. });
  52763. }, function (progress) {
  52764. if (_this._progressCallback) {
  52765. _this._progressCallback(progress);
  52766. }
  52767. }, function (scene, message) {
  52768. _this._currentScene = scene;
  52769. if (_this._errorCallback) {
  52770. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  52771. }
  52772. });
  52773. }
  52774. else {
  52775. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  52776. }
  52777. };
  52778. FilesInput.FilesToLoad = {};
  52779. return FilesInput;
  52780. }());
  52781. BABYLON.FilesInput = FilesInput;
  52782. })(BABYLON || (BABYLON = {}));
  52783. //# sourceMappingURL=babylon.filesInput.js.map
  52784. var BABYLON;
  52785. (function (BABYLON) {
  52786. /**
  52787. * This class implement a typical dictionary using a string as key and the generic type T as value.
  52788. * The underlying implementation relies on an associative array to ensure the best performances.
  52789. * The value can be anything including 'null' but except 'undefined'
  52790. */
  52791. var StringDictionary = /** @class */ (function () {
  52792. function StringDictionary() {
  52793. this._count = 0;
  52794. this._data = {};
  52795. }
  52796. /**
  52797. * This will clear this dictionary and copy the content from the 'source' one.
  52798. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  52799. * @param source the dictionary to take the content from and copy to this dictionary
  52800. */
  52801. StringDictionary.prototype.copyFrom = function (source) {
  52802. var _this = this;
  52803. this.clear();
  52804. source.forEach(function (t, v) { return _this.add(t, v); });
  52805. };
  52806. /**
  52807. * Get a value based from its key
  52808. * @param key the given key to get the matching value from
  52809. * @return the value if found, otherwise undefined is returned
  52810. */
  52811. StringDictionary.prototype.get = function (key) {
  52812. var val = this._data[key];
  52813. if (val !== undefined) {
  52814. return val;
  52815. }
  52816. return undefined;
  52817. };
  52818. /**
  52819. * Get a value from its key or add it if it doesn't exist.
  52820. * This method will ensure you that a given key/data will be present in the dictionary.
  52821. * @param key the given key to get the matching value from
  52822. * @param factory the factory that will create the value if the key is not present in the dictionary.
  52823. * The factory will only be invoked if there's no data for the given key.
  52824. * @return the value corresponding to the key.
  52825. */
  52826. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  52827. var val = this.get(key);
  52828. if (val !== undefined) {
  52829. return val;
  52830. }
  52831. val = factory(key);
  52832. if (val) {
  52833. this.add(key, val);
  52834. }
  52835. return val;
  52836. };
  52837. /**
  52838. * Get a value from its key if present in the dictionary otherwise add it
  52839. * @param key the key to get the value from
  52840. * @param val if there's no such key/value pair in the dictionary add it with this value
  52841. * @return the value corresponding to the key
  52842. */
  52843. StringDictionary.prototype.getOrAdd = function (key, val) {
  52844. var curVal = this.get(key);
  52845. if (curVal !== undefined) {
  52846. return curVal;
  52847. }
  52848. this.add(key, val);
  52849. return val;
  52850. };
  52851. /**
  52852. * Check if there's a given key in the dictionary
  52853. * @param key the key to check for
  52854. * @return true if the key is present, false otherwise
  52855. */
  52856. StringDictionary.prototype.contains = function (key) {
  52857. return this._data[key] !== undefined;
  52858. };
  52859. /**
  52860. * Add a new key and its corresponding value
  52861. * @param key the key to add
  52862. * @param value the value corresponding to the key
  52863. * @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
  52864. */
  52865. StringDictionary.prototype.add = function (key, value) {
  52866. if (this._data[key] !== undefined) {
  52867. return false;
  52868. }
  52869. this._data[key] = value;
  52870. ++this._count;
  52871. return true;
  52872. };
  52873. StringDictionary.prototype.set = function (key, value) {
  52874. if (this._data[key] === undefined) {
  52875. return false;
  52876. }
  52877. this._data[key] = value;
  52878. return true;
  52879. };
  52880. /**
  52881. * Get the element of the given key and remove it from the dictionary
  52882. * @param key
  52883. */
  52884. StringDictionary.prototype.getAndRemove = function (key) {
  52885. var val = this.get(key);
  52886. if (val !== undefined) {
  52887. delete this._data[key];
  52888. --this._count;
  52889. return val;
  52890. }
  52891. return null;
  52892. };
  52893. /**
  52894. * Remove a key/value from the dictionary.
  52895. * @param key the key to remove
  52896. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  52897. */
  52898. StringDictionary.prototype.remove = function (key) {
  52899. if (this.contains(key)) {
  52900. delete this._data[key];
  52901. --this._count;
  52902. return true;
  52903. }
  52904. return false;
  52905. };
  52906. /**
  52907. * Clear the whole content of the dictionary
  52908. */
  52909. StringDictionary.prototype.clear = function () {
  52910. this._data = {};
  52911. this._count = 0;
  52912. };
  52913. Object.defineProperty(StringDictionary.prototype, "count", {
  52914. get: function () {
  52915. return this._count;
  52916. },
  52917. enumerable: true,
  52918. configurable: true
  52919. });
  52920. /**
  52921. * Execute a callback on each key/val of the dictionary.
  52922. * Note that you can remove any element in this dictionary in the callback implementation
  52923. * @param callback the callback to execute on a given key/value pair
  52924. */
  52925. StringDictionary.prototype.forEach = function (callback) {
  52926. for (var cur in this._data) {
  52927. var val = this._data[cur];
  52928. callback(cur, val);
  52929. }
  52930. };
  52931. /**
  52932. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  52933. * If the callback returns null or undefined the method will iterate to the next key/value pair
  52934. * Note that you can remove any element in this dictionary in the callback implementation
  52935. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  52936. */
  52937. StringDictionary.prototype.first = function (callback) {
  52938. for (var cur in this._data) {
  52939. var val = this._data[cur];
  52940. var res = callback(cur, val);
  52941. if (res) {
  52942. return res;
  52943. }
  52944. }
  52945. return null;
  52946. };
  52947. return StringDictionary;
  52948. }());
  52949. BABYLON.StringDictionary = StringDictionary;
  52950. })(BABYLON || (BABYLON = {}));
  52951. //# sourceMappingURL=babylon.stringDictionary.js.map
  52952. var BABYLON;
  52953. (function (BABYLON) {
  52954. var Tags = /** @class */ (function () {
  52955. function Tags() {
  52956. }
  52957. Tags.EnableFor = function (obj) {
  52958. obj._tags = obj._tags || {};
  52959. obj.hasTags = function () {
  52960. return Tags.HasTags(obj);
  52961. };
  52962. obj.addTags = function (tagsString) {
  52963. return Tags.AddTagsTo(obj, tagsString);
  52964. };
  52965. obj.removeTags = function (tagsString) {
  52966. return Tags.RemoveTagsFrom(obj, tagsString);
  52967. };
  52968. obj.matchesTagsQuery = function (tagsQuery) {
  52969. return Tags.MatchesQuery(obj, tagsQuery);
  52970. };
  52971. };
  52972. Tags.DisableFor = function (obj) {
  52973. delete obj._tags;
  52974. delete obj.hasTags;
  52975. delete obj.addTags;
  52976. delete obj.removeTags;
  52977. delete obj.matchesTagsQuery;
  52978. };
  52979. Tags.HasTags = function (obj) {
  52980. if (!obj._tags) {
  52981. return false;
  52982. }
  52983. return !BABYLON.Tools.IsEmpty(obj._tags);
  52984. };
  52985. Tags.GetTags = function (obj, asString) {
  52986. if (asString === void 0) { asString = true; }
  52987. if (!obj._tags) {
  52988. return null;
  52989. }
  52990. if (asString) {
  52991. var tagsArray = [];
  52992. for (var tag in obj._tags) {
  52993. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  52994. tagsArray.push(tag);
  52995. }
  52996. }
  52997. return tagsArray.join(" ");
  52998. }
  52999. else {
  53000. return obj._tags;
  53001. }
  53002. };
  53003. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53004. // a tag cannot start with '||', '&&', and '!'
  53005. // it cannot contain whitespaces
  53006. Tags.AddTagsTo = function (obj, tagsString) {
  53007. if (!tagsString) {
  53008. return;
  53009. }
  53010. if (typeof tagsString !== "string") {
  53011. return;
  53012. }
  53013. var tags = tagsString.split(" ");
  53014. tags.forEach(function (tag, index, array) {
  53015. Tags._AddTagTo(obj, tag);
  53016. });
  53017. };
  53018. Tags._AddTagTo = function (obj, tag) {
  53019. tag = tag.trim();
  53020. if (tag === "" || tag === "true" || tag === "false") {
  53021. return;
  53022. }
  53023. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53024. return;
  53025. }
  53026. Tags.EnableFor(obj);
  53027. obj._tags[tag] = true;
  53028. };
  53029. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53030. if (!Tags.HasTags(obj)) {
  53031. return;
  53032. }
  53033. var tags = tagsString.split(" ");
  53034. for (var t in tags) {
  53035. Tags._RemoveTagFrom(obj, tags[t]);
  53036. }
  53037. };
  53038. Tags._RemoveTagFrom = function (obj, tag) {
  53039. delete obj._tags[tag];
  53040. };
  53041. Tags.MatchesQuery = function (obj, tagsQuery) {
  53042. if (tagsQuery === undefined) {
  53043. return true;
  53044. }
  53045. if (tagsQuery === "") {
  53046. return Tags.HasTags(obj);
  53047. }
  53048. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53049. };
  53050. return Tags;
  53051. }());
  53052. BABYLON.Tags = Tags;
  53053. })(BABYLON || (BABYLON = {}));
  53054. //# sourceMappingURL=babylon.tags.js.map
  53055. var BABYLON;
  53056. (function (BABYLON) {
  53057. var Internals;
  53058. (function (Internals) {
  53059. var AndOrNotEvaluator = /** @class */ (function () {
  53060. function AndOrNotEvaluator() {
  53061. }
  53062. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53063. if (!query.match(/\([^\(\)]*\)/g)) {
  53064. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53065. }
  53066. else {
  53067. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53068. // remove parenthesis
  53069. r = r.slice(1, r.length - 1);
  53070. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53071. });
  53072. }
  53073. if (query === "true") {
  53074. return true;
  53075. }
  53076. if (query === "false") {
  53077. return false;
  53078. }
  53079. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53080. };
  53081. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53082. evaluateCallback = evaluateCallback || (function (r) {
  53083. return r === "true" ? true : false;
  53084. });
  53085. var result;
  53086. var or = parenthesisContent.split("||");
  53087. for (var i in or) {
  53088. if (or.hasOwnProperty(i)) {
  53089. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53090. var and = ori.split("&&");
  53091. if (and.length > 1) {
  53092. for (var j = 0; j < and.length; ++j) {
  53093. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53094. if (andj !== "true" && andj !== "false") {
  53095. if (andj[0] === "!") {
  53096. result = !evaluateCallback(andj.substring(1));
  53097. }
  53098. else {
  53099. result = evaluateCallback(andj);
  53100. }
  53101. }
  53102. else {
  53103. result = andj === "true" ? true : false;
  53104. }
  53105. if (!result) {
  53106. ori = "false";
  53107. break;
  53108. }
  53109. }
  53110. }
  53111. if (result || ori === "true") {
  53112. result = true;
  53113. break;
  53114. }
  53115. // result equals false (or undefined)
  53116. if (ori !== "true" && ori !== "false") {
  53117. if (ori[0] === "!") {
  53118. result = !evaluateCallback(ori.substring(1));
  53119. }
  53120. else {
  53121. result = evaluateCallback(ori);
  53122. }
  53123. }
  53124. else {
  53125. result = ori === "true" ? true : false;
  53126. }
  53127. }
  53128. }
  53129. // the whole parenthesis scope is replaced by 'true' or 'false'
  53130. return result ? "true" : "false";
  53131. };
  53132. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53133. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53134. // remove whitespaces
  53135. r = r.replace(/[\s]/g, function () { return ""; });
  53136. return r.length % 2 ? "!" : "";
  53137. });
  53138. booleanString = booleanString.trim();
  53139. if (booleanString === "!true") {
  53140. booleanString = "false";
  53141. }
  53142. else if (booleanString === "!false") {
  53143. booleanString = "true";
  53144. }
  53145. return booleanString;
  53146. };
  53147. return AndOrNotEvaluator;
  53148. }());
  53149. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53150. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53151. })(BABYLON || (BABYLON = {}));
  53152. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53153. var BABYLON;
  53154. (function (BABYLON) {
  53155. var Database = /** @class */ (function () {
  53156. function Database(urlToScene, callbackManifestChecked) {
  53157. // Handling various flavors of prefixed version of IndexedDB
  53158. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53159. this.callbackManifestChecked = callbackManifestChecked;
  53160. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53161. this.db = null;
  53162. this._enableSceneOffline = false;
  53163. this._enableTexturesOffline = false;
  53164. this.manifestVersionFound = 0;
  53165. this.mustUpdateRessources = false;
  53166. this.hasReachedQuota = false;
  53167. if (!Database.IDBStorageEnabled) {
  53168. this.callbackManifestChecked(true);
  53169. }
  53170. else {
  53171. this.checkManifestFile();
  53172. }
  53173. }
  53174. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53175. get: function () {
  53176. return this._enableSceneOffline;
  53177. },
  53178. enumerable: true,
  53179. configurable: true
  53180. });
  53181. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53182. get: function () {
  53183. return this._enableTexturesOffline;
  53184. },
  53185. enumerable: true,
  53186. configurable: true
  53187. });
  53188. Database.prototype.checkManifestFile = function () {
  53189. var _this = this;
  53190. var noManifestFile = function () {
  53191. _this._enableSceneOffline = false;
  53192. _this._enableTexturesOffline = false;
  53193. _this.callbackManifestChecked(false);
  53194. };
  53195. var timeStampUsed = false;
  53196. var manifestURL = this.currentSceneUrl + ".manifest";
  53197. var xhr = new XMLHttpRequest();
  53198. if (navigator.onLine) {
  53199. // Adding a timestamp to by-pass browsers' cache
  53200. timeStampUsed = true;
  53201. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53202. }
  53203. xhr.open("GET", manifestURL, true);
  53204. xhr.addEventListener("load", function () {
  53205. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53206. try {
  53207. var manifestFile = JSON.parse(xhr.response);
  53208. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53209. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53210. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53211. _this.manifestVersionFound = manifestFile.version;
  53212. }
  53213. if (_this.callbackManifestChecked) {
  53214. _this.callbackManifestChecked(true);
  53215. }
  53216. }
  53217. catch (ex) {
  53218. noManifestFile();
  53219. }
  53220. }
  53221. else {
  53222. noManifestFile();
  53223. }
  53224. }, false);
  53225. xhr.addEventListener("error", function (event) {
  53226. if (timeStampUsed) {
  53227. timeStampUsed = false;
  53228. // Let's retry without the timeStamp
  53229. // It could fail when coupled with HTML5 Offline API
  53230. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53231. xhr.open("GET", retryManifestURL, true);
  53232. xhr.send();
  53233. }
  53234. else {
  53235. noManifestFile();
  53236. }
  53237. }, false);
  53238. try {
  53239. xhr.send();
  53240. }
  53241. catch (ex) {
  53242. BABYLON.Tools.Error("Error on XHR send request.");
  53243. this.callbackManifestChecked(false);
  53244. }
  53245. };
  53246. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53247. var _this = this;
  53248. var handleError = function () {
  53249. _this.isSupported = false;
  53250. if (errorCallback)
  53251. errorCallback();
  53252. };
  53253. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53254. // Your browser doesn't support IndexedDB
  53255. this.isSupported = false;
  53256. if (errorCallback)
  53257. errorCallback();
  53258. }
  53259. else {
  53260. // If the DB hasn't been opened or created yet
  53261. if (!this.db) {
  53262. this.hasReachedQuota = false;
  53263. this.isSupported = true;
  53264. var request = this.idbFactory.open("babylonjs", 1);
  53265. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53266. request.onerror = function (event) {
  53267. handleError();
  53268. };
  53269. // executes when a version change transaction cannot complete due to other active transactions
  53270. request.onblocked = function (event) {
  53271. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53272. handleError();
  53273. };
  53274. // DB has been opened successfully
  53275. request.onsuccess = function (event) {
  53276. _this.db = request.result;
  53277. successCallback();
  53278. };
  53279. // Initialization of the DB. Creating Scenes & Textures stores
  53280. request.onupgradeneeded = function (event) {
  53281. _this.db = (event.target).result;
  53282. if (_this.db) {
  53283. try {
  53284. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53285. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53286. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53287. }
  53288. catch (ex) {
  53289. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53290. handleError();
  53291. }
  53292. }
  53293. };
  53294. }
  53295. else {
  53296. if (successCallback)
  53297. successCallback();
  53298. }
  53299. }
  53300. };
  53301. Database.prototype.loadImageFromDB = function (url, image) {
  53302. var _this = this;
  53303. var completeURL = Database.ReturnFullUrlLocation(url);
  53304. var saveAndLoadImage = function () {
  53305. if (!_this.hasReachedQuota && _this.db !== null) {
  53306. // the texture is not yet in the DB, let's try to save it
  53307. _this._saveImageIntoDBAsync(completeURL, image);
  53308. }
  53309. else {
  53310. image.src = url;
  53311. }
  53312. };
  53313. if (!this.mustUpdateRessources) {
  53314. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53315. }
  53316. else {
  53317. saveAndLoadImage();
  53318. }
  53319. };
  53320. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53321. if (this.isSupported && this.db !== null) {
  53322. var texture;
  53323. var transaction = this.db.transaction(["textures"]);
  53324. transaction.onabort = function (event) {
  53325. image.src = url;
  53326. };
  53327. transaction.oncomplete = function (event) {
  53328. var blobTextureURL;
  53329. if (texture) {
  53330. var URL = window.URL || window.webkitURL;
  53331. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53332. image.onerror = function () {
  53333. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53334. image.src = url;
  53335. };
  53336. image.src = blobTextureURL;
  53337. }
  53338. else {
  53339. notInDBCallback();
  53340. }
  53341. };
  53342. var getRequest = transaction.objectStore("textures").get(url);
  53343. getRequest.onsuccess = function (event) {
  53344. texture = (event.target).result;
  53345. };
  53346. getRequest.onerror = function (event) {
  53347. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53348. image.src = url;
  53349. };
  53350. }
  53351. else {
  53352. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53353. image.src = url;
  53354. }
  53355. };
  53356. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53357. var _this = this;
  53358. if (this.isSupported) {
  53359. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53360. var generateBlobUrl = function () {
  53361. var blobTextureURL;
  53362. if (blob) {
  53363. var URL = window.URL || window.webkitURL;
  53364. try {
  53365. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53366. }
  53367. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53368. catch (ex) {
  53369. blobTextureURL = URL.createObjectURL(blob);
  53370. }
  53371. }
  53372. if (blobTextureURL) {
  53373. image.src = blobTextureURL;
  53374. }
  53375. };
  53376. if (Database.IsUASupportingBlobStorage) {
  53377. var xhr = new XMLHttpRequest(), blob;
  53378. xhr.open("GET", url, true);
  53379. xhr.responseType = "blob";
  53380. xhr.addEventListener("load", function () {
  53381. if (xhr.status === 200 && _this.db) {
  53382. // Blob as response (XHR2)
  53383. blob = xhr.response;
  53384. var transaction = _this.db.transaction(["textures"], "readwrite");
  53385. // the transaction could abort because of a QuotaExceededError error
  53386. transaction.onabort = function (event) {
  53387. try {
  53388. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53389. var srcElement = (event.srcElement || event.target);
  53390. var error = srcElement.error;
  53391. if (error && error.name === "QuotaExceededError") {
  53392. _this.hasReachedQuota = true;
  53393. }
  53394. }
  53395. catch (ex) { }
  53396. generateBlobUrl();
  53397. };
  53398. transaction.oncomplete = function (event) {
  53399. generateBlobUrl();
  53400. };
  53401. var newTexture = { textureUrl: url, data: blob };
  53402. try {
  53403. // Put the blob into the dabase
  53404. var addRequest = transaction.objectStore("textures").put(newTexture);
  53405. addRequest.onsuccess = function (event) {
  53406. };
  53407. addRequest.onerror = function (event) {
  53408. generateBlobUrl();
  53409. };
  53410. }
  53411. catch (ex) {
  53412. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53413. if (ex.code === 25) {
  53414. Database.IsUASupportingBlobStorage = false;
  53415. }
  53416. image.src = url;
  53417. }
  53418. }
  53419. else {
  53420. image.src = url;
  53421. }
  53422. }, false);
  53423. xhr.addEventListener("error", function (event) {
  53424. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53425. image.src = url;
  53426. }, false);
  53427. xhr.send();
  53428. }
  53429. else {
  53430. image.src = url;
  53431. }
  53432. }
  53433. else {
  53434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53435. image.src = url;
  53436. }
  53437. };
  53438. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53439. var _this = this;
  53440. var updateVersion = function () {
  53441. // the version is not yet in the DB or we need to update it
  53442. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53443. };
  53444. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53445. };
  53446. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53447. var _this = this;
  53448. if (this.isSupported && this.db) {
  53449. var version;
  53450. try {
  53451. var transaction = this.db.transaction(["versions"]);
  53452. transaction.oncomplete = function (event) {
  53453. if (version) {
  53454. // If the version in the JSON file is > than the version in DB
  53455. if (_this.manifestVersionFound > version.data) {
  53456. _this.mustUpdateRessources = true;
  53457. updateInDBCallback();
  53458. }
  53459. else {
  53460. callback(version.data);
  53461. }
  53462. }
  53463. else {
  53464. _this.mustUpdateRessources = true;
  53465. updateInDBCallback();
  53466. }
  53467. };
  53468. transaction.onabort = function (event) {
  53469. callback(-1);
  53470. };
  53471. var getRequest = transaction.objectStore("versions").get(url);
  53472. getRequest.onsuccess = function (event) {
  53473. version = (event.target).result;
  53474. };
  53475. getRequest.onerror = function (event) {
  53476. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53477. callback(-1);
  53478. };
  53479. }
  53480. catch (ex) {
  53481. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53482. callback(-1);
  53483. }
  53484. }
  53485. else {
  53486. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53487. callback(-1);
  53488. }
  53489. };
  53490. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53491. var _this = this;
  53492. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53493. try {
  53494. // Open a transaction to the database
  53495. var transaction = this.db.transaction(["versions"], "readwrite");
  53496. // the transaction could abort because of a QuotaExceededError error
  53497. transaction.onabort = function (event) {
  53498. try {
  53499. var error = event.srcElement['error'];
  53500. if (error && error.name === "QuotaExceededError") {
  53501. _this.hasReachedQuota = true;
  53502. }
  53503. }
  53504. catch (ex) { }
  53505. callback(-1);
  53506. };
  53507. transaction.oncomplete = function (event) {
  53508. callback(_this.manifestVersionFound);
  53509. };
  53510. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53511. // Put the scene into the database
  53512. var addRequest = transaction.objectStore("versions").put(newVersion);
  53513. addRequest.onsuccess = function (event) {
  53514. };
  53515. addRequest.onerror = function (event) {
  53516. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53517. };
  53518. }
  53519. catch (ex) {
  53520. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53521. callback(-1);
  53522. }
  53523. }
  53524. else {
  53525. callback(-1);
  53526. }
  53527. };
  53528. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53529. var _this = this;
  53530. var completeUrl = Database.ReturnFullUrlLocation(url);
  53531. var saveAndLoadFile = function () {
  53532. // the scene is not yet in the DB, let's try to save it
  53533. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53534. };
  53535. this._checkVersionFromDB(completeUrl, function (version) {
  53536. if (version !== -1) {
  53537. if (!_this.mustUpdateRessources) {
  53538. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53539. }
  53540. else {
  53541. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53542. }
  53543. }
  53544. else {
  53545. if (errorCallback) {
  53546. errorCallback();
  53547. }
  53548. }
  53549. });
  53550. };
  53551. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53552. if (this.isSupported && this.db) {
  53553. var targetStore;
  53554. if (url.indexOf(".babylon") !== -1) {
  53555. targetStore = "scenes";
  53556. }
  53557. else {
  53558. targetStore = "textures";
  53559. }
  53560. var file;
  53561. var transaction = this.db.transaction([targetStore]);
  53562. transaction.oncomplete = function (event) {
  53563. if (file) {
  53564. callback(file.data);
  53565. }
  53566. else {
  53567. notInDBCallback();
  53568. }
  53569. };
  53570. transaction.onabort = function (event) {
  53571. notInDBCallback();
  53572. };
  53573. var getRequest = transaction.objectStore(targetStore).get(url);
  53574. getRequest.onsuccess = function (event) {
  53575. file = (event.target).result;
  53576. };
  53577. getRequest.onerror = function (event) {
  53578. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  53579. notInDBCallback();
  53580. };
  53581. }
  53582. else {
  53583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53584. callback();
  53585. }
  53586. };
  53587. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  53588. var _this = this;
  53589. if (this.isSupported) {
  53590. var targetStore;
  53591. if (url.indexOf(".babylon") !== -1) {
  53592. targetStore = "scenes";
  53593. }
  53594. else {
  53595. targetStore = "textures";
  53596. }
  53597. // Create XHR
  53598. var xhr = new XMLHttpRequest();
  53599. var fileData;
  53600. xhr.open("GET", url, true);
  53601. if (useArrayBuffer) {
  53602. xhr.responseType = "arraybuffer";
  53603. }
  53604. if (progressCallback) {
  53605. xhr.onprogress = progressCallback;
  53606. }
  53607. xhr.addEventListener("load", function () {
  53608. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  53609. // Blob as response (XHR2)
  53610. //fileData = xhr.responseText;
  53611. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  53612. if (!_this.hasReachedQuota && _this.db) {
  53613. // Open a transaction to the database
  53614. var transaction = _this.db.transaction([targetStore], "readwrite");
  53615. // the transaction could abort because of a QuotaExceededError error
  53616. transaction.onabort = function (event) {
  53617. try {
  53618. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53619. var error = event.srcElement['error'];
  53620. if (error && error.name === "QuotaExceededError") {
  53621. _this.hasReachedQuota = true;
  53622. }
  53623. }
  53624. catch (ex) { }
  53625. callback(fileData);
  53626. };
  53627. transaction.oncomplete = function (event) {
  53628. callback(fileData);
  53629. };
  53630. var newFile;
  53631. if (targetStore === "scenes") {
  53632. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  53633. }
  53634. else {
  53635. newFile = { textureUrl: url, data: fileData };
  53636. }
  53637. try {
  53638. // Put the scene into the database
  53639. var addRequest = transaction.objectStore(targetStore).put(newFile);
  53640. addRequest.onsuccess = function (event) {
  53641. };
  53642. addRequest.onerror = function (event) {
  53643. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  53644. };
  53645. }
  53646. catch (ex) {
  53647. callback(fileData);
  53648. }
  53649. }
  53650. else {
  53651. callback(fileData);
  53652. }
  53653. }
  53654. else {
  53655. callback();
  53656. }
  53657. }, false);
  53658. xhr.addEventListener("error", function (event) {
  53659. BABYLON.Tools.Error("error on XHR request.");
  53660. callback();
  53661. }, false);
  53662. xhr.send();
  53663. }
  53664. else {
  53665. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53666. callback();
  53667. }
  53668. };
  53669. Database.IsUASupportingBlobStorage = true;
  53670. Database.IDBStorageEnabled = true;
  53671. Database.parseURL = function (url) {
  53672. var a = document.createElement('a');
  53673. a.href = url;
  53674. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  53675. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  53676. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  53677. return absLocation;
  53678. };
  53679. Database.ReturnFullUrlLocation = function (url) {
  53680. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  53681. return (Database.parseURL(window.location.href) + url);
  53682. }
  53683. else {
  53684. return url;
  53685. }
  53686. };
  53687. return Database;
  53688. }());
  53689. BABYLON.Database = Database;
  53690. })(BABYLON || (BABYLON = {}));
  53691. //# sourceMappingURL=babylon.database.js.map
  53692. var BABYLON;
  53693. (function (BABYLON) {
  53694. var FresnelParameters = /** @class */ (function () {
  53695. function FresnelParameters() {
  53696. this._isEnabled = true;
  53697. this.leftColor = BABYLON.Color3.White();
  53698. this.rightColor = BABYLON.Color3.Black();
  53699. this.bias = 0;
  53700. this.power = 1;
  53701. }
  53702. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  53703. get: function () {
  53704. return this._isEnabled;
  53705. },
  53706. set: function (value) {
  53707. if (this._isEnabled === value) {
  53708. return;
  53709. }
  53710. this._isEnabled = value;
  53711. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  53712. },
  53713. enumerable: true,
  53714. configurable: true
  53715. });
  53716. FresnelParameters.prototype.clone = function () {
  53717. var newFresnelParameters = new FresnelParameters();
  53718. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  53719. return newFresnelParameters;
  53720. };
  53721. FresnelParameters.prototype.serialize = function () {
  53722. var serializationObject = {};
  53723. serializationObject.isEnabled = this.isEnabled;
  53724. serializationObject.leftColor = this.leftColor;
  53725. serializationObject.rightColor = this.rightColor;
  53726. serializationObject.bias = this.bias;
  53727. serializationObject.power = this.power;
  53728. return serializationObject;
  53729. };
  53730. FresnelParameters.Parse = function (parsedFresnelParameters) {
  53731. var fresnelParameters = new FresnelParameters();
  53732. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  53733. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  53734. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  53735. fresnelParameters.bias = parsedFresnelParameters.bias;
  53736. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  53737. return fresnelParameters;
  53738. };
  53739. return FresnelParameters;
  53740. }());
  53741. BABYLON.FresnelParameters = FresnelParameters;
  53742. })(BABYLON || (BABYLON = {}));
  53743. //# sourceMappingURL=babylon.fresnelParameters.js.map
  53744. var BABYLON;
  53745. (function (BABYLON) {
  53746. var MultiMaterial = /** @class */ (function (_super) {
  53747. __extends(MultiMaterial, _super);
  53748. function MultiMaterial(name, scene) {
  53749. var _this = _super.call(this, name, scene, true) || this;
  53750. scene.multiMaterials.push(_this);
  53751. _this.subMaterials = new Array();
  53752. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  53753. return _this;
  53754. }
  53755. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  53756. get: function () {
  53757. return this._subMaterials;
  53758. },
  53759. set: function (value) {
  53760. this._subMaterials = value;
  53761. this._hookArray(value);
  53762. },
  53763. enumerable: true,
  53764. configurable: true
  53765. });
  53766. MultiMaterial.prototype._hookArray = function (array) {
  53767. var _this = this;
  53768. var oldPush = array.push;
  53769. array.push = function () {
  53770. var items = [];
  53771. for (var _i = 0; _i < arguments.length; _i++) {
  53772. items[_i] = arguments[_i];
  53773. }
  53774. var result = oldPush.apply(array, items);
  53775. _this._markAllSubMeshesAsTexturesDirty();
  53776. return result;
  53777. };
  53778. var oldSplice = array.splice;
  53779. array.splice = function (index, deleteCount) {
  53780. var deleted = oldSplice.apply(array, [index, deleteCount]);
  53781. _this._markAllSubMeshesAsTexturesDirty();
  53782. return deleted;
  53783. };
  53784. };
  53785. // Properties
  53786. MultiMaterial.prototype.getSubMaterial = function (index) {
  53787. if (index < 0 || index >= this.subMaterials.length) {
  53788. return this.getScene().defaultMaterial;
  53789. }
  53790. return this.subMaterials[index];
  53791. };
  53792. MultiMaterial.prototype.getActiveTextures = function () {
  53793. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  53794. if (subMaterial) {
  53795. return subMaterial.getActiveTextures();
  53796. }
  53797. else {
  53798. return [];
  53799. }
  53800. }));
  53801. var _a;
  53802. };
  53803. // Methods
  53804. MultiMaterial.prototype.getClassName = function () {
  53805. return "MultiMaterial";
  53806. };
  53807. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  53808. for (var index = 0; index < this.subMaterials.length; index++) {
  53809. var subMaterial = this.subMaterials[index];
  53810. if (subMaterial) {
  53811. if (subMaterial.storeEffectOnSubMeshes) {
  53812. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  53813. return false;
  53814. }
  53815. continue;
  53816. }
  53817. if (!subMaterial.isReady(mesh)) {
  53818. return false;
  53819. }
  53820. }
  53821. }
  53822. return true;
  53823. };
  53824. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  53825. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  53826. for (var index = 0; index < this.subMaterials.length; index++) {
  53827. var subMaterial = null;
  53828. var current = this.subMaterials[index];
  53829. if (cloneChildren && current) {
  53830. subMaterial = current.clone(name + "-" + current.name);
  53831. }
  53832. else {
  53833. subMaterial = this.subMaterials[index];
  53834. }
  53835. newMultiMaterial.subMaterials.push(subMaterial);
  53836. }
  53837. return newMultiMaterial;
  53838. };
  53839. MultiMaterial.prototype.serialize = function () {
  53840. var serializationObject = {};
  53841. serializationObject.name = this.name;
  53842. serializationObject.id = this.id;
  53843. serializationObject.tags = BABYLON.Tags.GetTags(this);
  53844. serializationObject.materials = [];
  53845. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  53846. var subMat = this.subMaterials[matIndex];
  53847. if (subMat) {
  53848. serializationObject.materials.push(subMat.id);
  53849. }
  53850. else {
  53851. serializationObject.materials.push(null);
  53852. }
  53853. }
  53854. return serializationObject;
  53855. };
  53856. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53857. var scene = this.getScene();
  53858. if (!scene) {
  53859. return;
  53860. }
  53861. var index = scene.multiMaterials.indexOf(this);
  53862. if (index >= 0) {
  53863. scene.multiMaterials.splice(index, 1);
  53864. }
  53865. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53866. };
  53867. return MultiMaterial;
  53868. }(BABYLON.Material));
  53869. BABYLON.MultiMaterial = MultiMaterial;
  53870. })(BABYLON || (BABYLON = {}));
  53871. //# sourceMappingURL=babylon.multiMaterial.js.map
  53872. var BABYLON;
  53873. (function (BABYLON) {
  53874. var FreeCameraTouchInput = /** @class */ (function () {
  53875. function FreeCameraTouchInput() {
  53876. this._offsetX = null;
  53877. this._offsetY = null;
  53878. this._pointerCount = 0;
  53879. this._pointerPressed = new Array();
  53880. this.touchAngularSensibility = 200000.0;
  53881. this.touchMoveSensibility = 250.0;
  53882. }
  53883. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  53884. var _this = this;
  53885. var previousPosition = null;
  53886. if (this._pointerInput === undefined) {
  53887. this._onLostFocus = function (evt) {
  53888. _this._offsetX = null;
  53889. _this._offsetY = null;
  53890. };
  53891. this._pointerInput = function (p, s) {
  53892. var evt = p.event;
  53893. if (evt.pointerType === "mouse") {
  53894. return;
  53895. }
  53896. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  53897. if (!noPreventDefault) {
  53898. evt.preventDefault();
  53899. }
  53900. _this._pointerPressed.push(evt.pointerId);
  53901. if (_this._pointerPressed.length !== 1) {
  53902. return;
  53903. }
  53904. previousPosition = {
  53905. x: evt.clientX,
  53906. y: evt.clientY
  53907. };
  53908. }
  53909. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  53910. if (!noPreventDefault) {
  53911. evt.preventDefault();
  53912. }
  53913. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53914. if (index === -1) {
  53915. return;
  53916. }
  53917. _this._pointerPressed.splice(index, 1);
  53918. if (index != 0) {
  53919. return;
  53920. }
  53921. previousPosition = null;
  53922. _this._offsetX = null;
  53923. _this._offsetY = null;
  53924. }
  53925. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  53926. if (!noPreventDefault) {
  53927. evt.preventDefault();
  53928. }
  53929. if (!previousPosition) {
  53930. return;
  53931. }
  53932. var index = _this._pointerPressed.indexOf(evt.pointerId);
  53933. if (index != 0) {
  53934. return;
  53935. }
  53936. _this._offsetX = evt.clientX - previousPosition.x;
  53937. _this._offsetY = -(evt.clientY - previousPosition.y);
  53938. }
  53939. };
  53940. }
  53941. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  53942. if (this._onLostFocus) {
  53943. element.addEventListener("blur", this._onLostFocus);
  53944. }
  53945. };
  53946. FreeCameraTouchInput.prototype.detachControl = function (element) {
  53947. if (this._pointerInput && element) {
  53948. if (this._observer) {
  53949. this.camera.getScene().onPointerObservable.remove(this._observer);
  53950. this._observer = null;
  53951. }
  53952. if (this._onLostFocus) {
  53953. element.removeEventListener("blur", this._onLostFocus);
  53954. this._onLostFocus = null;
  53955. }
  53956. this._pointerPressed = [];
  53957. this._offsetX = null;
  53958. this._offsetY = null;
  53959. this._pointerCount = 0;
  53960. }
  53961. };
  53962. FreeCameraTouchInput.prototype.checkInputs = function () {
  53963. if (this._offsetX && this._offsetY) {
  53964. var camera = this.camera;
  53965. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  53966. if (this._pointerPressed.length > 1) {
  53967. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  53968. }
  53969. else {
  53970. var speed = camera._computeLocalCameraSpeed();
  53971. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  53972. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  53973. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  53974. }
  53975. }
  53976. };
  53977. FreeCameraTouchInput.prototype.getClassName = function () {
  53978. return "FreeCameraTouchInput";
  53979. };
  53980. FreeCameraTouchInput.prototype.getSimpleName = function () {
  53981. return "touch";
  53982. };
  53983. __decorate([
  53984. BABYLON.serialize()
  53985. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  53986. __decorate([
  53987. BABYLON.serialize()
  53988. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  53989. return FreeCameraTouchInput;
  53990. }());
  53991. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  53992. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  53993. })(BABYLON || (BABYLON = {}));
  53994. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  53995. var BABYLON;
  53996. (function (BABYLON) {
  53997. // We're mainly based on the logic defined into the FreeCamera code
  53998. var TouchCamera = /** @class */ (function (_super) {
  53999. __extends(TouchCamera, _super);
  54000. //-- end properties for backward compatibility for inputs
  54001. function TouchCamera(name, position, scene) {
  54002. var _this = _super.call(this, name, position, scene) || this;
  54003. _this.inputs.addTouch();
  54004. _this._setupInputs();
  54005. return _this;
  54006. }
  54007. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54008. //-- Begin properties for backward compatibility for inputs
  54009. get: function () {
  54010. var touch = this.inputs.attached["touch"];
  54011. if (touch)
  54012. return touch.touchAngularSensibility;
  54013. return 0;
  54014. },
  54015. set: function (value) {
  54016. var touch = this.inputs.attached["touch"];
  54017. if (touch)
  54018. touch.touchAngularSensibility = value;
  54019. },
  54020. enumerable: true,
  54021. configurable: true
  54022. });
  54023. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54024. get: function () {
  54025. var touch = this.inputs.attached["touch"];
  54026. if (touch)
  54027. return touch.touchMoveSensibility;
  54028. return 0;
  54029. },
  54030. set: function (value) {
  54031. var touch = this.inputs.attached["touch"];
  54032. if (touch)
  54033. touch.touchMoveSensibility = value;
  54034. },
  54035. enumerable: true,
  54036. configurable: true
  54037. });
  54038. TouchCamera.prototype.getClassName = function () {
  54039. return "TouchCamera";
  54040. };
  54041. TouchCamera.prototype._setupInputs = function () {
  54042. var mouse = this.inputs.attached["mouse"];
  54043. if (mouse) {
  54044. mouse.touchEnabled = false;
  54045. }
  54046. };
  54047. return TouchCamera;
  54048. }(BABYLON.FreeCamera));
  54049. BABYLON.TouchCamera = TouchCamera;
  54050. })(BABYLON || (BABYLON = {}));
  54051. //# sourceMappingURL=babylon.touchCamera.js.map
  54052. var BABYLON;
  54053. (function (BABYLON) {
  54054. var ProceduralTexture = /** @class */ (function (_super) {
  54055. __extends(ProceduralTexture, _super);
  54056. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54057. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54058. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54059. if (isCube === void 0) { isCube = false; }
  54060. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54061. _this.isCube = isCube;
  54062. _this.isEnabled = true;
  54063. _this._currentRefreshId = -1;
  54064. _this._refreshRate = 1;
  54065. _this._vertexBuffers = {};
  54066. _this._uniforms = new Array();
  54067. _this._samplers = new Array();
  54068. _this._textures = {};
  54069. _this._floats = {};
  54070. _this._floatsArrays = {};
  54071. _this._colors3 = {};
  54072. _this._colors4 = {};
  54073. _this._vectors2 = {};
  54074. _this._vectors3 = {};
  54075. _this._matrices = {};
  54076. _this._fallbackTextureUsed = false;
  54077. scene._proceduralTextures.push(_this);
  54078. _this._engine = scene.getEngine();
  54079. _this.name = name;
  54080. _this.isRenderTarget = true;
  54081. _this._size = size;
  54082. _this._generateMipMaps = generateMipMaps;
  54083. _this.setFragment(fragment);
  54084. _this._fallbackTexture = fallbackTexture;
  54085. if (isCube) {
  54086. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54087. _this.setFloat("face", 0);
  54088. }
  54089. else {
  54090. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54091. }
  54092. // VBO
  54093. var vertices = [];
  54094. vertices.push(1, 1);
  54095. vertices.push(-1, 1);
  54096. vertices.push(-1, -1);
  54097. vertices.push(1, -1);
  54098. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54099. _this._createIndexBuffer();
  54100. return _this;
  54101. }
  54102. ProceduralTexture.prototype._createIndexBuffer = function () {
  54103. var engine = this._engine;
  54104. // Indices
  54105. var indices = [];
  54106. indices.push(0);
  54107. indices.push(1);
  54108. indices.push(2);
  54109. indices.push(0);
  54110. indices.push(2);
  54111. indices.push(3);
  54112. this._indexBuffer = engine.createIndexBuffer(indices);
  54113. };
  54114. ProceduralTexture.prototype._rebuild = function () {
  54115. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54116. if (vb) {
  54117. vb._rebuild();
  54118. }
  54119. this._createIndexBuffer();
  54120. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54121. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54122. }
  54123. };
  54124. ProceduralTexture.prototype.reset = function () {
  54125. if (this._effect === undefined) {
  54126. return;
  54127. }
  54128. var engine = this._engine;
  54129. engine._releaseEffect(this._effect);
  54130. };
  54131. ProceduralTexture.prototype.isReady = function () {
  54132. var _this = this;
  54133. var engine = this._engine;
  54134. var shaders;
  54135. if (!this._fragment) {
  54136. return false;
  54137. }
  54138. if (this._fallbackTextureUsed) {
  54139. return true;
  54140. }
  54141. if (this._fragment.fragmentElement !== undefined) {
  54142. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54143. }
  54144. else {
  54145. shaders = { vertex: "procedural", fragment: this._fragment };
  54146. }
  54147. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54148. _this.releaseInternalTexture();
  54149. if (_this._fallbackTexture) {
  54150. _this._texture = _this._fallbackTexture._texture;
  54151. if (_this._texture) {
  54152. _this._texture.incrementReferences();
  54153. }
  54154. }
  54155. _this._fallbackTextureUsed = true;
  54156. });
  54157. return this._effect.isReady();
  54158. };
  54159. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54160. this._currentRefreshId = -1;
  54161. };
  54162. ProceduralTexture.prototype.setFragment = function (fragment) {
  54163. this._fragment = fragment;
  54164. };
  54165. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54166. get: function () {
  54167. return this._refreshRate;
  54168. },
  54169. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54170. set: function (value) {
  54171. this._refreshRate = value;
  54172. this.resetRefreshCounter();
  54173. },
  54174. enumerable: true,
  54175. configurable: true
  54176. });
  54177. ProceduralTexture.prototype._shouldRender = function () {
  54178. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54179. return false;
  54180. }
  54181. if (this._fallbackTextureUsed) {
  54182. return false;
  54183. }
  54184. if (this._currentRefreshId === -1) {
  54185. this._currentRefreshId = 1;
  54186. return true;
  54187. }
  54188. if (this.refreshRate === this._currentRefreshId) {
  54189. this._currentRefreshId = 1;
  54190. return true;
  54191. }
  54192. this._currentRefreshId++;
  54193. return false;
  54194. };
  54195. ProceduralTexture.prototype.getRenderSize = function () {
  54196. return this._size;
  54197. };
  54198. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54199. if (this._fallbackTextureUsed) {
  54200. return;
  54201. }
  54202. this.releaseInternalTexture();
  54203. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54204. };
  54205. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54206. if (this._uniforms.indexOf(uniformName) === -1) {
  54207. this._uniforms.push(uniformName);
  54208. }
  54209. };
  54210. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54211. if (this._samplers.indexOf(name) === -1) {
  54212. this._samplers.push(name);
  54213. }
  54214. this._textures[name] = texture;
  54215. return this;
  54216. };
  54217. ProceduralTexture.prototype.setFloat = function (name, value) {
  54218. this._checkUniform(name);
  54219. this._floats[name] = value;
  54220. return this;
  54221. };
  54222. ProceduralTexture.prototype.setFloats = function (name, value) {
  54223. this._checkUniform(name);
  54224. this._floatsArrays[name] = value;
  54225. return this;
  54226. };
  54227. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54228. this._checkUniform(name);
  54229. this._colors3[name] = value;
  54230. return this;
  54231. };
  54232. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54233. this._checkUniform(name);
  54234. this._colors4[name] = value;
  54235. return this;
  54236. };
  54237. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54238. this._checkUniform(name);
  54239. this._vectors2[name] = value;
  54240. return this;
  54241. };
  54242. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54243. this._checkUniform(name);
  54244. this._vectors3[name] = value;
  54245. return this;
  54246. };
  54247. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54248. this._checkUniform(name);
  54249. this._matrices[name] = value;
  54250. return this;
  54251. };
  54252. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54253. var scene = this.getScene();
  54254. if (!scene) {
  54255. return;
  54256. }
  54257. var engine = this._engine;
  54258. // Render
  54259. engine.enableEffect(this._effect);
  54260. engine.setState(false);
  54261. // Texture
  54262. for (var name in this._textures) {
  54263. this._effect.setTexture(name, this._textures[name]);
  54264. }
  54265. // Float
  54266. for (name in this._floats) {
  54267. this._effect.setFloat(name, this._floats[name]);
  54268. }
  54269. // Floats
  54270. for (name in this._floatsArrays) {
  54271. this._effect.setArray(name, this._floatsArrays[name]);
  54272. }
  54273. // Color3
  54274. for (name in this._colors3) {
  54275. this._effect.setColor3(name, this._colors3[name]);
  54276. }
  54277. // Color4
  54278. for (name in this._colors4) {
  54279. var color = this._colors4[name];
  54280. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54281. }
  54282. // Vector2
  54283. for (name in this._vectors2) {
  54284. this._effect.setVector2(name, this._vectors2[name]);
  54285. }
  54286. // Vector3
  54287. for (name in this._vectors3) {
  54288. this._effect.setVector3(name, this._vectors3[name]);
  54289. }
  54290. // Matrix
  54291. for (name in this._matrices) {
  54292. this._effect.setMatrix(name, this._matrices[name]);
  54293. }
  54294. if (!this._texture) {
  54295. return;
  54296. }
  54297. if (this.isCube) {
  54298. for (var face = 0; face < 6; face++) {
  54299. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54300. // VBOs
  54301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54302. this._effect.setFloat("face", face);
  54303. // Clear
  54304. engine.clear(scene.clearColor, true, true, true);
  54305. // Draw order
  54306. engine.draw(true, 0, 6);
  54307. // Mipmaps
  54308. if (face === 5) {
  54309. engine.generateMipMapsForCubemap(this._texture);
  54310. }
  54311. }
  54312. }
  54313. else {
  54314. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54315. // VBOs
  54316. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54317. // Clear
  54318. engine.clear(scene.clearColor, true, true, true);
  54319. // Draw order
  54320. engine.draw(true, 0, 6);
  54321. }
  54322. // Unbind
  54323. engine.unBindFramebuffer(this._texture, this.isCube);
  54324. if (this.onGenerated) {
  54325. this.onGenerated();
  54326. }
  54327. };
  54328. ProceduralTexture.prototype.clone = function () {
  54329. var textureSize = this.getSize();
  54330. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54331. // Base texture
  54332. newTexture.hasAlpha = this.hasAlpha;
  54333. newTexture.level = this.level;
  54334. // RenderTarget Texture
  54335. newTexture.coordinatesMode = this.coordinatesMode;
  54336. return newTexture;
  54337. };
  54338. ProceduralTexture.prototype.dispose = function () {
  54339. var scene = this.getScene();
  54340. if (!scene) {
  54341. return;
  54342. }
  54343. var index = scene._proceduralTextures.indexOf(this);
  54344. if (index >= 0) {
  54345. scene._proceduralTextures.splice(index, 1);
  54346. }
  54347. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54348. if (vertexBuffer) {
  54349. vertexBuffer.dispose();
  54350. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54351. }
  54352. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54353. this._indexBuffer = null;
  54354. }
  54355. _super.prototype.dispose.call(this);
  54356. };
  54357. return ProceduralTexture;
  54358. }(BABYLON.Texture));
  54359. BABYLON.ProceduralTexture = ProceduralTexture;
  54360. })(BABYLON || (BABYLON = {}));
  54361. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54362. var BABYLON;
  54363. (function (BABYLON) {
  54364. var CustomProceduralTexture = /** @class */ (function (_super) {
  54365. __extends(CustomProceduralTexture, _super);
  54366. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54367. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54368. _this._animate = true;
  54369. _this._time = 0;
  54370. _this._texturePath = texturePath;
  54371. //Try to load json
  54372. _this.loadJson(texturePath);
  54373. _this.refreshRate = 1;
  54374. return _this;
  54375. }
  54376. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54377. var _this = this;
  54378. var noConfigFile = function () {
  54379. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54380. try {
  54381. _this.setFragment(_this._texturePath);
  54382. }
  54383. catch (ex) {
  54384. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54385. }
  54386. };
  54387. var configFileUrl = jsonUrl + "/config.json";
  54388. var xhr = new XMLHttpRequest();
  54389. xhr.open("GET", configFileUrl, true);
  54390. xhr.addEventListener("load", function () {
  54391. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54392. try {
  54393. _this._config = JSON.parse(xhr.response);
  54394. _this.updateShaderUniforms();
  54395. _this.updateTextures();
  54396. _this.setFragment(_this._texturePath + "/custom");
  54397. _this._animate = _this._config.animate;
  54398. _this.refreshRate = _this._config.refreshrate;
  54399. }
  54400. catch (ex) {
  54401. noConfigFile();
  54402. }
  54403. }
  54404. else {
  54405. noConfigFile();
  54406. }
  54407. }, false);
  54408. xhr.addEventListener("error", function () {
  54409. noConfigFile();
  54410. }, false);
  54411. try {
  54412. xhr.send();
  54413. }
  54414. catch (ex) {
  54415. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54416. }
  54417. };
  54418. CustomProceduralTexture.prototype.isReady = function () {
  54419. if (!_super.prototype.isReady.call(this)) {
  54420. return false;
  54421. }
  54422. for (var name in this._textures) {
  54423. var texture = this._textures[name];
  54424. if (!texture.isReady()) {
  54425. return false;
  54426. }
  54427. }
  54428. return true;
  54429. };
  54430. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54431. var scene = this.getScene();
  54432. if (this._animate && scene) {
  54433. this._time += scene.getAnimationRatio() * 0.03;
  54434. this.updateShaderUniforms();
  54435. }
  54436. _super.prototype.render.call(this, useCameraPostProcess);
  54437. };
  54438. CustomProceduralTexture.prototype.updateTextures = function () {
  54439. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54440. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54441. }
  54442. };
  54443. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54444. if (this._config) {
  54445. for (var j = 0; j < this._config.uniforms.length; j++) {
  54446. var uniform = this._config.uniforms[j];
  54447. switch (uniform.type) {
  54448. case "float":
  54449. this.setFloat(uniform.name, uniform.value);
  54450. break;
  54451. case "color3":
  54452. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54453. break;
  54454. case "color4":
  54455. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54456. break;
  54457. case "vector2":
  54458. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54459. break;
  54460. case "vector3":
  54461. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54462. break;
  54463. }
  54464. }
  54465. }
  54466. this.setFloat("time", this._time);
  54467. };
  54468. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54469. get: function () {
  54470. return this._animate;
  54471. },
  54472. set: function (value) {
  54473. this._animate = value;
  54474. },
  54475. enumerable: true,
  54476. configurable: true
  54477. });
  54478. return CustomProceduralTexture;
  54479. }(BABYLON.ProceduralTexture));
  54480. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54481. })(BABYLON || (BABYLON = {}));
  54482. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54483. var BABYLON;
  54484. (function (BABYLON) {
  54485. var FreeCameraGamepadInput = /** @class */ (function () {
  54486. function FreeCameraGamepadInput() {
  54487. this.gamepadAngularSensibility = 200;
  54488. this.gamepadMoveSensibility = 40;
  54489. // private members
  54490. this._cameraTransform = BABYLON.Matrix.Identity();
  54491. this._deltaTransform = BABYLON.Vector3.Zero();
  54492. this._vector3 = BABYLON.Vector3.Zero();
  54493. this._vector2 = BABYLON.Vector2.Zero();
  54494. }
  54495. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54496. var _this = this;
  54497. var manager = this.camera.getScene().gamepadManager;
  54498. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54499. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54500. // prioritize XBOX gamepads.
  54501. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54502. _this.gamepad = gamepad;
  54503. }
  54504. }
  54505. });
  54506. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54507. if (_this.gamepad === gamepad) {
  54508. _this.gamepad = null;
  54509. }
  54510. });
  54511. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54512. };
  54513. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54514. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54515. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54516. this.gamepad = null;
  54517. };
  54518. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54519. if (this.gamepad && this.gamepad.leftStick) {
  54520. var camera = this.camera;
  54521. var LSValues = this.gamepad.leftStick;
  54522. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54523. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54524. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54525. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54526. var RSValues = this.gamepad.rightStick;
  54527. if (RSValues) {
  54528. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54529. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54530. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54531. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54532. }
  54533. else {
  54534. RSValues = { x: 0, y: 0 };
  54535. }
  54536. if (!camera.rotationQuaternion) {
  54537. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54538. }
  54539. else {
  54540. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54541. }
  54542. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54543. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54544. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54545. camera.cameraDirection.addInPlace(this._deltaTransform);
  54546. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54547. camera.cameraRotation.addInPlace(this._vector2);
  54548. }
  54549. };
  54550. FreeCameraGamepadInput.prototype.getClassName = function () {
  54551. return "FreeCameraGamepadInput";
  54552. };
  54553. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54554. return "gamepad";
  54555. };
  54556. __decorate([
  54557. BABYLON.serialize()
  54558. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54559. __decorate([
  54560. BABYLON.serialize()
  54561. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54562. return FreeCameraGamepadInput;
  54563. }());
  54564. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  54565. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  54566. })(BABYLON || (BABYLON = {}));
  54567. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  54568. var BABYLON;
  54569. (function (BABYLON) {
  54570. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  54571. function ArcRotateCameraGamepadInput() {
  54572. this.gamepadRotationSensibility = 80;
  54573. this.gamepadMoveSensibility = 40;
  54574. }
  54575. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54576. var _this = this;
  54577. var manager = this.camera.getScene().gamepadManager;
  54578. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54579. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54580. // prioritize XBOX gamepads.
  54581. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54582. _this.gamepad = gamepad;
  54583. }
  54584. }
  54585. });
  54586. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54587. if (_this.gamepad === gamepad) {
  54588. _this.gamepad = null;
  54589. }
  54590. });
  54591. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54592. };
  54593. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  54594. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54595. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54596. this.gamepad = null;
  54597. };
  54598. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  54599. if (this.gamepad) {
  54600. var camera = this.camera;
  54601. var RSValues = this.gamepad.rightStick;
  54602. if (RSValues) {
  54603. if (RSValues.x != 0) {
  54604. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  54605. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  54606. camera.inertialAlphaOffset += normalizedRX;
  54607. }
  54608. }
  54609. if (RSValues.y != 0) {
  54610. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  54611. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  54612. camera.inertialBetaOffset += normalizedRY;
  54613. }
  54614. }
  54615. }
  54616. var LSValues = this.gamepad.leftStick;
  54617. if (LSValues && LSValues.y != 0) {
  54618. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54619. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  54620. this.camera.inertialRadiusOffset -= normalizedLY;
  54621. }
  54622. }
  54623. }
  54624. };
  54625. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  54626. return "ArcRotateCameraGamepadInput";
  54627. };
  54628. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  54629. return "gamepad";
  54630. };
  54631. __decorate([
  54632. BABYLON.serialize()
  54633. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  54634. __decorate([
  54635. BABYLON.serialize()
  54636. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54637. return ArcRotateCameraGamepadInput;
  54638. }());
  54639. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  54640. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  54641. })(BABYLON || (BABYLON = {}));
  54642. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  54643. var BABYLON;
  54644. (function (BABYLON) {
  54645. var GamepadManager = /** @class */ (function () {
  54646. function GamepadManager() {
  54647. var _this = this;
  54648. this._babylonGamepads = [];
  54649. this._oneGamepadConnected = false;
  54650. this._isMonitoring = false;
  54651. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  54652. if (!BABYLON.Tools.IsWindowObjectExist()) {
  54653. this._gamepadEventSupported = false;
  54654. }
  54655. else {
  54656. this._gamepadEventSupported = 'GamepadEvent' in window;
  54657. this._gamepadSupport = (navigator.getGamepads ||
  54658. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  54659. }
  54660. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  54661. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  54662. for (var i in _this._babylonGamepads) {
  54663. var gamepad = _this._babylonGamepads[i];
  54664. if (gamepad && gamepad._isConnected) {
  54665. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  54666. }
  54667. }
  54668. });
  54669. this._onGamepadConnectedEvent = function (evt) {
  54670. var gamepad = evt.gamepad;
  54671. if (gamepad.index in _this._babylonGamepads) {
  54672. if (_this._babylonGamepads[gamepad.index].isConnected) {
  54673. return;
  54674. }
  54675. }
  54676. var newGamepad;
  54677. if (_this._babylonGamepads[gamepad.index]) {
  54678. newGamepad = _this._babylonGamepads[gamepad.index];
  54679. newGamepad.browserGamepad = gamepad;
  54680. newGamepad._isConnected = true;
  54681. }
  54682. else {
  54683. newGamepad = _this._addNewGamepad(gamepad);
  54684. }
  54685. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54686. _this._startMonitoringGamepads();
  54687. };
  54688. this._onGamepadDisconnectedEvent = function (evt) {
  54689. var gamepad = evt.gamepad;
  54690. // Remove the gamepad from the list of gamepads to monitor.
  54691. for (var i in _this._babylonGamepads) {
  54692. if (_this._babylonGamepads[i].index === gamepad.index) {
  54693. var disconnectedGamepad = _this._babylonGamepads[i];
  54694. disconnectedGamepad._isConnected = false;
  54695. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  54696. break;
  54697. }
  54698. }
  54699. };
  54700. if (this._gamepadSupport) {
  54701. //first add already-connected gamepads
  54702. this._updateGamepadObjects();
  54703. if (this._babylonGamepads.length) {
  54704. this._startMonitoringGamepads();
  54705. }
  54706. // Checking if the gamepad connected event is supported (like in Firefox)
  54707. if (this._gamepadEventSupported) {
  54708. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54709. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  54710. }
  54711. else {
  54712. this._startMonitoringGamepads();
  54713. }
  54714. }
  54715. }
  54716. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  54717. get: function () {
  54718. return this._babylonGamepads;
  54719. },
  54720. enumerable: true,
  54721. configurable: true
  54722. });
  54723. GamepadManager.prototype.getGamepadByType = function (type) {
  54724. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  54725. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  54726. var gamepad = _a[_i];
  54727. if (gamepad && gamepad.type === type) {
  54728. return gamepad;
  54729. }
  54730. }
  54731. return null;
  54732. };
  54733. GamepadManager.prototype.dispose = function () {
  54734. if (this._gamepadEventSupported) {
  54735. if (this._onGamepadConnectedEvent) {
  54736. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  54737. }
  54738. if (this._onGamepadDisconnectedEvent) {
  54739. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  54740. }
  54741. this._onGamepadConnectedEvent = null;
  54742. this._onGamepadDisconnectedEvent = null;
  54743. }
  54744. this._babylonGamepads.forEach(function (gamepad) {
  54745. gamepad.dispose();
  54746. });
  54747. this.onGamepadConnectedObservable.clear();
  54748. this.onGamepadDisconnectedObservable.clear();
  54749. this._oneGamepadConnected = false;
  54750. this._stopMonitoringGamepads();
  54751. this._babylonGamepads = [];
  54752. };
  54753. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  54754. if (!this._oneGamepadConnected) {
  54755. this._oneGamepadConnected = true;
  54756. }
  54757. var newGamepad;
  54758. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  54759. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54760. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  54761. }
  54762. else if (gamepad.pose) {
  54763. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  54764. }
  54765. else {
  54766. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  54767. }
  54768. this._babylonGamepads[newGamepad.index] = newGamepad;
  54769. return newGamepad;
  54770. };
  54771. GamepadManager.prototype._startMonitoringGamepads = function () {
  54772. if (!this._isMonitoring) {
  54773. this._isMonitoring = true;
  54774. this._checkGamepadsStatus();
  54775. }
  54776. };
  54777. GamepadManager.prototype._stopMonitoringGamepads = function () {
  54778. this._isMonitoring = false;
  54779. };
  54780. GamepadManager.prototype._checkGamepadsStatus = function () {
  54781. var _this = this;
  54782. // Hack to be compatible Chrome
  54783. this._updateGamepadObjects();
  54784. for (var i in this._babylonGamepads) {
  54785. var gamepad = this._babylonGamepads[i];
  54786. if (!gamepad || !gamepad.isConnected) {
  54787. continue;
  54788. }
  54789. gamepad.update();
  54790. }
  54791. if (this._isMonitoring) {
  54792. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  54793. }
  54794. };
  54795. // This function is called only on Chrome, which does not properly support
  54796. // connection/disconnection events and forces you to recopy again the gamepad object
  54797. GamepadManager.prototype._updateGamepadObjects = function () {
  54798. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54799. for (var i = 0; i < gamepads.length; i++) {
  54800. if (gamepads[i]) {
  54801. if (!this._babylonGamepads[gamepads[i].index]) {
  54802. var newGamepad = this._addNewGamepad(gamepads[i]);
  54803. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  54804. }
  54805. else {
  54806. // Forced to copy again this object for Chrome for unknown reason
  54807. this._babylonGamepads[i].browserGamepad = gamepads[i];
  54808. if (!this._babylonGamepads[i].isConnected) {
  54809. this._babylonGamepads[i]._isConnected = true;
  54810. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  54811. }
  54812. }
  54813. }
  54814. }
  54815. };
  54816. return GamepadManager;
  54817. }());
  54818. BABYLON.GamepadManager = GamepadManager;
  54819. })(BABYLON || (BABYLON = {}));
  54820. //# sourceMappingURL=babylon.gamepadManager.js.map
  54821. var BABYLON;
  54822. (function (BABYLON) {
  54823. var StickValues = /** @class */ (function () {
  54824. function StickValues(x, y) {
  54825. this.x = x;
  54826. this.y = y;
  54827. }
  54828. return StickValues;
  54829. }());
  54830. BABYLON.StickValues = StickValues;
  54831. var Gamepad = /** @class */ (function () {
  54832. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  54833. if (leftStickX === void 0) { leftStickX = 0; }
  54834. if (leftStickY === void 0) { leftStickY = 1; }
  54835. if (rightStickX === void 0) { rightStickX = 2; }
  54836. if (rightStickY === void 0) { rightStickY = 3; }
  54837. this.id = id;
  54838. this.index = index;
  54839. this.browserGamepad = browserGamepad;
  54840. this._isConnected = true;
  54841. this.type = Gamepad.GAMEPAD;
  54842. this._leftStickAxisX = leftStickX;
  54843. this._leftStickAxisY = leftStickY;
  54844. this._rightStickAxisX = rightStickX;
  54845. this._rightStickAxisY = rightStickY;
  54846. if (this.browserGamepad.axes.length >= 2) {
  54847. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54848. }
  54849. if (this.browserGamepad.axes.length >= 4) {
  54850. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54851. }
  54852. }
  54853. Object.defineProperty(Gamepad.prototype, "isConnected", {
  54854. get: function () {
  54855. return this._isConnected;
  54856. },
  54857. enumerable: true,
  54858. configurable: true
  54859. });
  54860. Gamepad.prototype.onleftstickchanged = function (callback) {
  54861. this._onleftstickchanged = callback;
  54862. };
  54863. Gamepad.prototype.onrightstickchanged = function (callback) {
  54864. this._onrightstickchanged = callback;
  54865. };
  54866. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54867. get: function () {
  54868. return this._leftStick;
  54869. },
  54870. set: function (newValues) {
  54871. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54872. this._onleftstickchanged(newValues);
  54873. }
  54874. this._leftStick = newValues;
  54875. },
  54876. enumerable: true,
  54877. configurable: true
  54878. });
  54879. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54880. get: function () {
  54881. return this._rightStick;
  54882. },
  54883. set: function (newValues) {
  54884. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54885. this._onrightstickchanged(newValues);
  54886. }
  54887. this._rightStick = newValues;
  54888. },
  54889. enumerable: true,
  54890. configurable: true
  54891. });
  54892. Gamepad.prototype.update = function () {
  54893. if (this._leftStick) {
  54894. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  54895. }
  54896. if (this._rightStick) {
  54897. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  54898. }
  54899. };
  54900. Gamepad.prototype.dispose = function () {
  54901. };
  54902. Gamepad.GAMEPAD = 0;
  54903. Gamepad.GENERIC = 1;
  54904. Gamepad.XBOX = 2;
  54905. Gamepad.POSE_ENABLED = 3;
  54906. return Gamepad;
  54907. }());
  54908. BABYLON.Gamepad = Gamepad;
  54909. var GenericPad = /** @class */ (function (_super) {
  54910. __extends(GenericPad, _super);
  54911. function GenericPad(id, index, browserGamepad) {
  54912. var _this = _super.call(this, id, index, browserGamepad) || this;
  54913. _this.onButtonDownObservable = new BABYLON.Observable();
  54914. _this.onButtonUpObservable = new BABYLON.Observable();
  54915. _this.type = Gamepad.GENERIC;
  54916. _this._buttons = new Array(browserGamepad.buttons.length);
  54917. return _this;
  54918. }
  54919. GenericPad.prototype.onbuttondown = function (callback) {
  54920. this._onbuttondown = callback;
  54921. };
  54922. GenericPad.prototype.onbuttonup = function (callback) {
  54923. this._onbuttonup = callback;
  54924. };
  54925. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54926. if (newValue !== currentValue) {
  54927. if (newValue === 1) {
  54928. if (this._onbuttondown) {
  54929. this._onbuttondown(buttonIndex);
  54930. }
  54931. this.onButtonDownObservable.notifyObservers(buttonIndex);
  54932. }
  54933. if (newValue === 0) {
  54934. if (this._onbuttonup) {
  54935. this._onbuttonup(buttonIndex);
  54936. }
  54937. this.onButtonUpObservable.notifyObservers(buttonIndex);
  54938. }
  54939. }
  54940. return newValue;
  54941. };
  54942. GenericPad.prototype.update = function () {
  54943. _super.prototype.update.call(this);
  54944. for (var index = 0; index < this._buttons.length; index++) {
  54945. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  54946. }
  54947. };
  54948. return GenericPad;
  54949. }(Gamepad));
  54950. BABYLON.GenericPad = GenericPad;
  54951. })(BABYLON || (BABYLON = {}));
  54952. //# sourceMappingURL=babylon.gamepad.js.map
  54953. var BABYLON;
  54954. (function (BABYLON) {
  54955. var Xbox360Button;
  54956. (function (Xbox360Button) {
  54957. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54958. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54959. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54960. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54961. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54962. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54963. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54964. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54965. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54966. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54967. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54968. var Xbox360Dpad;
  54969. (function (Xbox360Dpad) {
  54970. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54971. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54972. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54973. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54974. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54975. var Xbox360Pad = /** @class */ (function (_super) {
  54976. __extends(Xbox360Pad, _super);
  54977. function Xbox360Pad(id, index, gamepad, xboxOne) {
  54978. if (xboxOne === void 0) { xboxOne = false; }
  54979. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  54980. _this._leftTrigger = 0;
  54981. _this._rightTrigger = 0;
  54982. _this.onButtonDownObservable = new BABYLON.Observable();
  54983. _this.onButtonUpObservable = new BABYLON.Observable();
  54984. _this.onPadDownObservable = new BABYLON.Observable();
  54985. _this.onPadUpObservable = new BABYLON.Observable();
  54986. _this._buttonA = 0;
  54987. _this._buttonB = 0;
  54988. _this._buttonX = 0;
  54989. _this._buttonY = 0;
  54990. _this._buttonBack = 0;
  54991. _this._buttonStart = 0;
  54992. _this._buttonLB = 0;
  54993. _this._buttonRB = 0;
  54994. _this._buttonLeftStick = 0;
  54995. _this._buttonRightStick = 0;
  54996. _this._dPadUp = 0;
  54997. _this._dPadDown = 0;
  54998. _this._dPadLeft = 0;
  54999. _this._dPadRight = 0;
  55000. _this._isXboxOnePad = false;
  55001. _this.type = BABYLON.Gamepad.XBOX;
  55002. _this._isXboxOnePad = xboxOne;
  55003. return _this;
  55004. }
  55005. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55006. this._onlefttriggerchanged = callback;
  55007. };
  55008. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55009. this._onrighttriggerchanged = callback;
  55010. };
  55011. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55012. get: function () {
  55013. return this._leftTrigger;
  55014. },
  55015. set: function (newValue) {
  55016. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55017. this._onlefttriggerchanged(newValue);
  55018. }
  55019. this._leftTrigger = newValue;
  55020. },
  55021. enumerable: true,
  55022. configurable: true
  55023. });
  55024. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55025. get: function () {
  55026. return this._rightTrigger;
  55027. },
  55028. set: function (newValue) {
  55029. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55030. this._onrighttriggerchanged(newValue);
  55031. }
  55032. this._rightTrigger = newValue;
  55033. },
  55034. enumerable: true,
  55035. configurable: true
  55036. });
  55037. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55038. this._onbuttondown = callback;
  55039. };
  55040. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55041. this._onbuttonup = callback;
  55042. };
  55043. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55044. this._ondpaddown = callback;
  55045. };
  55046. Xbox360Pad.prototype.ondpadup = function (callback) {
  55047. this._ondpadup = callback;
  55048. };
  55049. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55050. if (newValue !== currentValue) {
  55051. if (newValue === 1) {
  55052. if (this._onbuttondown) {
  55053. this._onbuttondown(buttonType);
  55054. }
  55055. this.onButtonDownObservable.notifyObservers(buttonType);
  55056. }
  55057. if (newValue === 0) {
  55058. if (this._onbuttonup) {
  55059. this._onbuttonup(buttonType);
  55060. }
  55061. this.onButtonUpObservable.notifyObservers(buttonType);
  55062. }
  55063. }
  55064. return newValue;
  55065. };
  55066. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55067. if (newValue !== currentValue) {
  55068. if (newValue === 1) {
  55069. if (this._ondpaddown) {
  55070. this._ondpaddown(buttonType);
  55071. }
  55072. this.onPadDownObservable.notifyObservers(buttonType);
  55073. }
  55074. if (newValue === 0) {
  55075. if (this._ondpadup) {
  55076. this._ondpadup(buttonType);
  55077. }
  55078. this.onPadUpObservable.notifyObservers(buttonType);
  55079. }
  55080. }
  55081. return newValue;
  55082. };
  55083. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55084. get: function () {
  55085. return this._buttonA;
  55086. },
  55087. set: function (value) {
  55088. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55089. },
  55090. enumerable: true,
  55091. configurable: true
  55092. });
  55093. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55094. get: function () {
  55095. return this._buttonB;
  55096. },
  55097. set: function (value) {
  55098. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55099. },
  55100. enumerable: true,
  55101. configurable: true
  55102. });
  55103. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55104. get: function () {
  55105. return this._buttonX;
  55106. },
  55107. set: function (value) {
  55108. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55109. },
  55110. enumerable: true,
  55111. configurable: true
  55112. });
  55113. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55114. get: function () {
  55115. return this._buttonY;
  55116. },
  55117. set: function (value) {
  55118. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55119. },
  55120. enumerable: true,
  55121. configurable: true
  55122. });
  55123. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55124. get: function () {
  55125. return this._buttonStart;
  55126. },
  55127. set: function (value) {
  55128. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55129. },
  55130. enumerable: true,
  55131. configurable: true
  55132. });
  55133. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55134. get: function () {
  55135. return this._buttonBack;
  55136. },
  55137. set: function (value) {
  55138. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55139. },
  55140. enumerable: true,
  55141. configurable: true
  55142. });
  55143. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55144. get: function () {
  55145. return this._buttonLB;
  55146. },
  55147. set: function (value) {
  55148. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55149. },
  55150. enumerable: true,
  55151. configurable: true
  55152. });
  55153. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55154. get: function () {
  55155. return this._buttonRB;
  55156. },
  55157. set: function (value) {
  55158. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55159. },
  55160. enumerable: true,
  55161. configurable: true
  55162. });
  55163. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55164. get: function () {
  55165. return this._buttonLeftStick;
  55166. },
  55167. set: function (value) {
  55168. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55169. },
  55170. enumerable: true,
  55171. configurable: true
  55172. });
  55173. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55174. get: function () {
  55175. return this._buttonRightStick;
  55176. },
  55177. set: function (value) {
  55178. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55179. },
  55180. enumerable: true,
  55181. configurable: true
  55182. });
  55183. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55184. get: function () {
  55185. return this._dPadUp;
  55186. },
  55187. set: function (value) {
  55188. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55189. },
  55190. enumerable: true,
  55191. configurable: true
  55192. });
  55193. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55194. get: function () {
  55195. return this._dPadDown;
  55196. },
  55197. set: function (value) {
  55198. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55199. },
  55200. enumerable: true,
  55201. configurable: true
  55202. });
  55203. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55204. get: function () {
  55205. return this._dPadLeft;
  55206. },
  55207. set: function (value) {
  55208. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55209. },
  55210. enumerable: true,
  55211. configurable: true
  55212. });
  55213. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55214. get: function () {
  55215. return this._dPadRight;
  55216. },
  55217. set: function (value) {
  55218. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55219. },
  55220. enumerable: true,
  55221. configurable: true
  55222. });
  55223. Xbox360Pad.prototype.update = function () {
  55224. _super.prototype.update.call(this);
  55225. if (this._isXboxOnePad) {
  55226. this.buttonA = this.browserGamepad.buttons[0].value;
  55227. this.buttonB = this.browserGamepad.buttons[1].value;
  55228. this.buttonX = this.browserGamepad.buttons[2].value;
  55229. this.buttonY = this.browserGamepad.buttons[3].value;
  55230. this.buttonLB = this.browserGamepad.buttons[4].value;
  55231. this.buttonRB = this.browserGamepad.buttons[5].value;
  55232. this.leftTrigger = this.browserGamepad.axes[2];
  55233. this.rightTrigger = this.browserGamepad.axes[5];
  55234. this.buttonBack = this.browserGamepad.buttons[9].value;
  55235. this.buttonStart = this.browserGamepad.buttons[8].value;
  55236. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55237. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55238. this.dPadUp = this.browserGamepad.buttons[11].value;
  55239. this.dPadDown = this.browserGamepad.buttons[12].value;
  55240. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55241. this.dPadRight = this.browserGamepad.buttons[14].value;
  55242. }
  55243. else {
  55244. this.buttonA = this.browserGamepad.buttons[0].value;
  55245. this.buttonB = this.browserGamepad.buttons[1].value;
  55246. this.buttonX = this.browserGamepad.buttons[2].value;
  55247. this.buttonY = this.browserGamepad.buttons[3].value;
  55248. this.buttonLB = this.browserGamepad.buttons[4].value;
  55249. this.buttonRB = this.browserGamepad.buttons[5].value;
  55250. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55251. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55252. this.buttonBack = this.browserGamepad.buttons[8].value;
  55253. this.buttonStart = this.browserGamepad.buttons[9].value;
  55254. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55255. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55256. this.dPadUp = this.browserGamepad.buttons[12].value;
  55257. this.dPadDown = this.browserGamepad.buttons[13].value;
  55258. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55259. this.dPadRight = this.browserGamepad.buttons[15].value;
  55260. }
  55261. };
  55262. return Xbox360Pad;
  55263. }(BABYLON.Gamepad));
  55264. BABYLON.Xbox360Pad = Xbox360Pad;
  55265. })(BABYLON || (BABYLON = {}));
  55266. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55267. var BABYLON;
  55268. (function (BABYLON) {
  55269. var PoseEnabledControllerType;
  55270. (function (PoseEnabledControllerType) {
  55271. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55272. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55273. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55274. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55275. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55276. var PoseEnabledControllerHelper = /** @class */ (function () {
  55277. function PoseEnabledControllerHelper() {
  55278. }
  55279. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55280. // Oculus Touch
  55281. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55282. return new BABYLON.OculusTouchController(vrGamepad);
  55283. }
  55284. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55285. return new BABYLON.WindowsMotionController(vrGamepad);
  55286. }
  55287. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55288. return new BABYLON.ViveController(vrGamepad);
  55289. }
  55290. else {
  55291. return new BABYLON.GenericController(vrGamepad);
  55292. }
  55293. };
  55294. return PoseEnabledControllerHelper;
  55295. }());
  55296. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55297. var PoseEnabledController = /** @class */ (function (_super) {
  55298. __extends(PoseEnabledController, _super);
  55299. function PoseEnabledController(browserGamepad) {
  55300. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55301. _this.deviceScaleFactor = 1;
  55302. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55303. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55304. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55305. _this.position = BABYLON.Vector3.Zero();
  55306. _this.rotationQuaternion = new BABYLON.Quaternion();
  55307. _this.devicePosition = BABYLON.Vector3.Zero();
  55308. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55309. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55310. _this._calculatedRotation = new BABYLON.Quaternion();
  55311. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55312. return _this;
  55313. }
  55314. PoseEnabledController.prototype.update = function () {
  55315. _super.prototype.update.call(this);
  55316. var pose = this.browserGamepad.pose;
  55317. this.updateFromDevice(pose);
  55318. if (this._mesh) {
  55319. this._mesh.position.copyFrom(this._calculatedPosition);
  55320. if (this._mesh.rotationQuaternion) {
  55321. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55322. }
  55323. }
  55324. };
  55325. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55326. if (poseData) {
  55327. this.rawPose = poseData;
  55328. if (poseData.position) {
  55329. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55330. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55331. this.devicePosition.z *= -1;
  55332. }
  55333. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55334. this._calculatedPosition.addInPlace(this.position);
  55335. }
  55336. var pose = this.rawPose;
  55337. if (poseData.orientation && pose.orientation) {
  55338. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55339. if (this._mesh) {
  55340. if (this._mesh.getScene().useRightHandedSystem) {
  55341. this.deviceRotationQuaternion.z *= -1;
  55342. this.deviceRotationQuaternion.w *= -1;
  55343. }
  55344. else {
  55345. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55346. }
  55347. }
  55348. // if the camera is set, rotate to the camera's rotation
  55349. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55350. }
  55351. }
  55352. };
  55353. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55354. if (this._mesh) {
  55355. this._mesh.parent = null;
  55356. }
  55357. this._mesh = mesh;
  55358. if (this._poseControlledCamera) {
  55359. this._mesh.parent = this._poseControlledCamera;
  55360. }
  55361. if (!this._mesh.rotationQuaternion) {
  55362. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55363. }
  55364. };
  55365. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55366. this._poseControlledCamera = camera;
  55367. if (this._mesh) {
  55368. this._mesh.parent = this._poseControlledCamera;
  55369. }
  55370. };
  55371. PoseEnabledController.prototype.dispose = function () {
  55372. if (this._mesh) {
  55373. this._mesh.dispose();
  55374. }
  55375. this._mesh = null;
  55376. _super.prototype.dispose.call(this);
  55377. };
  55378. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55379. get: function () {
  55380. return this._mesh;
  55381. },
  55382. enumerable: true,
  55383. configurable: true
  55384. });
  55385. PoseEnabledController.prototype.getForwardRay = function (length) {
  55386. if (length === void 0) { length = 100; }
  55387. if (!this.mesh) {
  55388. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55389. }
  55390. var m = this.mesh.getWorldMatrix();
  55391. var origin = m.getTranslation();
  55392. var forward = new BABYLON.Vector3(0, 0, -1);
  55393. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55394. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55395. return new BABYLON.Ray(origin, direction, length);
  55396. };
  55397. return PoseEnabledController;
  55398. }(BABYLON.Gamepad));
  55399. BABYLON.PoseEnabledController = PoseEnabledController;
  55400. })(BABYLON || (BABYLON = {}));
  55401. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55402. var BABYLON;
  55403. (function (BABYLON) {
  55404. var WebVRController = /** @class */ (function (_super) {
  55405. __extends(WebVRController, _super);
  55406. function WebVRController(vrGamepad) {
  55407. var _this = _super.call(this, vrGamepad) || this;
  55408. // Observables
  55409. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55410. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55411. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55412. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55413. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55414. _this.pad = { x: 0, y: 0 };
  55415. // avoid GC, store state in a tmp object
  55416. _this._changes = {
  55417. pressChanged: false,
  55418. touchChanged: false,
  55419. valueChanged: false,
  55420. changed: false
  55421. };
  55422. _this._buttons = new Array(vrGamepad.buttons.length);
  55423. _this.hand = vrGamepad.hand;
  55424. return _this;
  55425. }
  55426. WebVRController.prototype.onButtonStateChange = function (callback) {
  55427. this._onButtonStateChange = callback;
  55428. };
  55429. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55430. get: function () {
  55431. return this._defaultModel;
  55432. },
  55433. enumerable: true,
  55434. configurable: true
  55435. });
  55436. WebVRController.prototype.update = function () {
  55437. _super.prototype.update.call(this);
  55438. for (var index = 0; index < this._buttons.length; index++) {
  55439. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55440. }
  55441. ;
  55442. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55443. this.pad.x = this.leftStick.x;
  55444. this.pad.y = this.leftStick.y;
  55445. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55446. }
  55447. };
  55448. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55449. if (!newState) {
  55450. newState = {
  55451. pressed: false,
  55452. touched: false,
  55453. value: 0
  55454. };
  55455. }
  55456. if (!currentState) {
  55457. this._buttons[buttonIndex] = {
  55458. pressed: newState.pressed,
  55459. touched: newState.touched,
  55460. value: newState.value
  55461. };
  55462. return;
  55463. }
  55464. this._checkChanges(newState, currentState);
  55465. if (this._changes.changed) {
  55466. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55467. this.handleButtonChange(buttonIndex, newState, this._changes);
  55468. }
  55469. this._buttons[buttonIndex].pressed = newState.pressed;
  55470. this._buttons[buttonIndex].touched = newState.touched;
  55471. // oculus triggers are never 0, thou not touched.
  55472. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55473. };
  55474. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55475. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55476. this._changes.touchChanged = newState.touched !== currentState.touched;
  55477. this._changes.valueChanged = newState.value !== currentState.value;
  55478. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55479. return this._changes;
  55480. };
  55481. WebVRController.prototype.dispose = function () {
  55482. _super.prototype.dispose.call(this);
  55483. this.onTriggerStateChangedObservable.clear();
  55484. this.onMainButtonStateChangedObservable.clear();
  55485. this.onSecondaryButtonStateChangedObservable.clear();
  55486. this.onPadStateChangedObservable.clear();
  55487. this.onPadValuesChangedObservable.clear();
  55488. };
  55489. return WebVRController;
  55490. }(BABYLON.PoseEnabledController));
  55491. BABYLON.WebVRController = WebVRController;
  55492. })(BABYLON || (BABYLON = {}));
  55493. //# sourceMappingURL=babylon.webVRController.js.map
  55494. var BABYLON;
  55495. (function (BABYLON) {
  55496. var OculusTouchController = /** @class */ (function (_super) {
  55497. __extends(OculusTouchController, _super);
  55498. function OculusTouchController(vrGamepad) {
  55499. var _this = _super.call(this, vrGamepad) || this;
  55500. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55501. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55502. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55503. return _this;
  55504. }
  55505. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55506. var _this = this;
  55507. var meshName;
  55508. // Hand
  55509. if (this.hand === 'left') {
  55510. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55511. }
  55512. else {
  55513. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55514. }
  55515. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55516. /*
  55517. Parent Mesh name: oculus_touch_left
  55518. - body
  55519. - trigger
  55520. - thumbstick
  55521. - grip
  55522. - button_y
  55523. - button_x
  55524. - button_enter
  55525. */
  55526. _this._defaultModel = newMeshes[1];
  55527. _this.attachToMesh(_this._defaultModel);
  55528. if (meshLoaded) {
  55529. meshLoaded(_this._defaultModel);
  55530. }
  55531. });
  55532. };
  55533. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55534. // helper getters for left and right hand.
  55535. get: function () {
  55536. if (this.hand === 'right') {
  55537. return this.onMainButtonStateChangedObservable;
  55538. }
  55539. else {
  55540. throw new Error('No A button on left hand');
  55541. }
  55542. },
  55543. enumerable: true,
  55544. configurable: true
  55545. });
  55546. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55547. get: function () {
  55548. if (this.hand === 'right') {
  55549. return this.onSecondaryButtonStateChangedObservable;
  55550. }
  55551. else {
  55552. throw new Error('No B button on left hand');
  55553. }
  55554. },
  55555. enumerable: true,
  55556. configurable: true
  55557. });
  55558. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55559. get: function () {
  55560. if (this.hand === 'left') {
  55561. return this.onMainButtonStateChangedObservable;
  55562. }
  55563. else {
  55564. throw new Error('No X button on right hand');
  55565. }
  55566. },
  55567. enumerable: true,
  55568. configurable: true
  55569. });
  55570. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  55571. get: function () {
  55572. if (this.hand === 'left') {
  55573. return this.onSecondaryButtonStateChangedObservable;
  55574. }
  55575. else {
  55576. throw new Error('No Y button on right hand');
  55577. }
  55578. },
  55579. enumerable: true,
  55580. configurable: true
  55581. });
  55582. /*
  55583. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  55584. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  55585. 2) secondary trigger (same)
  55586. 3) A (right) X (left), touch, pressed = value
  55587. 4) B / Y
  55588. 5) thumb rest
  55589. */
  55590. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55591. var notifyObject = state; //{ state: state, changes: changes };
  55592. var triggerDirection = this.hand === 'right' ? -1 : 1;
  55593. switch (buttonIdx) {
  55594. case 0:
  55595. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55596. return;
  55597. case 1:// index trigger
  55598. if (this._defaultModel) {
  55599. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  55600. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  55601. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  55602. }
  55603. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55604. return;
  55605. case 2:// secondary trigger
  55606. if (this._defaultModel) {
  55607. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  55608. }
  55609. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  55610. return;
  55611. case 3:
  55612. if (this._defaultModel) {
  55613. if (notifyObject.pressed) {
  55614. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  55615. }
  55616. else {
  55617. (this._defaultModel.getChildren()[1]).position.y = 0;
  55618. }
  55619. }
  55620. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55621. return;
  55622. case 4:
  55623. if (this._defaultModel) {
  55624. if (notifyObject.pressed) {
  55625. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55626. }
  55627. else {
  55628. (this._defaultModel.getChildren()[2]).position.y = 0;
  55629. }
  55630. }
  55631. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55632. return;
  55633. case 5:
  55634. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  55635. return;
  55636. }
  55637. };
  55638. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  55639. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  55640. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  55641. return OculusTouchController;
  55642. }(BABYLON.WebVRController));
  55643. BABYLON.OculusTouchController = OculusTouchController;
  55644. })(BABYLON || (BABYLON = {}));
  55645. //# sourceMappingURL=babylon.oculusTouchController.js.map
  55646. var BABYLON;
  55647. (function (BABYLON) {
  55648. var ViveController = /** @class */ (function (_super) {
  55649. __extends(ViveController, _super);
  55650. function ViveController(vrGamepad) {
  55651. var _this = _super.call(this, vrGamepad) || this;
  55652. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  55653. return _this;
  55654. }
  55655. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55656. var _this = this;
  55657. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  55658. /*
  55659. Parent Mesh name: ViveWand
  55660. - body
  55661. - r_gripper
  55662. - l_gripper
  55663. - menu_button
  55664. - system_button
  55665. - trackpad
  55666. - trigger
  55667. - LED
  55668. */
  55669. _this._defaultModel = newMeshes[1];
  55670. _this.attachToMesh(_this._defaultModel);
  55671. if (meshLoaded) {
  55672. meshLoaded(_this._defaultModel);
  55673. }
  55674. });
  55675. };
  55676. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  55677. get: function () {
  55678. return this.onMainButtonStateChangedObservable;
  55679. },
  55680. enumerable: true,
  55681. configurable: true
  55682. });
  55683. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  55684. get: function () {
  55685. return this.onMainButtonStateChangedObservable;
  55686. },
  55687. enumerable: true,
  55688. configurable: true
  55689. });
  55690. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  55691. get: function () {
  55692. return this.onSecondaryButtonStateChangedObservable;
  55693. },
  55694. enumerable: true,
  55695. configurable: true
  55696. });
  55697. /**
  55698. * Vive mapping:
  55699. * 0: touchpad
  55700. * 1: trigger
  55701. * 2: left AND right buttons
  55702. * 3: menu button
  55703. */
  55704. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55705. var notifyObject = state; //{ state: state, changes: changes };
  55706. switch (buttonIdx) {
  55707. case 0:
  55708. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  55709. return;
  55710. case 1:// index trigger
  55711. if (this._defaultModel) {
  55712. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  55713. }
  55714. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  55715. return;
  55716. case 2:// left AND right button
  55717. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  55718. return;
  55719. case 3:
  55720. if (this._defaultModel) {
  55721. if (notifyObject.pressed) {
  55722. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  55723. }
  55724. else {
  55725. (this._defaultModel.getChildren()[2]).position.y = 0;
  55726. }
  55727. }
  55728. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  55729. return;
  55730. }
  55731. };
  55732. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  55733. ViveController.MODEL_FILENAME = 'wand.babylon';
  55734. return ViveController;
  55735. }(BABYLON.WebVRController));
  55736. BABYLON.ViveController = ViveController;
  55737. })(BABYLON || (BABYLON = {}));
  55738. //# sourceMappingURL=babylon.viveController.js.map
  55739. var BABYLON;
  55740. (function (BABYLON) {
  55741. var GenericController = /** @class */ (function (_super) {
  55742. __extends(GenericController, _super);
  55743. function GenericController(vrGamepad) {
  55744. return _super.call(this, vrGamepad) || this;
  55745. }
  55746. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55747. var _this = this;
  55748. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  55749. _this._defaultModel = newMeshes[1];
  55750. _this.attachToMesh(_this._defaultModel);
  55751. if (meshLoaded) {
  55752. meshLoaded(_this._defaultModel);
  55753. }
  55754. });
  55755. };
  55756. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55757. console.log("Button id: " + buttonIdx + "state: ");
  55758. console.dir(state);
  55759. };
  55760. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  55761. GenericController.MODEL_FILENAME = 'generic.babylon';
  55762. return GenericController;
  55763. }(BABYLON.WebVRController));
  55764. BABYLON.GenericController = GenericController;
  55765. })(BABYLON || (BABYLON = {}));
  55766. //# sourceMappingURL=babylon.genericController.js.map
  55767. var BABYLON;
  55768. (function (BABYLON) {
  55769. var LoadedMeshInfo = /** @class */ (function () {
  55770. function LoadedMeshInfo() {
  55771. this.buttonMeshes = {};
  55772. this.axisMeshes = {};
  55773. }
  55774. return LoadedMeshInfo;
  55775. }());
  55776. var WindowsMotionController = /** @class */ (function (_super) {
  55777. __extends(WindowsMotionController, _super);
  55778. function WindowsMotionController(vrGamepad) {
  55779. var _this = _super.call(this, vrGamepad) || this;
  55780. _this._mapping = {
  55781. // Semantic button names
  55782. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  55783. // A mapping of the button name to glTF model node name
  55784. // that should be transformed by button value.
  55785. buttonMeshNames: {
  55786. 'trigger': 'SELECT',
  55787. 'menu': 'MENU',
  55788. 'grip': 'GRASP',
  55789. 'thumbstick': 'THUMBSTICK_PRESS',
  55790. 'trackpad': 'TOUCHPAD_PRESS'
  55791. },
  55792. // This mapping is used to translate from the Motion Controller to Babylon semantics
  55793. buttonObservableNames: {
  55794. 'trigger': 'onTriggerStateChangedObservable',
  55795. 'menu': 'onSecondaryButtonStateChangedObservable',
  55796. 'grip': 'onMainButtonStateChangedObservable',
  55797. 'thumbstick': 'onPadStateChangedObservable',
  55798. 'trackpad': 'onTrackpadChangedObservable'
  55799. },
  55800. // A mapping of the axis name to glTF model node name
  55801. // that should be transformed by axis value.
  55802. // This array mirrors the browserGamepad.axes array, such that
  55803. // the mesh corresponding to axis 0 is in this array index 0.
  55804. axisMeshNames: [
  55805. 'THUMBSTICK_X',
  55806. 'THUMBSTICK_Y',
  55807. 'TOUCHPAD_TOUCH_X',
  55808. 'TOUCHPAD_TOUCH_Y'
  55809. ],
  55810. pointingPoseMeshName: 'POINTING_POSE'
  55811. };
  55812. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  55813. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  55814. _this._loadedMeshInfo = null;
  55815. return _this;
  55816. }
  55817. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  55818. get: function () {
  55819. return this.onTriggerStateChangedObservable;
  55820. },
  55821. enumerable: true,
  55822. configurable: true
  55823. });
  55824. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  55825. get: function () {
  55826. return this.onSecondaryButtonStateChangedObservable;
  55827. },
  55828. enumerable: true,
  55829. configurable: true
  55830. });
  55831. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  55832. get: function () {
  55833. return this.onMainButtonStateChangedObservable;
  55834. },
  55835. enumerable: true,
  55836. configurable: true
  55837. });
  55838. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  55839. get: function () {
  55840. return this.onPadStateChangedObservable;
  55841. },
  55842. enumerable: true,
  55843. configurable: true
  55844. });
  55845. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  55846. get: function () {
  55847. return this.onTrackpadChangedObservable;
  55848. },
  55849. enumerable: true,
  55850. configurable: true
  55851. });
  55852. /**
  55853. * Called once per frame by the engine.
  55854. */
  55855. WindowsMotionController.prototype.update = function () {
  55856. _super.prototype.update.call(this);
  55857. // Only need to animate axes if there is a loaded mesh
  55858. if (this._loadedMeshInfo) {
  55859. if (this.browserGamepad.axes) {
  55860. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  55861. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  55862. }
  55863. }
  55864. }
  55865. };
  55866. /**
  55867. * Called once for each button that changed state since the last frame
  55868. * @param buttonIdx Which button index changed
  55869. * @param state New state of the button
  55870. * @param changes Which properties on the state changed since last frame
  55871. */
  55872. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  55873. var buttonName = this._mapping.buttons[buttonIdx];
  55874. if (!buttonName) {
  55875. return;
  55876. }
  55877. // Only emit events for buttons that we know how to map from index to name
  55878. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  55879. if (observable) {
  55880. observable.notifyObservers(state);
  55881. }
  55882. this.lerpButtonTransform(buttonName, state.value);
  55883. };
  55884. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  55885. // If there is no loaded mesh, there is nothing to transform.
  55886. if (!this._loadedMeshInfo) {
  55887. return;
  55888. }
  55889. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  55890. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55891. return;
  55892. }
  55893. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  55894. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  55895. };
  55896. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  55897. if (!this._loadedMeshInfo) {
  55898. return;
  55899. }
  55900. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  55901. if (!meshInfo) {
  55902. return;
  55903. }
  55904. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  55905. return;
  55906. }
  55907. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  55908. var lerpValue = axisValue * 0.5 + 0.5;
  55909. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  55910. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  55911. };
  55912. /**
  55913. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  55914. * @param scene scene in which to add meshes
  55915. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  55916. */
  55917. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  55918. var _this = this;
  55919. if (forceDefault === void 0) { forceDefault = false; }
  55920. var path;
  55921. var filename;
  55922. // Checking if GLB loader is present
  55923. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  55924. // Determine the device specific folder based on the ID suffix
  55925. var device = 'default';
  55926. if (this.id && !forceDefault) {
  55927. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  55928. device = ((match && match[0]) || device);
  55929. }
  55930. // Hand
  55931. if (this.hand === 'left') {
  55932. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  55933. }
  55934. else {
  55935. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  55936. }
  55937. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  55938. }
  55939. else {
  55940. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  55941. path = BABYLON.GenericController.MODEL_BASE_URL;
  55942. filename = BABYLON.GenericController.MODEL_FILENAME;
  55943. }
  55944. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  55945. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  55946. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  55947. if (!_this._loadedMeshInfo) {
  55948. return;
  55949. }
  55950. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  55951. _this.attachToMesh(_this._defaultModel);
  55952. if (meshLoaded) {
  55953. meshLoaded(_this._defaultModel);
  55954. }
  55955. }, null, function (scene, message) {
  55956. BABYLON.Tools.Log(message);
  55957. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  55958. if (!forceDefault) {
  55959. _this.initControllerMesh(scene, meshLoaded, true);
  55960. }
  55961. });
  55962. };
  55963. /**
  55964. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  55965. * can be transformed by button presses and axes values, based on this._mapping.
  55966. *
  55967. * @param scene scene in which the meshes exist
  55968. * @param meshes list of meshes that make up the controller model to process
  55969. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  55970. */
  55971. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  55972. var loadedMeshInfo = null;
  55973. // Create a new mesh to contain the glTF hierarchy
  55974. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  55975. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  55976. var childMesh = null;
  55977. for (var i = 0; i < meshes.length; i++) {
  55978. var mesh = meshes[i];
  55979. if (!mesh.parent) {
  55980. // Exclude controller meshes from picking results
  55981. mesh.isPickable = false;
  55982. // Handle root node, attach to the new parentMesh
  55983. childMesh = mesh;
  55984. break;
  55985. }
  55986. }
  55987. if (childMesh) {
  55988. childMesh.setParent(parentMesh);
  55989. // Create our mesh info. Note that this method will always return non-null.
  55990. loadedMeshInfo = this.createMeshInfo(parentMesh);
  55991. }
  55992. else {
  55993. BABYLON.Tools.Warn('Could not find root node in model file.');
  55994. }
  55995. return loadedMeshInfo;
  55996. };
  55997. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  55998. var loadedMeshInfo = new LoadedMeshInfo();
  55999. var i;
  56000. loadedMeshInfo.rootNode = rootNode;
  56001. // Reset the caches
  56002. loadedMeshInfo.buttonMeshes = {};
  56003. loadedMeshInfo.axisMeshes = {};
  56004. // Button Meshes
  56005. for (i = 0; i < this._mapping.buttons.length; i++) {
  56006. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56007. if (!buttonMeshName) {
  56008. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56009. continue;
  56010. }
  56011. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56012. if (!buttonMesh) {
  56013. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56014. continue;
  56015. }
  56016. var buttonMeshInfo = {
  56017. index: i,
  56018. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56019. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56020. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56021. };
  56022. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56023. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56024. }
  56025. else {
  56026. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56027. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56028. '(VALUE: ' + !!buttonMeshInfo.value +
  56029. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56030. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56031. ')');
  56032. }
  56033. }
  56034. // Axis Meshes
  56035. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56036. var axisMeshName = this._mapping.axisMeshNames[i];
  56037. if (!axisMeshName) {
  56038. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56039. continue;
  56040. }
  56041. var axisMesh = getChildByName(rootNode, axisMeshName);
  56042. if (!axisMesh) {
  56043. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56044. continue;
  56045. }
  56046. var axisMeshInfo = {
  56047. index: i,
  56048. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56049. min: getImmediateChildByName(axisMesh, 'MIN'),
  56050. max: getImmediateChildByName(axisMesh, 'MAX')
  56051. };
  56052. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56053. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56054. }
  56055. else {
  56056. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56057. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56058. '(VALUE: ' + !!axisMeshInfo.value +
  56059. ', MIN: ' + !!axisMeshInfo.min +
  56060. ', MAX:' + !!axisMeshInfo.max +
  56061. ')');
  56062. }
  56063. }
  56064. // Pointing Ray
  56065. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56066. if (!loadedMeshInfo.pointingPoseNode) {
  56067. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56068. }
  56069. return loadedMeshInfo;
  56070. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56071. function getChildByName(node, name) {
  56072. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56073. }
  56074. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56075. function getImmediateChildByName(node, name) {
  56076. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56077. }
  56078. };
  56079. WindowsMotionController.prototype.getForwardRay = function (length) {
  56080. if (length === void 0) { length = 100; }
  56081. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56082. return _super.prototype.getForwardRay.call(this, length);
  56083. }
  56084. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56085. var origin = m.getTranslation();
  56086. var forward = new BABYLON.Vector3(0, 0, -1);
  56087. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56088. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56089. return new BABYLON.Ray(origin, direction, length);
  56090. };
  56091. WindowsMotionController.prototype.dispose = function () {
  56092. _super.prototype.dispose.call(this);
  56093. this.onTrackpadChangedObservable.clear();
  56094. };
  56095. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56096. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56097. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56098. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56099. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56100. return WindowsMotionController;
  56101. }(BABYLON.WebVRController));
  56102. BABYLON.WindowsMotionController = WindowsMotionController;
  56103. })(BABYLON || (BABYLON = {}));
  56104. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56105. var BABYLON;
  56106. (function (BABYLON) {
  56107. var FollowCamera = /** @class */ (function (_super) {
  56108. __extends(FollowCamera, _super);
  56109. function FollowCamera(name, position, scene, lockedTarget) {
  56110. if (lockedTarget === void 0) { lockedTarget = null; }
  56111. var _this = _super.call(this, name, position, scene) || this;
  56112. _this.radius = 12;
  56113. _this.rotationOffset = 0;
  56114. _this.heightOffset = 4;
  56115. _this.cameraAcceleration = 0.05;
  56116. _this.maxCameraSpeed = 20;
  56117. _this.lockedTarget = lockedTarget;
  56118. return _this;
  56119. }
  56120. FollowCamera.prototype.getRadians = function (degrees) {
  56121. return degrees * Math.PI / 180;
  56122. };
  56123. FollowCamera.prototype.follow = function (cameraTarget) {
  56124. if (!cameraTarget)
  56125. return;
  56126. var yRotation;
  56127. if (cameraTarget.rotationQuaternion) {
  56128. var rotMatrix = new BABYLON.Matrix();
  56129. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56130. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56131. }
  56132. else {
  56133. yRotation = cameraTarget.rotation.y;
  56134. }
  56135. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56136. var targetPosition = cameraTarget.getAbsolutePosition();
  56137. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56138. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56139. var dx = targetX - this.position.x;
  56140. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56141. var dz = (targetZ) - this.position.z;
  56142. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56143. var vy = dy * this.cameraAcceleration;
  56144. var vz = dz * this.cameraAcceleration * 2;
  56145. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56146. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56147. }
  56148. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56149. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56150. }
  56151. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56152. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56153. }
  56154. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56155. this.setTarget(targetPosition);
  56156. };
  56157. FollowCamera.prototype._checkInputs = function () {
  56158. _super.prototype._checkInputs.call(this);
  56159. if (this.lockedTarget) {
  56160. this.follow(this.lockedTarget);
  56161. }
  56162. };
  56163. FollowCamera.prototype.getClassName = function () {
  56164. return "FollowCamera";
  56165. };
  56166. __decorate([
  56167. BABYLON.serialize()
  56168. ], FollowCamera.prototype, "radius", void 0);
  56169. __decorate([
  56170. BABYLON.serialize()
  56171. ], FollowCamera.prototype, "rotationOffset", void 0);
  56172. __decorate([
  56173. BABYLON.serialize()
  56174. ], FollowCamera.prototype, "heightOffset", void 0);
  56175. __decorate([
  56176. BABYLON.serialize()
  56177. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56178. __decorate([
  56179. BABYLON.serialize()
  56180. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56181. __decorate([
  56182. BABYLON.serializeAsMeshReference("lockedTargetId")
  56183. ], FollowCamera.prototype, "lockedTarget", void 0);
  56184. return FollowCamera;
  56185. }(BABYLON.TargetCamera));
  56186. BABYLON.FollowCamera = FollowCamera;
  56187. var ArcFollowCamera = /** @class */ (function (_super) {
  56188. __extends(ArcFollowCamera, _super);
  56189. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56190. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56191. _this.alpha = alpha;
  56192. _this.beta = beta;
  56193. _this.radius = radius;
  56194. _this.target = target;
  56195. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56196. _this.follow();
  56197. return _this;
  56198. }
  56199. ArcFollowCamera.prototype.follow = function () {
  56200. if (!this.target) {
  56201. return;
  56202. }
  56203. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56204. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56205. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56206. var targetPosition = this.target.getAbsolutePosition();
  56207. this.position = targetPosition.add(this._cartesianCoordinates);
  56208. this.setTarget(targetPosition);
  56209. };
  56210. ArcFollowCamera.prototype._checkInputs = function () {
  56211. _super.prototype._checkInputs.call(this);
  56212. this.follow();
  56213. };
  56214. ArcFollowCamera.prototype.getClassName = function () {
  56215. return "ArcFollowCamera";
  56216. };
  56217. return ArcFollowCamera;
  56218. }(BABYLON.TargetCamera));
  56219. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56220. })(BABYLON || (BABYLON = {}));
  56221. //# sourceMappingURL=babylon.followCamera.js.map
  56222. var BABYLON;
  56223. (function (BABYLON) {
  56224. // We're mainly based on the logic defined into the FreeCamera code
  56225. var UniversalCamera = /** @class */ (function (_super) {
  56226. __extends(UniversalCamera, _super);
  56227. //-- end properties for backward compatibility for inputs
  56228. function UniversalCamera(name, position, scene) {
  56229. var _this = _super.call(this, name, position, scene) || this;
  56230. _this.inputs.addGamepad();
  56231. return _this;
  56232. }
  56233. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56234. //-- Begin properties for backward compatibility for inputs
  56235. get: function () {
  56236. var gamepad = this.inputs.attached["gamepad"];
  56237. if (gamepad)
  56238. return gamepad.gamepadAngularSensibility;
  56239. return 0;
  56240. },
  56241. set: function (value) {
  56242. var gamepad = this.inputs.attached["gamepad"];
  56243. if (gamepad)
  56244. gamepad.gamepadAngularSensibility = value;
  56245. },
  56246. enumerable: true,
  56247. configurable: true
  56248. });
  56249. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56250. get: function () {
  56251. var gamepad = this.inputs.attached["gamepad"];
  56252. if (gamepad)
  56253. return gamepad.gamepadMoveSensibility;
  56254. return 0;
  56255. },
  56256. set: function (value) {
  56257. var gamepad = this.inputs.attached["gamepad"];
  56258. if (gamepad)
  56259. gamepad.gamepadMoveSensibility = value;
  56260. },
  56261. enumerable: true,
  56262. configurable: true
  56263. });
  56264. UniversalCamera.prototype.getClassName = function () {
  56265. return "UniversalCamera";
  56266. };
  56267. return UniversalCamera;
  56268. }(BABYLON.TouchCamera));
  56269. BABYLON.UniversalCamera = UniversalCamera;
  56270. })(BABYLON || (BABYLON = {}));
  56271. //# sourceMappingURL=babylon.universalCamera.js.map
  56272. var BABYLON;
  56273. (function (BABYLON) {
  56274. // We're mainly based on the logic defined into the FreeCamera code
  56275. var GamepadCamera = /** @class */ (function (_super) {
  56276. __extends(GamepadCamera, _super);
  56277. //-- end properties for backward compatibility for inputs
  56278. function GamepadCamera(name, position, scene) {
  56279. return _super.call(this, name, position, scene) || this;
  56280. }
  56281. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56282. //-- Begin properties for backward compatibility for inputs
  56283. get: function () {
  56284. var gamepad = this.inputs.attached["gamepad"];
  56285. if (gamepad)
  56286. return gamepad.gamepadAngularSensibility;
  56287. return 0;
  56288. },
  56289. set: function (value) {
  56290. var gamepad = this.inputs.attached["gamepad"];
  56291. if (gamepad)
  56292. gamepad.gamepadAngularSensibility = value;
  56293. },
  56294. enumerable: true,
  56295. configurable: true
  56296. });
  56297. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56298. get: function () {
  56299. var gamepad = this.inputs.attached["gamepad"];
  56300. if (gamepad)
  56301. return gamepad.gamepadMoveSensibility;
  56302. return 0;
  56303. },
  56304. set: function (value) {
  56305. var gamepad = this.inputs.attached["gamepad"];
  56306. if (gamepad)
  56307. gamepad.gamepadMoveSensibility = value;
  56308. },
  56309. enumerable: true,
  56310. configurable: true
  56311. });
  56312. GamepadCamera.prototype.getClassName = function () {
  56313. return "GamepadCamera";
  56314. };
  56315. return GamepadCamera;
  56316. }(BABYLON.UniversalCamera));
  56317. BABYLON.GamepadCamera = GamepadCamera;
  56318. })(BABYLON || (BABYLON = {}));
  56319. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56320. var BABYLON;
  56321. (function (BABYLON) {
  56322. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56323. function PostProcessRenderPipelineManager() {
  56324. this._renderPipelines = {};
  56325. }
  56326. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56327. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56328. };
  56329. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56330. if (unique === void 0) { unique = false; }
  56331. var renderPipeline = this._renderPipelines[renderPipelineName];
  56332. if (!renderPipeline) {
  56333. return;
  56334. }
  56335. renderPipeline._attachCameras(cameras, unique);
  56336. };
  56337. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56338. var renderPipeline = this._renderPipelines[renderPipelineName];
  56339. if (!renderPipeline) {
  56340. return;
  56341. }
  56342. renderPipeline._detachCameras(cameras);
  56343. };
  56344. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56345. var renderPipeline = this._renderPipelines[renderPipelineName];
  56346. if (!renderPipeline) {
  56347. return;
  56348. }
  56349. renderPipeline._enableEffect(renderEffectName, cameras);
  56350. };
  56351. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56352. var renderPipeline = this._renderPipelines[renderPipelineName];
  56353. if (!renderPipeline) {
  56354. return;
  56355. }
  56356. renderPipeline._disableEffect(renderEffectName, cameras);
  56357. };
  56358. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56359. var renderPipeline = this._renderPipelines[renderPipelineName];
  56360. if (!renderPipeline) {
  56361. return;
  56362. }
  56363. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56364. };
  56365. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56366. var renderPipeline = this._renderPipelines[renderPipelineName];
  56367. if (!renderPipeline) {
  56368. return;
  56369. }
  56370. renderPipeline._disableDisplayOnlyPass(cameras);
  56371. };
  56372. PostProcessRenderPipelineManager.prototype.update = function () {
  56373. for (var renderPipelineName in this._renderPipelines) {
  56374. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56375. var pipeline = this._renderPipelines[renderPipelineName];
  56376. if (!pipeline.isSupported) {
  56377. pipeline.dispose();
  56378. delete this._renderPipelines[renderPipelineName];
  56379. }
  56380. else {
  56381. pipeline._update();
  56382. }
  56383. }
  56384. }
  56385. };
  56386. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56387. for (var renderPipelineName in this._renderPipelines) {
  56388. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56389. var pipeline = this._renderPipelines[renderPipelineName];
  56390. pipeline._rebuild();
  56391. }
  56392. }
  56393. };
  56394. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56395. for (var renderPipelineName in this._renderPipelines) {
  56396. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56397. var pipeline = this._renderPipelines[renderPipelineName];
  56398. pipeline.dispose();
  56399. }
  56400. }
  56401. };
  56402. return PostProcessRenderPipelineManager;
  56403. }());
  56404. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56405. })(BABYLON || (BABYLON = {}));
  56406. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56407. var BABYLON;
  56408. (function (BABYLON) {
  56409. var PostProcessRenderPass = /** @class */ (function () {
  56410. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56411. this._refCount = 0;
  56412. this._name = name;
  56413. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56414. this.setRenderList(renderList);
  56415. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56416. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56417. this._scene = scene;
  56418. this._renderList = renderList;
  56419. }
  56420. // private
  56421. PostProcessRenderPass.prototype._incRefCount = function () {
  56422. if (this._refCount === 0) {
  56423. this._scene.customRenderTargets.push(this._renderTexture);
  56424. }
  56425. return ++this._refCount;
  56426. };
  56427. PostProcessRenderPass.prototype._decRefCount = function () {
  56428. this._refCount--;
  56429. if (this._refCount <= 0) {
  56430. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56431. }
  56432. return this._refCount;
  56433. };
  56434. PostProcessRenderPass.prototype._update = function () {
  56435. this.setRenderList(this._renderList);
  56436. };
  56437. // public
  56438. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56439. this._renderTexture.renderList = renderList;
  56440. };
  56441. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56442. return this._renderTexture;
  56443. };
  56444. return PostProcessRenderPass;
  56445. }());
  56446. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56447. })(BABYLON || (BABYLON = {}));
  56448. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56449. var BABYLON;
  56450. (function (BABYLON) {
  56451. var PostProcessRenderEffect = /** @class */ (function () {
  56452. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56453. this._engine = engine;
  56454. this._name = name;
  56455. this._singleInstance = singleInstance || true;
  56456. this._getPostProcess = getPostProcess;
  56457. this._cameras = {};
  56458. this._indicesForCamera = {};
  56459. this._postProcesses = {};
  56460. this._renderPasses = {};
  56461. this._renderEffectAsPasses = {};
  56462. }
  56463. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56464. get: function () {
  56465. for (var index in this._postProcesses) {
  56466. if (!this._postProcesses[index].isSupported) {
  56467. return false;
  56468. }
  56469. }
  56470. return true;
  56471. },
  56472. enumerable: true,
  56473. configurable: true
  56474. });
  56475. PostProcessRenderEffect.prototype._update = function () {
  56476. for (var renderPassName in this._renderPasses) {
  56477. this._renderPasses[renderPassName]._update();
  56478. }
  56479. };
  56480. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56481. this._renderPasses[renderPass._name] = renderPass;
  56482. this._linkParameters();
  56483. };
  56484. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56485. delete this._renderPasses[renderPass._name];
  56486. this._linkParameters();
  56487. };
  56488. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56489. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56490. this._linkParameters();
  56491. };
  56492. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56493. for (var renderPassName in this._renderPasses) {
  56494. if (renderPassName === passName) {
  56495. return this._renderPasses[passName];
  56496. }
  56497. }
  56498. return null;
  56499. };
  56500. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56501. this._renderPasses = {};
  56502. this._linkParameters();
  56503. };
  56504. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56505. var cameraKey;
  56506. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56507. if (!cams) {
  56508. return;
  56509. }
  56510. for (var i = 0; i < cams.length; i++) {
  56511. var camera = cams[i];
  56512. var cameraName = camera.name;
  56513. if (this._singleInstance) {
  56514. cameraKey = 0;
  56515. }
  56516. else {
  56517. cameraKey = cameraName;
  56518. }
  56519. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56520. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56521. if (!this._indicesForCamera[cameraName]) {
  56522. this._indicesForCamera[cameraName] = [];
  56523. }
  56524. this._indicesForCamera[cameraName].push(index);
  56525. if (!this._cameras[cameraName]) {
  56526. this._cameras[cameraName] = camera;
  56527. }
  56528. for (var passName in this._renderPasses) {
  56529. this._renderPasses[passName]._incRefCount();
  56530. }
  56531. }
  56532. this._linkParameters();
  56533. };
  56534. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56535. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56536. if (!cams) {
  56537. return;
  56538. }
  56539. for (var i = 0; i < cams.length; i++) {
  56540. var camera = cams[i];
  56541. var cameraName = camera.name;
  56542. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56543. if (this._cameras[cameraName]) {
  56544. //this._indicesForCamera.splice(index, 1);
  56545. this._cameras[cameraName] = null;
  56546. }
  56547. for (var passName in this._renderPasses) {
  56548. this._renderPasses[passName]._decRefCount();
  56549. }
  56550. }
  56551. };
  56552. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56553. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56554. if (!cams) {
  56555. return;
  56556. }
  56557. for (var i = 0; i < cams.length; i++) {
  56558. var camera = cams[i];
  56559. var cameraName = camera.name;
  56560. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56561. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56562. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  56563. }
  56564. }
  56565. for (var passName in this._renderPasses) {
  56566. this._renderPasses[passName]._incRefCount();
  56567. }
  56568. }
  56569. };
  56570. PostProcessRenderEffect.prototype._disable = function (cameras) {
  56571. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56572. if (!cams) {
  56573. return;
  56574. }
  56575. for (var i = 0; i < cams.length; i++) {
  56576. var camera = cams[i];
  56577. var cameraName = camera.Name;
  56578. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56579. for (var passName in this._renderPasses) {
  56580. this._renderPasses[passName]._decRefCount();
  56581. }
  56582. }
  56583. };
  56584. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  56585. if (this._singleInstance) {
  56586. return this._postProcesses[0];
  56587. }
  56588. else {
  56589. if (!camera) {
  56590. return null;
  56591. }
  56592. return this._postProcesses[camera.name];
  56593. }
  56594. };
  56595. PostProcessRenderEffect.prototype._linkParameters = function () {
  56596. var _this = this;
  56597. for (var index in this._postProcesses) {
  56598. if (this.applyParameters) {
  56599. this.applyParameters(this._postProcesses[index]);
  56600. }
  56601. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  56602. _this._linkTextures(effect);
  56603. });
  56604. }
  56605. };
  56606. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  56607. for (var renderPassName in this._renderPasses) {
  56608. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  56609. }
  56610. for (var renderEffectName in this._renderEffectAsPasses) {
  56611. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  56612. }
  56613. };
  56614. return PostProcessRenderEffect;
  56615. }());
  56616. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  56617. })(BABYLON || (BABYLON = {}));
  56618. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  56619. var BABYLON;
  56620. (function (BABYLON) {
  56621. var PostProcessRenderPipeline = /** @class */ (function () {
  56622. function PostProcessRenderPipeline(engine, name) {
  56623. this._engine = engine;
  56624. this._name = name;
  56625. this._renderEffects = {};
  56626. this._renderEffectsForIsolatedPass = new Array();
  56627. this._cameras = [];
  56628. }
  56629. PostProcessRenderPipeline.prototype.getClassName = function () {
  56630. return "PostProcessRenderPipeline";
  56631. };
  56632. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  56633. get: function () {
  56634. for (var renderEffectName in this._renderEffects) {
  56635. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56636. if (!this._renderEffects[renderEffectName].isSupported) {
  56637. return false;
  56638. }
  56639. }
  56640. }
  56641. return true;
  56642. },
  56643. enumerable: true,
  56644. configurable: true
  56645. });
  56646. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  56647. this._renderEffects[renderEffect._name] = renderEffect;
  56648. };
  56649. // private
  56650. PostProcessRenderPipeline.prototype._rebuild = function () {
  56651. };
  56652. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  56653. var renderEffects = this._renderEffects[renderEffectName];
  56654. if (!renderEffects) {
  56655. return;
  56656. }
  56657. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56658. };
  56659. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  56660. var renderEffects = this._renderEffects[renderEffectName];
  56661. if (!renderEffects) {
  56662. return;
  56663. }
  56664. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  56665. };
  56666. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  56667. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56668. if (!cams) {
  56669. return;
  56670. }
  56671. var indicesToDelete = [];
  56672. var i;
  56673. for (i = 0; i < cams.length; i++) {
  56674. var camera = cams[i];
  56675. var cameraName = camera.name;
  56676. if (this._cameras.indexOf(camera) === -1) {
  56677. this._cameras[cameraName] = camera;
  56678. }
  56679. else if (unique) {
  56680. indicesToDelete.push(i);
  56681. }
  56682. }
  56683. for (i = 0; i < indicesToDelete.length; i++) {
  56684. cameras.splice(indicesToDelete[i], 1);
  56685. }
  56686. for (var renderEffectName in this._renderEffects) {
  56687. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56688. this._renderEffects[renderEffectName]._attachCameras(cams);
  56689. }
  56690. }
  56691. };
  56692. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  56693. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56694. if (!cams) {
  56695. return;
  56696. }
  56697. for (var renderEffectName in this._renderEffects) {
  56698. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56699. this._renderEffects[renderEffectName]._detachCameras(cams);
  56700. }
  56701. }
  56702. for (var i = 0; i < cams.length; i++) {
  56703. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  56704. }
  56705. };
  56706. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  56707. var _this = this;
  56708. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56709. if (!cams) {
  56710. return;
  56711. }
  56712. var pass = null;
  56713. var renderEffectName;
  56714. for (renderEffectName in this._renderEffects) {
  56715. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56716. pass = this._renderEffects[renderEffectName].getPass(passName);
  56717. if (pass != null) {
  56718. break;
  56719. }
  56720. }
  56721. }
  56722. if (pass === null) {
  56723. return;
  56724. }
  56725. for (renderEffectName in this._renderEffects) {
  56726. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56727. this._renderEffects[renderEffectName]._disable(cams);
  56728. }
  56729. }
  56730. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  56731. for (var i = 0; i < cams.length; i++) {
  56732. var camera = cams[i];
  56733. var cameraName = camera.name;
  56734. 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); });
  56735. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  56736. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  56737. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  56738. }
  56739. };
  56740. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  56741. var _this = this;
  56742. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56743. if (!cams) {
  56744. return;
  56745. }
  56746. for (var i = 0; i < cams.length; i++) {
  56747. var camera = cams[i];
  56748. var cameraName = camera.name;
  56749. 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); });
  56750. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  56751. }
  56752. for (var renderEffectName in this._renderEffects) {
  56753. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56754. this._renderEffects[renderEffectName]._enable(cams);
  56755. }
  56756. }
  56757. };
  56758. PostProcessRenderPipeline.prototype._update = function () {
  56759. for (var renderEffectName in this._renderEffects) {
  56760. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  56761. this._renderEffects[renderEffectName]._update();
  56762. }
  56763. }
  56764. for (var i = 0; i < this._cameras.length; i++) {
  56765. var cameraName = this._cameras[i].name;
  56766. if (this._renderEffectsForIsolatedPass[cameraName]) {
  56767. this._renderEffectsForIsolatedPass[cameraName]._update();
  56768. }
  56769. }
  56770. };
  56771. PostProcessRenderPipeline.prototype._reset = function () {
  56772. this._renderEffects = {};
  56773. this._renderEffectsForIsolatedPass = new Array();
  56774. };
  56775. PostProcessRenderPipeline.prototype.dispose = function () {
  56776. // Must be implemented by children
  56777. };
  56778. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  56779. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  56780. __decorate([
  56781. BABYLON.serialize()
  56782. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  56783. return PostProcessRenderPipeline;
  56784. }());
  56785. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  56786. })(BABYLON || (BABYLON = {}));
  56787. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  56788. var BABYLON;
  56789. (function (BABYLON) {
  56790. var DepthRenderer = /** @class */ (function () {
  56791. function DepthRenderer(scene, type) {
  56792. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  56793. var _this = this;
  56794. this._scene = scene;
  56795. var engine = scene.getEngine();
  56796. // Render target
  56797. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  56798. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56799. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56800. this._depthMap.refreshRate = 1;
  56801. this._depthMap.renderParticles = false;
  56802. this._depthMap.renderList = null;
  56803. // set default depth value to 1.0 (far away)
  56804. this._depthMap.onClearObservable.add(function (engine) {
  56805. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  56806. });
  56807. // Custom render function
  56808. var renderSubMesh = function (subMesh) {
  56809. var mesh = subMesh.getRenderingMesh();
  56810. var scene = _this._scene;
  56811. var engine = scene.getEngine();
  56812. var material = subMesh.getMaterial();
  56813. if (!material) {
  56814. return;
  56815. }
  56816. // Culling
  56817. engine.setState(material.backFaceCulling);
  56818. // Managing instances
  56819. var batch = mesh._getInstancesRenderList(subMesh._id);
  56820. if (batch.mustReturn) {
  56821. return;
  56822. }
  56823. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  56824. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  56825. engine.enableEffect(_this._effect);
  56826. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  56827. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  56828. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  56829. // Alpha test
  56830. if (material && material.needAlphaTesting()) {
  56831. var alphaTexture = material.getAlphaTestTexture();
  56832. if (alphaTexture) {
  56833. _this._effect.setTexture("diffuseSampler", alphaTexture);
  56834. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  56835. }
  56836. }
  56837. // Bones
  56838. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56839. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  56840. }
  56841. // Draw
  56842. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  56843. }
  56844. };
  56845. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  56846. var index;
  56847. if (depthOnlySubMeshes.length) {
  56848. engine.setColorWrite(false);
  56849. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  56850. renderSubMesh(depthOnlySubMeshes.data[index]);
  56851. }
  56852. engine.setColorWrite(true);
  56853. }
  56854. for (index = 0; index < opaqueSubMeshes.length; index++) {
  56855. renderSubMesh(opaqueSubMeshes.data[index]);
  56856. }
  56857. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  56858. renderSubMesh(alphaTestSubMeshes.data[index]);
  56859. }
  56860. };
  56861. }
  56862. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  56863. var material = subMesh.getMaterial();
  56864. if (material.disableDepthWrite) {
  56865. return false;
  56866. }
  56867. var defines = [];
  56868. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56869. var mesh = subMesh.getMesh();
  56870. // Alpha test
  56871. if (material && material.needAlphaTesting()) {
  56872. defines.push("#define ALPHATEST");
  56873. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56874. attribs.push(BABYLON.VertexBuffer.UVKind);
  56875. defines.push("#define UV1");
  56876. }
  56877. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56879. defines.push("#define UV2");
  56880. }
  56881. }
  56882. // Bones
  56883. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56884. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56885. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56886. if (mesh.numBoneInfluencers > 4) {
  56887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56889. }
  56890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56891. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  56892. }
  56893. else {
  56894. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56895. }
  56896. // Instances
  56897. if (useInstances) {
  56898. defines.push("#define INSTANCES");
  56899. attribs.push("world0");
  56900. attribs.push("world1");
  56901. attribs.push("world2");
  56902. attribs.push("world3");
  56903. }
  56904. // Get correct effect
  56905. var join = defines.join("\n");
  56906. if (this._cachedDefines !== join) {
  56907. this._cachedDefines = join;
  56908. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  56909. }
  56910. return this._effect.isReady();
  56911. };
  56912. DepthRenderer.prototype.getDepthMap = function () {
  56913. return this._depthMap;
  56914. };
  56915. // Methods
  56916. DepthRenderer.prototype.dispose = function () {
  56917. this._depthMap.dispose();
  56918. };
  56919. return DepthRenderer;
  56920. }());
  56921. BABYLON.DepthRenderer = DepthRenderer;
  56922. })(BABYLON || (BABYLON = {}));
  56923. //# sourceMappingURL=babylon.depthRenderer.js.map
  56924. var BABYLON;
  56925. (function (BABYLON) {
  56926. var SSAORenderingPipeline = /** @class */ (function (_super) {
  56927. __extends(SSAORenderingPipeline, _super);
  56928. /**
  56929. * @constructor
  56930. * @param {string} name - The rendering pipeline name
  56931. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56932. * @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 }
  56933. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56934. */
  56935. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  56936. var _this = _super.call(this, scene.getEngine(), name) || this;
  56937. // Members
  56938. /**
  56939. * The PassPostProcess id in the pipeline that contains the original scene color
  56940. * @type {string}
  56941. */
  56942. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  56943. /**
  56944. * The SSAO PostProcess id in the pipeline
  56945. * @type {string}
  56946. */
  56947. _this.SSAORenderEffect = "SSAORenderEffect";
  56948. /**
  56949. * The horizontal blur PostProcess id in the pipeline
  56950. * @type {string}
  56951. */
  56952. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  56953. /**
  56954. * The vertical blur PostProcess id in the pipeline
  56955. * @type {string}
  56956. */
  56957. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  56958. /**
  56959. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  56960. * @type {string}
  56961. */
  56962. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  56963. /**
  56964. * The output strength of the SSAO post-process. Default value is 1.0.
  56965. * @type {number}
  56966. */
  56967. _this.totalStrength = 1.0;
  56968. /**
  56969. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  56970. * @type {number}
  56971. */
  56972. _this.radius = 0.0001;
  56973. /**
  56974. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  56975. * Must not be equal to fallOff and superior to fallOff.
  56976. * Default value is 0.975
  56977. * @type {number}
  56978. */
  56979. _this.area = 0.0075;
  56980. /**
  56981. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  56982. * Must not be equal to area and inferior to area.
  56983. * Default value is 0.0
  56984. * @type {number}
  56985. */
  56986. _this.fallOff = 0.000001;
  56987. /**
  56988. * The base color of the SSAO post-process
  56989. * The final result is "base + ssao" between [0, 1]
  56990. * @type {number}
  56991. */
  56992. _this.base = 0.5;
  56993. _this._firstUpdate = true;
  56994. _this._scene = scene;
  56995. // Set up assets
  56996. _this._createRandomTexture();
  56997. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  56998. var ssaoRatio = ratio.ssaoRatio || ratio;
  56999. var combineRatio = ratio.combineRatio || ratio;
  57000. _this._ratio = {
  57001. ssaoRatio: ssaoRatio,
  57002. combineRatio: combineRatio
  57003. };
  57004. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57005. _this._createSSAOPostProcess(ssaoRatio);
  57006. _this._createBlurPostProcess(ssaoRatio);
  57007. _this._createSSAOCombinePostProcess(combineRatio);
  57008. // Set up pipeline
  57009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57011. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57012. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57013. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57014. // Finish
  57015. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57016. if (cameras)
  57017. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57018. return _this;
  57019. }
  57020. // Public Methods
  57021. /**
  57022. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57023. */
  57024. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57025. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57026. for (var i = 0; i < this._scene.cameras.length; i++) {
  57027. var camera = this._scene.cameras[i];
  57028. this._originalColorPostProcess.dispose(camera);
  57029. this._ssaoPostProcess.dispose(camera);
  57030. this._blurHPostProcess.dispose(camera);
  57031. this._blurVPostProcess.dispose(camera);
  57032. this._ssaoCombinePostProcess.dispose(camera);
  57033. }
  57034. this._randomTexture.dispose();
  57035. if (disableDepthRender)
  57036. this._scene.disableDepthRenderer();
  57037. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57038. _super.prototype.dispose.call(this);
  57039. };
  57040. // Private Methods
  57041. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57042. var _this = this;
  57043. /*
  57044. var samplerOffsets = [
  57045. -8.0, -6.0, -4.0, -2.0,
  57046. 0.0,
  57047. 2.0, 4.0, 6.0, 8.0
  57048. ];
  57049. */
  57050. var samplerOffsets = new Array();
  57051. for (var i = -8; i < 8; i++) {
  57052. samplerOffsets.push(i * 2);
  57053. }
  57054. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57055. this._blurHPostProcess.onApply = function (effect) {
  57056. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57057. effect.setTexture("depthSampler", _this._depthTexture);
  57058. if (_this._firstUpdate) {
  57059. effect.setArray("samplerOffsets", samplerOffsets);
  57060. }
  57061. };
  57062. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57063. this._blurVPostProcess.onApply = function (effect) {
  57064. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57065. effect.setTexture("depthSampler", _this._depthTexture);
  57066. if (_this._firstUpdate) {
  57067. effect.setArray("samplerOffsets", samplerOffsets);
  57068. _this._firstUpdate = false;
  57069. }
  57070. };
  57071. };
  57072. SSAORenderingPipeline.prototype._rebuild = function () {
  57073. this._firstUpdate = true;
  57074. _super.prototype._rebuild.call(this);
  57075. };
  57076. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57077. var _this = this;
  57078. var numSamples = 16;
  57079. var sampleSphere = [
  57080. 0.5381, 0.1856, -0.4319,
  57081. 0.1379, 0.2486, 0.4430,
  57082. 0.3371, 0.5679, -0.0057,
  57083. -0.6999, -0.0451, -0.0019,
  57084. 0.0689, -0.1598, -0.8547,
  57085. 0.0560, 0.0069, -0.1843,
  57086. -0.0146, 0.1402, 0.0762,
  57087. 0.0100, -0.1924, -0.0344,
  57088. -0.3577, -0.5301, -0.4358,
  57089. -0.3169, 0.1063, 0.0158,
  57090. 0.0103, -0.5869, 0.0046,
  57091. -0.0897, -0.4940, 0.3287,
  57092. 0.7119, -0.0154, -0.0918,
  57093. -0.0533, 0.0596, -0.5411,
  57094. 0.0352, -0.0631, 0.5460,
  57095. -0.4776, 0.2847, -0.0271
  57096. ];
  57097. var samplesFactor = 1.0 / numSamples;
  57098. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57099. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57100. "area", "fallOff", "base", "range", "viewport"
  57101. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57102. this._ssaoPostProcess.onApply = function (effect) {
  57103. if (_this._firstUpdate) {
  57104. effect.setArray3("sampleSphere", sampleSphere);
  57105. effect.setFloat("samplesFactor", samplesFactor);
  57106. effect.setFloat("randTextureTiles", 4.0);
  57107. }
  57108. effect.setFloat("totalStrength", _this.totalStrength);
  57109. effect.setFloat("radius", _this.radius);
  57110. effect.setFloat("area", _this.area);
  57111. effect.setFloat("fallOff", _this.fallOff);
  57112. effect.setFloat("base", _this.base);
  57113. effect.setTexture("textureSampler", _this._depthTexture);
  57114. effect.setTexture("randomSampler", _this._randomTexture);
  57115. };
  57116. };
  57117. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57118. var _this = this;
  57119. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57120. this._ssaoCombinePostProcess.onApply = function (effect) {
  57121. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57122. };
  57123. };
  57124. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57125. var size = 512;
  57126. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57127. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57128. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57129. var context = this._randomTexture.getContext();
  57130. var rand = function (min, max) {
  57131. return Math.random() * (max - min) + min;
  57132. };
  57133. var randVector = BABYLON.Vector3.Zero();
  57134. for (var x = 0; x < size; x++) {
  57135. for (var y = 0; y < size; y++) {
  57136. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57137. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57138. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57139. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57140. context.fillRect(x, y, 1, 1);
  57141. }
  57142. }
  57143. this._randomTexture.update(false);
  57144. };
  57145. __decorate([
  57146. BABYLON.serialize()
  57147. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57148. __decorate([
  57149. BABYLON.serialize()
  57150. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57151. __decorate([
  57152. BABYLON.serialize()
  57153. ], SSAORenderingPipeline.prototype, "area", void 0);
  57154. __decorate([
  57155. BABYLON.serialize()
  57156. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57157. __decorate([
  57158. BABYLON.serialize()
  57159. ], SSAORenderingPipeline.prototype, "base", void 0);
  57160. __decorate([
  57161. BABYLON.serialize()
  57162. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57163. return SSAORenderingPipeline;
  57164. }(BABYLON.PostProcessRenderPipeline));
  57165. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57166. })(BABYLON || (BABYLON = {}));
  57167. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57168. var BABYLON;
  57169. (function (BABYLON) {
  57170. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57171. __extends(SSAO2RenderingPipeline, _super);
  57172. /**
  57173. * @constructor
  57174. * @param {string} name - The rendering pipeline name
  57175. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57176. * @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 }
  57177. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57178. */
  57179. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57180. var _this = _super.call(this, scene.getEngine(), name) || this;
  57181. // Members
  57182. /**
  57183. * The PassPostProcess id in the pipeline that contains the original scene color
  57184. * @type {string}
  57185. */
  57186. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57187. /**
  57188. * The SSAO PostProcess id in the pipeline
  57189. * @type {string}
  57190. */
  57191. _this.SSAORenderEffect = "SSAORenderEffect";
  57192. /**
  57193. * The horizontal blur PostProcess id in the pipeline
  57194. * @type {string}
  57195. */
  57196. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57197. /**
  57198. * The vertical blur PostProcess id in the pipeline
  57199. * @type {string}
  57200. */
  57201. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57202. /**
  57203. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57204. * @type {string}
  57205. */
  57206. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57207. /**
  57208. * The output strength of the SSAO post-process. Default value is 1.0.
  57209. * @type {number}
  57210. */
  57211. _this.totalStrength = 1.0;
  57212. /**
  57213. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57214. * @type {number}
  57215. */
  57216. _this.maxZ = 100.0;
  57217. /**
  57218. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57219. * @type {number}
  57220. */
  57221. _this.minZAspect = 0.2;
  57222. /**
  57223. * Number of samples used for the SSAO calculations. Default value is 8
  57224. * @type {number}
  57225. */
  57226. _this._samples = 8;
  57227. /**
  57228. * Are we using bilateral blur ?
  57229. * @type {boolean}
  57230. */
  57231. _this._expensiveBlur = true;
  57232. /**
  57233. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57234. * @type {number}
  57235. */
  57236. _this.radius = 2.0;
  57237. /**
  57238. * The base color of the SSAO post-process
  57239. * The final result is "base + ssao" between [0, 1]
  57240. * @type {number}
  57241. */
  57242. _this.base = 0.1;
  57243. _this._firstUpdate = true;
  57244. _this._scene = scene;
  57245. if (!_this.isSupported) {
  57246. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57247. return _this;
  57248. }
  57249. var ssaoRatio = ratio.ssaoRatio || ratio;
  57250. var blurRatio = ratio.blurRatio || ratio;
  57251. _this._ratio = {
  57252. ssaoRatio: ssaoRatio,
  57253. blurRatio: blurRatio
  57254. };
  57255. // Set up assets
  57256. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57257. _this._createRandomTexture();
  57258. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57259. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57260. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57261. _this._createSSAOPostProcess(1.0);
  57262. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57263. _this._createSSAOCombinePostProcess(blurRatio);
  57264. // Set up pipeline
  57265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57266. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57270. // Finish
  57271. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57272. if (cameras)
  57273. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57274. return _this;
  57275. }
  57276. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57277. get: function () {
  57278. return this._samples;
  57279. },
  57280. set: function (n) {
  57281. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57282. this._samples = n;
  57283. this._sampleSphere = this._generateHemisphere();
  57284. this._firstUpdate = true;
  57285. },
  57286. enumerable: true,
  57287. configurable: true
  57288. });
  57289. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57290. get: function () {
  57291. return this._expensiveBlur;
  57292. },
  57293. set: function (b) {
  57294. 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"]);
  57295. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57296. this._expensiveBlur = b;
  57297. this._firstUpdate = true;
  57298. },
  57299. enumerable: true,
  57300. configurable: true
  57301. });
  57302. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57303. /**
  57304. * Support test.
  57305. * @type {boolean}
  57306. */
  57307. get: function () {
  57308. var engine = BABYLON.Engine.LastCreatedEngine;
  57309. if (!engine) {
  57310. return false;
  57311. }
  57312. return engine.getCaps().drawBuffersExtension;
  57313. },
  57314. enumerable: true,
  57315. configurable: true
  57316. });
  57317. // Public Methods
  57318. /**
  57319. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57320. */
  57321. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57322. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57323. for (var i = 0; i < this._scene.cameras.length; i++) {
  57324. var camera = this._scene.cameras[i];
  57325. this._originalColorPostProcess.dispose(camera);
  57326. this._ssaoPostProcess.dispose(camera);
  57327. this._blurHPostProcess.dispose(camera);
  57328. this._blurVPostProcess.dispose(camera);
  57329. this._ssaoCombinePostProcess.dispose(camera);
  57330. }
  57331. this._randomTexture.dispose();
  57332. if (disableGeometryBufferRenderer)
  57333. this._scene.disableGeometryBufferRenderer();
  57334. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57335. _super.prototype.dispose.call(this);
  57336. };
  57337. // Private Methods
  57338. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57339. var _this = this;
  57340. this._samplerOffsets = [];
  57341. var expensive = this.expensiveBlur;
  57342. for (var i = -8; i < 8; i++) {
  57343. this._samplerOffsets.push(i * 2 + 0.5);
  57344. }
  57345. 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");
  57346. this._blurHPostProcess.onApply = function (effect) {
  57347. if (!_this._scene.activeCamera) {
  57348. return;
  57349. }
  57350. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57351. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57352. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57353. effect.setFloat("radius", _this.radius);
  57354. effect.setTexture("depthSampler", _this._depthTexture);
  57355. if (_this._firstUpdate) {
  57356. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57357. }
  57358. };
  57359. 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");
  57360. this._blurVPostProcess.onApply = function (effect) {
  57361. if (!_this._scene.activeCamera) {
  57362. return;
  57363. }
  57364. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57365. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57366. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57367. effect.setFloat("radius", _this.radius);
  57368. effect.setTexture("depthSampler", _this._depthTexture);
  57369. if (_this._firstUpdate) {
  57370. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57371. _this._firstUpdate = false;
  57372. }
  57373. };
  57374. };
  57375. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57376. this._firstUpdate = true;
  57377. _super.prototype._rebuild.call(this);
  57378. };
  57379. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57380. var numSamples = this.samples;
  57381. var result = [];
  57382. var vector, scale;
  57383. var rand = function (min, max) {
  57384. return Math.random() * (max - min) + min;
  57385. };
  57386. var i = 0;
  57387. while (i < numSamples) {
  57388. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57389. vector.normalize();
  57390. scale = i / numSamples;
  57391. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57392. vector.scaleInPlace(scale);
  57393. result.push(vector.x, vector.y, vector.z);
  57394. i++;
  57395. }
  57396. return result;
  57397. };
  57398. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57399. var _this = this;
  57400. var numSamples = this.samples;
  57401. this._sampleSphere = this._generateHemisphere();
  57402. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57403. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57404. "base", "range", "projection", "near", "far", "texelSize",
  57405. "xViewport", "yViewport", "maxZ", "minZAspect"
  57406. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57407. this._ssaoPostProcess.onApply = function (effect) {
  57408. if (_this._firstUpdate) {
  57409. effect.setArray3("sampleSphere", _this._sampleSphere);
  57410. effect.setFloat("randTextureTiles", 4.0);
  57411. }
  57412. if (!_this._scene.activeCamera) {
  57413. return;
  57414. }
  57415. effect.setFloat("samplesFactor", 1 / _this.samples);
  57416. effect.setFloat("totalStrength", _this.totalStrength);
  57417. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57418. effect.setFloat("radius", _this.radius);
  57419. effect.setFloat("maxZ", _this.maxZ);
  57420. effect.setFloat("minZAspect", _this.minZAspect);
  57421. effect.setFloat("base", _this.base);
  57422. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57423. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57424. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57425. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57426. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57427. effect.setTexture("textureSampler", _this._depthTexture);
  57428. effect.setTexture("normalSampler", _this._normalTexture);
  57429. effect.setTexture("randomSampler", _this._randomTexture);
  57430. };
  57431. };
  57432. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57433. var _this = this;
  57434. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57435. this._ssaoCombinePostProcess.onApply = function (effect) {
  57436. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57437. };
  57438. };
  57439. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57440. var size = 512;
  57441. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57442. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57443. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57444. var context = this._randomTexture.getContext();
  57445. var rand = function (min, max) {
  57446. return Math.random() * (max - min) + min;
  57447. };
  57448. var randVector = BABYLON.Vector3.Zero();
  57449. for (var x = 0; x < size; x++) {
  57450. for (var y = 0; y < size; y++) {
  57451. randVector.x = rand(0.0, 1.0);
  57452. randVector.y = rand(0.0, 1.0);
  57453. randVector.z = 0.0;
  57454. randVector.normalize();
  57455. randVector.scaleInPlace(255);
  57456. randVector.x = Math.floor(randVector.x);
  57457. randVector.y = Math.floor(randVector.y);
  57458. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57459. context.fillRect(x, y, 1, 1);
  57460. }
  57461. }
  57462. this._randomTexture.update(false);
  57463. };
  57464. __decorate([
  57465. BABYLON.serialize()
  57466. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57467. __decorate([
  57468. BABYLON.serialize()
  57469. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57470. __decorate([
  57471. BABYLON.serialize()
  57472. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57473. __decorate([
  57474. BABYLON.serialize("samples")
  57475. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57476. __decorate([
  57477. BABYLON.serialize("expensiveBlur")
  57478. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57479. __decorate([
  57480. BABYLON.serialize()
  57481. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57482. __decorate([
  57483. BABYLON.serialize()
  57484. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57485. __decorate([
  57486. BABYLON.serialize()
  57487. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57488. return SSAO2RenderingPipeline;
  57489. }(BABYLON.PostProcessRenderPipeline));
  57490. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57491. })(BABYLON || (BABYLON = {}));
  57492. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57493. // BABYLON.JS Chromatic Aberration GLSL Shader
  57494. // Author: Olivier Guyot
  57495. // Separates very slightly R, G and B colors on the edges of the screen
  57496. // Inspired by Francois Tarlier & Martins Upitis
  57497. var BABYLON;
  57498. (function (BABYLON) {
  57499. var LensRenderingPipeline = /** @class */ (function (_super) {
  57500. __extends(LensRenderingPipeline, _super);
  57501. /**
  57502. * @constructor
  57503. *
  57504. * Effect parameters are as follow:
  57505. * {
  57506. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57507. * edge_blur: number; // from 0 to x (1 for realism)
  57508. * distortion: number; // from 0 to x (1 for realism)
  57509. * grain_amount: number; // from 0 to 1
  57510. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57511. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57512. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57513. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57514. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57515. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57516. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57517. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57518. * }
  57519. * Note: if an effect parameter is unset, effect is disabled
  57520. *
  57521. * @param {string} name - The rendering pipeline name
  57522. * @param {object} parameters - An object containing all parameters (see above)
  57523. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57524. * @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)
  57525. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57526. */
  57527. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57528. if (ratio === void 0) { ratio = 1.0; }
  57529. var _this = _super.call(this, scene.getEngine(), name) || this;
  57530. // Lens effects can be of the following:
  57531. // - chromatic aberration (slight shift of RGB colors)
  57532. // - blur on the edge of the lens
  57533. // - lens distortion
  57534. // - depth-of-field blur & highlights enhancing
  57535. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57536. // - grain effect (noise or custom texture)
  57537. // Two additional texture samplers are needed:
  57538. // - depth map (for depth-of-field)
  57539. // - grain texture
  57540. /**
  57541. * The chromatic aberration PostProcess id in the pipeline
  57542. * @type {string}
  57543. */
  57544. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57545. /**
  57546. * The highlights enhancing PostProcess id in the pipeline
  57547. * @type {string}
  57548. */
  57549. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57550. /**
  57551. * The depth-of-field PostProcess id in the pipeline
  57552. * @type {string}
  57553. */
  57554. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57555. _this._scene = scene;
  57556. // Fetch texture samplers
  57557. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57558. if (parameters.grain_texture) {
  57559. _this._grainTexture = parameters.grain_texture;
  57560. }
  57561. else {
  57562. _this._createGrainTexture();
  57563. }
  57564. // save parameters
  57565. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  57566. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  57567. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  57568. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  57569. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  57570. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  57571. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  57572. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  57573. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  57574. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  57575. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  57576. // Create effects
  57577. _this._createChromaticAberrationPostProcess(ratio);
  57578. _this._createHighlightsPostProcess(ratio);
  57579. _this._createDepthOfFieldPostProcess(ratio / 4);
  57580. // Set up pipeline
  57581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  57582. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  57583. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  57584. if (_this._highlightsGain === -1) {
  57585. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  57586. }
  57587. // Finish
  57588. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57589. if (cameras) {
  57590. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57591. }
  57592. return _this;
  57593. }
  57594. // public methods (self explanatory)
  57595. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  57596. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  57597. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  57598. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  57599. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  57600. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  57601. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  57602. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  57603. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  57604. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  57605. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  57606. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  57607. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  57608. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  57609. };
  57610. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  57611. this._highlightsPostProcess.updateEffect();
  57612. };
  57613. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  57614. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  57615. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  57616. this._highlightsGain = amount;
  57617. };
  57618. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  57619. if (this._highlightsGain === -1) {
  57620. this._highlightsGain = 1.0;
  57621. }
  57622. this._highlightsThreshold = amount;
  57623. };
  57624. LensRenderingPipeline.prototype.disableHighlights = function () {
  57625. this._highlightsGain = -1;
  57626. };
  57627. /**
  57628. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  57629. */
  57630. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57631. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57632. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57633. this._chromaticAberrationPostProcess = null;
  57634. this._highlightsPostProcess = null;
  57635. this._depthOfFieldPostProcess = null;
  57636. this._grainTexture.dispose();
  57637. if (disableDepthRender)
  57638. this._scene.disableDepthRenderer();
  57639. };
  57640. // colors shifting and distortion
  57641. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  57642. var _this = this;
  57643. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  57644. [], // samplers
  57645. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57646. this._chromaticAberrationPostProcess.onApply = function (effect) {
  57647. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  57648. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57649. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57650. };
  57651. };
  57652. // highlights enhancing
  57653. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  57654. var _this = this;
  57655. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  57656. [], // samplers
  57657. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  57658. this._highlightsPostProcess.onApply = function (effect) {
  57659. effect.setFloat('gain', _this._highlightsGain);
  57660. effect.setFloat('threshold', _this._highlightsThreshold);
  57661. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  57662. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57663. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57664. };
  57665. };
  57666. // colors shifting and distortion
  57667. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  57668. var _this = this;
  57669. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  57670. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  57671. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  57672. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57673. this._depthOfFieldPostProcess.onApply = function (effect) {
  57674. effect.setTexture("depthSampler", _this._depthTexture);
  57675. effect.setTexture("grainSampler", _this._grainTexture);
  57676. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  57677. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  57678. effect.setFloat('grain_amount', _this._grainAmount);
  57679. effect.setBool('blur_noise', _this._blurNoise);
  57680. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  57681. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  57682. effect.setFloat('distortion', _this._distortion);
  57683. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  57684. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  57685. effect.setFloat('aperture', _this._dofAperture);
  57686. effect.setFloat('darken', _this._dofDarken);
  57687. effect.setFloat('edge_blur', _this._edgeBlur);
  57688. effect.setBool('highlights', (_this._highlightsGain !== -1));
  57689. if (_this._scene.activeCamera) {
  57690. effect.setFloat('near', _this._scene.activeCamera.minZ);
  57691. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  57692. }
  57693. };
  57694. };
  57695. // creates a black and white random noise texture, 512x512
  57696. LensRenderingPipeline.prototype._createGrainTexture = function () {
  57697. var size = 512;
  57698. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57699. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57700. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57701. var context = this._grainTexture.getContext();
  57702. var rand = function (min, max) {
  57703. return Math.random() * (max - min) + min;
  57704. };
  57705. var value;
  57706. for (var x = 0; x < size; x++) {
  57707. for (var y = 0; y < size; y++) {
  57708. value = Math.floor(rand(0.42, 0.58) * 255);
  57709. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  57710. context.fillRect(x, y, 1, 1);
  57711. }
  57712. }
  57713. this._grainTexture.update(false);
  57714. };
  57715. return LensRenderingPipeline;
  57716. }(BABYLON.PostProcessRenderPipeline));
  57717. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  57718. })(BABYLON || (BABYLON = {}));
  57719. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  57720. var BABYLON;
  57721. (function (BABYLON) {
  57722. var StandardRenderingPipeline = /** @class */ (function (_super) {
  57723. __extends(StandardRenderingPipeline, _super);
  57724. /**
  57725. * @constructor
  57726. * @param {string} name - The rendering pipeline name
  57727. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57728. * @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)
  57729. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57730. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57731. */
  57732. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57733. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57734. var _this = _super.call(this, scene.getEngine(), name) || this;
  57735. _this.downSampleX4PostProcess = null;
  57736. _this.brightPassPostProcess = null;
  57737. _this.blurHPostProcesses = [];
  57738. _this.blurVPostProcesses = [];
  57739. _this.textureAdderPostProcess = null;
  57740. _this.volumetricLightPostProcess = null;
  57741. _this.volumetricLightSmoothXPostProcess = null;
  57742. _this.volumetricLightSmoothYPostProcess = null;
  57743. _this.volumetricLightMergePostProces = null;
  57744. _this.volumetricLightFinalPostProcess = null;
  57745. _this.luminancePostProcess = null;
  57746. _this.luminanceDownSamplePostProcesses = [];
  57747. _this.hdrPostProcess = null;
  57748. _this.textureAdderFinalPostProcess = null;
  57749. _this.lensFlareFinalPostProcess = null;
  57750. _this.hdrFinalPostProcess = null;
  57751. _this.lensFlarePostProcess = null;
  57752. _this.lensFlareComposePostProcess = null;
  57753. _this.motionBlurPostProcess = null;
  57754. _this.depthOfFieldPostProcess = null;
  57755. // Values
  57756. _this.brightThreshold = 1.0;
  57757. _this.blurWidth = 512.0;
  57758. _this.horizontalBlur = false;
  57759. _this.exposure = 1.0;
  57760. _this.lensTexture = null;
  57761. _this.volumetricLightCoefficient = 0.2;
  57762. _this.volumetricLightPower = 4.0;
  57763. _this.volumetricLightBlurScale = 64.0;
  57764. _this.sourceLight = null;
  57765. _this.hdrMinimumLuminance = 1.0;
  57766. _this.hdrDecreaseRate = 0.5;
  57767. _this.hdrIncreaseRate = 0.5;
  57768. _this.lensColorTexture = null;
  57769. _this.lensFlareStrength = 20.0;
  57770. _this.lensFlareGhostDispersal = 1.4;
  57771. _this.lensFlareHaloWidth = 0.7;
  57772. _this.lensFlareDistortionStrength = 16.0;
  57773. _this.lensStarTexture = null;
  57774. _this.lensFlareDirtTexture = null;
  57775. _this.depthOfFieldDistance = 10.0;
  57776. _this.depthOfFieldBlurWidth = 64.0;
  57777. _this.motionStrength = 1.0;
  57778. // IAnimatable
  57779. _this.animations = [];
  57780. _this._currentDepthOfFieldSource = null;
  57781. _this._hdrCurrentLuminance = 1.0;
  57782. // Getters and setters
  57783. _this._bloomEnabled = true;
  57784. _this._depthOfFieldEnabled = false;
  57785. _this._vlsEnabled = false;
  57786. _this._lensFlareEnabled = false;
  57787. _this._hdrEnabled = false;
  57788. _this._motionBlurEnabled = false;
  57789. _this._motionBlurSamples = 64.0;
  57790. _this._volumetricLightStepsCount = 50.0;
  57791. _this._cameras = cameras || [];
  57792. // Initialize
  57793. _this._scene = scene;
  57794. _this._basePostProcess = originalPostProcess;
  57795. _this._ratio = ratio;
  57796. // Misc
  57797. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57798. // Finish
  57799. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57800. _this._buildPipeline();
  57801. return _this;
  57802. }
  57803. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  57804. get: function () {
  57805. return this._bloomEnabled;
  57806. },
  57807. set: function (enabled) {
  57808. if (this._bloomEnabled === enabled) {
  57809. return;
  57810. }
  57811. this._bloomEnabled = enabled;
  57812. this._buildPipeline();
  57813. },
  57814. enumerable: true,
  57815. configurable: true
  57816. });
  57817. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57818. get: function () {
  57819. return this._depthOfFieldEnabled;
  57820. },
  57821. set: function (enabled) {
  57822. if (this._depthOfFieldEnabled === enabled) {
  57823. return;
  57824. }
  57825. this._depthOfFieldEnabled = enabled;
  57826. this._buildPipeline();
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57832. get: function () {
  57833. return this._lensFlareEnabled;
  57834. },
  57835. set: function (enabled) {
  57836. if (this._lensFlareEnabled === enabled) {
  57837. return;
  57838. }
  57839. this._lensFlareEnabled = enabled;
  57840. this._buildPipeline();
  57841. },
  57842. enumerable: true,
  57843. configurable: true
  57844. });
  57845. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  57846. get: function () {
  57847. return this._hdrEnabled;
  57848. },
  57849. set: function (enabled) {
  57850. if (this._hdrEnabled === enabled) {
  57851. return;
  57852. }
  57853. this._hdrEnabled = enabled;
  57854. this._buildPipeline();
  57855. },
  57856. enumerable: true,
  57857. configurable: true
  57858. });
  57859. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  57860. get: function () {
  57861. return this._vlsEnabled;
  57862. },
  57863. set: function (enabled) {
  57864. if (this._vlsEnabled === enabled) {
  57865. return;
  57866. }
  57867. if (enabled) {
  57868. var geometry = this._scene.enableGeometryBufferRenderer();
  57869. if (!geometry) {
  57870. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  57871. return;
  57872. }
  57873. }
  57874. this._vlsEnabled = enabled;
  57875. this._buildPipeline();
  57876. },
  57877. enumerable: true,
  57878. configurable: true
  57879. });
  57880. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  57881. get: function () {
  57882. return this._motionBlurEnabled;
  57883. },
  57884. set: function (enabled) {
  57885. if (this._motionBlurEnabled === enabled) {
  57886. return;
  57887. }
  57888. this._motionBlurEnabled = enabled;
  57889. this._buildPipeline();
  57890. },
  57891. enumerable: true,
  57892. configurable: true
  57893. });
  57894. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  57895. get: function () {
  57896. return this._volumetricLightStepsCount;
  57897. },
  57898. set: function (count) {
  57899. if (this.volumetricLightPostProcess) {
  57900. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  57901. }
  57902. this._volumetricLightStepsCount = count;
  57903. },
  57904. enumerable: true,
  57905. configurable: true
  57906. });
  57907. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  57908. get: function () {
  57909. return this._motionBlurSamples;
  57910. },
  57911. set: function (samples) {
  57912. if (this.motionBlurPostProcess) {
  57913. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  57914. }
  57915. this._motionBlurSamples = samples;
  57916. },
  57917. enumerable: true,
  57918. configurable: true
  57919. });
  57920. StandardRenderingPipeline.prototype._buildPipeline = function () {
  57921. var _this = this;
  57922. var ratio = this._ratio;
  57923. var scene = this._scene;
  57924. this._disposePostProcesses();
  57925. this._reset();
  57926. // Create pass post-process
  57927. if (!this._basePostProcess) {
  57928. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  57929. this.originalPostProcess.onApply = function (effect) {
  57930. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  57931. };
  57932. }
  57933. else {
  57934. this.originalPostProcess = this._basePostProcess;
  57935. }
  57936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57937. this._currentDepthOfFieldSource = this.originalPostProcess;
  57938. if (this._vlsEnabled) {
  57939. // Create volumetric light
  57940. this._createVolumetricLightPostProcess(scene, ratio);
  57941. // Create volumetric light final post-process
  57942. 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);
  57943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  57944. }
  57945. if (this._bloomEnabled) {
  57946. // Create down sample X4 post-process
  57947. this._createDownSampleX4PostProcess(scene, ratio / 2);
  57948. // Create bright pass post-process
  57949. this._createBrightPassPostProcess(scene, ratio / 2);
  57950. // Create gaussian blur post-processes (down sampling blurs)
  57951. this._createBlurPostProcesses(scene, ratio / 4, 1);
  57952. // Create texture adder post-process
  57953. this._createTextureAdderPostProcess(scene, ratio);
  57954. // Create depth-of-field source post-process
  57955. 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);
  57956. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57957. }
  57958. if (this._lensFlareEnabled) {
  57959. // Create lens flare post-process
  57960. this._createLensFlarePostProcess(scene, ratio);
  57961. // Create depth-of-field source post-process post lens-flare and disable it now
  57962. 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);
  57963. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  57964. }
  57965. if (this._hdrEnabled) {
  57966. // Create luminance
  57967. this._createLuminancePostProcesses(scene, this._floatTextureType);
  57968. // Create HDR
  57969. this._createHdrPostProcess(scene, ratio);
  57970. // Create depth-of-field source post-process post hdr and disable it now
  57971. 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);
  57972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  57973. }
  57974. if (this._depthOfFieldEnabled) {
  57975. // Create gaussian blur used by depth-of-field
  57976. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  57977. // Create depth-of-field post-process
  57978. this._createDepthOfFieldPostProcess(scene, ratio);
  57979. }
  57980. if (this._motionBlurEnabled) {
  57981. // Create motion blur post-process
  57982. this._createMotionBlurPostProcess(scene, ratio);
  57983. }
  57984. if (this._cameras !== null) {
  57985. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57986. }
  57987. };
  57988. // Down Sample X4 Post-Processs
  57989. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57990. var _this = this;
  57991. var downSampleX4Offsets = new Array(32);
  57992. 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);
  57993. this.downSampleX4PostProcess.onApply = function (effect) {
  57994. var id = 0;
  57995. var width = _this.downSampleX4PostProcess.width;
  57996. var height = _this.downSampleX4PostProcess.height;
  57997. for (var i = -2; i < 2; i++) {
  57998. for (var j = -2; j < 2; j++) {
  57999. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58000. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58001. id += 2;
  58002. }
  58003. }
  58004. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58005. };
  58006. // Add to pipeline
  58007. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58008. };
  58009. // Brightpass Post-Process
  58010. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58011. var _this = this;
  58012. var brightOffsets = new Array(8);
  58013. 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);
  58014. this.brightPassPostProcess.onApply = function (effect) {
  58015. var sU = (1.0 / _this.brightPassPostProcess.width);
  58016. var sV = (1.0 / _this.brightPassPostProcess.height);
  58017. brightOffsets[0] = -0.5 * sU;
  58018. brightOffsets[1] = 0.5 * sV;
  58019. brightOffsets[2] = 0.5 * sU;
  58020. brightOffsets[3] = 0.5 * sV;
  58021. brightOffsets[4] = -0.5 * sU;
  58022. brightOffsets[5] = -0.5 * sV;
  58023. brightOffsets[6] = 0.5 * sU;
  58024. brightOffsets[7] = -0.5 * sV;
  58025. effect.setArray2("dsOffsets", brightOffsets);
  58026. effect.setFloat("brightThreshold", _this.brightThreshold);
  58027. };
  58028. // Add to pipeline
  58029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58030. };
  58031. // Create blur H&V post-processes
  58032. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58033. var _this = this;
  58034. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58035. var engine = scene.getEngine();
  58036. 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);
  58037. 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);
  58038. blurX.onActivateObservable.add(function () {
  58039. var dw = blurX.width / engine.getRenderWidth();
  58040. blurX.kernel = _this[blurWidthKey] * dw;
  58041. });
  58042. blurY.onActivateObservable.add(function () {
  58043. var dw = blurY.height / engine.getRenderHeight();
  58044. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58045. });
  58046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58047. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58048. this.blurHPostProcesses.push(blurX);
  58049. this.blurVPostProcesses.push(blurY);
  58050. };
  58051. // Create texture adder post-process
  58052. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58053. var _this = this;
  58054. 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);
  58055. this.textureAdderPostProcess.onApply = function (effect) {
  58056. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58057. effect.setTexture("lensSampler", _this.lensTexture);
  58058. effect.setFloat("exposure", _this.exposure);
  58059. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58060. };
  58061. // Add to pipeline
  58062. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58063. };
  58064. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58065. var _this = this;
  58066. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58067. geometryRenderer.enablePosition = true;
  58068. var geometry = geometryRenderer.getGBuffer();
  58069. // Base post-process
  58070. 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));
  58071. var depthValues = BABYLON.Vector2.Zero();
  58072. this.volumetricLightPostProcess.onApply = function (effect) {
  58073. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58074. var generator = _this.sourceLight.getShadowGenerator();
  58075. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58076. effect.setTexture("positionSampler", geometry.textures[2]);
  58077. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58078. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58079. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58080. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58081. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58082. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58083. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58084. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58085. effect.setVector2("depthValues", depthValues);
  58086. }
  58087. };
  58088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58089. // Smooth
  58090. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58091. // Merge
  58092. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58093. this.volumetricLightMergePostProces.onApply = function (effect) {
  58094. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58095. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58096. };
  58097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58098. };
  58099. // Create luminance
  58100. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58101. var _this = this;
  58102. // Create luminance
  58103. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58104. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58105. var offsets = [];
  58106. this.luminancePostProcess.onApply = function (effect) {
  58107. var sU = (1.0 / _this.luminancePostProcess.width);
  58108. var sV = (1.0 / _this.luminancePostProcess.height);
  58109. offsets[0] = -0.5 * sU;
  58110. offsets[1] = 0.5 * sV;
  58111. offsets[2] = 0.5 * sU;
  58112. offsets[3] = 0.5 * sV;
  58113. offsets[4] = -0.5 * sU;
  58114. offsets[5] = -0.5 * sV;
  58115. offsets[6] = 0.5 * sU;
  58116. offsets[7] = -0.5 * sV;
  58117. effect.setArray2("lumOffsets", offsets);
  58118. };
  58119. // Add to pipeline
  58120. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58121. // Create down sample luminance
  58122. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58123. var size = Math.pow(3, i);
  58124. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58125. if (i === 0) {
  58126. defines += "#define FINAL_DOWN_SAMPLER";
  58127. }
  58128. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58129. this.luminanceDownSamplePostProcesses.push(postProcess);
  58130. }
  58131. // Create callbacks and add effects
  58132. var lastLuminance = this.luminancePostProcess;
  58133. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58134. var downSampleOffsets = new Array(18);
  58135. pp.onApply = function (effect) {
  58136. if (!lastLuminance) {
  58137. return;
  58138. }
  58139. var id = 0;
  58140. for (var x = -1; x < 2; x++) {
  58141. for (var y = -1; y < 2; y++) {
  58142. downSampleOffsets[id] = x / lastLuminance.width;
  58143. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58144. id += 2;
  58145. }
  58146. }
  58147. effect.setArray2("dsOffsets", downSampleOffsets);
  58148. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58149. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58150. lastLuminance = _this.luminancePostProcess;
  58151. }
  58152. else {
  58153. lastLuminance = pp;
  58154. }
  58155. };
  58156. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58157. pp.onAfterRender = function (effect) {
  58158. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58159. 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);
  58160. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58161. };
  58162. }
  58163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58164. });
  58165. };
  58166. // Create HDR post-process
  58167. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58168. var _this = this;
  58169. 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);
  58170. var outputLiminance = 1;
  58171. var time = 0;
  58172. var lastTime = 0;
  58173. this.hdrPostProcess.onApply = function (effect) {
  58174. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58175. time += scene.getEngine().getDeltaTime();
  58176. if (outputLiminance < 0) {
  58177. outputLiminance = _this._hdrCurrentLuminance;
  58178. }
  58179. else {
  58180. var dt = (lastTime - time) / 1000.0;
  58181. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58182. outputLiminance += _this.hdrDecreaseRate * dt;
  58183. }
  58184. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58185. outputLiminance -= _this.hdrIncreaseRate * dt;
  58186. }
  58187. else {
  58188. outputLiminance = _this._hdrCurrentLuminance;
  58189. }
  58190. }
  58191. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58192. effect.setFloat("averageLuminance", outputLiminance);
  58193. lastTime = time;
  58194. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58195. };
  58196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58197. };
  58198. // Create lens flare post-process
  58199. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58200. var _this = this;
  58201. 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);
  58202. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58203. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58204. 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);
  58205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58206. var resolution = new BABYLON.Vector2(0, 0);
  58207. // Lens flare
  58208. this.lensFlarePostProcess.onApply = function (effect) {
  58209. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58210. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58211. effect.setFloat("strength", _this.lensFlareStrength);
  58212. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58213. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58214. // Shift
  58215. resolution.x = _this.lensFlarePostProcess.width;
  58216. resolution.y = _this.lensFlarePostProcess.height;
  58217. effect.setVector2("resolution", resolution);
  58218. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58219. };
  58220. // Compose
  58221. 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);
  58222. 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);
  58223. this.lensFlareComposePostProcess.onApply = function (effect) {
  58224. if (!_this._scene.activeCamera) {
  58225. return;
  58226. }
  58227. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58228. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58229. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58230. // Lens start rotation matrix
  58231. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58232. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58233. 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));
  58234. camRot *= 4.0;
  58235. 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);
  58236. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58237. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58238. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58239. };
  58240. };
  58241. // Create depth-of-field post-process
  58242. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58243. var _this = this;
  58244. 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);
  58245. this.depthOfFieldPostProcess.onApply = function (effect) {
  58246. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58247. effect.setTexture("depthSampler", _this._getDepthTexture());
  58248. effect.setFloat("distance", _this.depthOfFieldDistance);
  58249. };
  58250. // Add to pipeline
  58251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58252. };
  58253. // Create motion blur post-process
  58254. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58255. var _this = this;
  58256. 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);
  58257. var motionScale = 0;
  58258. var prevViewProjection = BABYLON.Matrix.Identity();
  58259. var invViewProjection = BABYLON.Matrix.Identity();
  58260. var viewProjection = BABYLON.Matrix.Identity();
  58261. var screenSize = BABYLON.Vector2.Zero();
  58262. this.motionBlurPostProcess.onApply = function (effect) {
  58263. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58264. viewProjection.invertToRef(invViewProjection);
  58265. effect.setMatrix("inverseViewProjection", invViewProjection);
  58266. effect.setMatrix("prevViewProjection", prevViewProjection);
  58267. prevViewProjection = viewProjection;
  58268. screenSize.x = _this.motionBlurPostProcess.width;
  58269. screenSize.y = _this.motionBlurPostProcess.height;
  58270. effect.setVector2("screenSize", screenSize);
  58271. motionScale = scene.getEngine().getFps() / 60.0;
  58272. effect.setFloat("motionScale", motionScale);
  58273. effect.setFloat("motionStrength", _this.motionStrength);
  58274. effect.setTexture("depthSampler", _this._getDepthTexture());
  58275. };
  58276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58277. };
  58278. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58279. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58280. var renderer = this._scene.enableGeometryBufferRenderer();
  58281. return renderer.getGBuffer().textures[0];
  58282. }
  58283. return this._scene.enableDepthRenderer().getDepthMap();
  58284. };
  58285. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58286. for (var i = 0; i < this._cameras.length; i++) {
  58287. var camera = this._cameras[i];
  58288. if (this.originalPostProcess) {
  58289. this.originalPostProcess.dispose(camera);
  58290. }
  58291. if (this.downSampleX4PostProcess) {
  58292. this.downSampleX4PostProcess.dispose(camera);
  58293. }
  58294. if (this.brightPassPostProcess) {
  58295. this.brightPassPostProcess.dispose(camera);
  58296. }
  58297. if (this.textureAdderPostProcess) {
  58298. this.textureAdderPostProcess.dispose(camera);
  58299. }
  58300. if (this.textureAdderFinalPostProcess) {
  58301. this.textureAdderFinalPostProcess.dispose(camera);
  58302. }
  58303. if (this.volumetricLightPostProcess) {
  58304. this.volumetricLightPostProcess.dispose(camera);
  58305. }
  58306. if (this.volumetricLightSmoothXPostProcess) {
  58307. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58308. }
  58309. if (this.volumetricLightSmoothYPostProcess) {
  58310. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58311. }
  58312. if (this.volumetricLightMergePostProces) {
  58313. this.volumetricLightMergePostProces.dispose(camera);
  58314. }
  58315. if (this.volumetricLightFinalPostProcess) {
  58316. this.volumetricLightFinalPostProcess.dispose(camera);
  58317. }
  58318. if (this.lensFlarePostProcess) {
  58319. this.lensFlarePostProcess.dispose(camera);
  58320. }
  58321. if (this.lensFlareComposePostProcess) {
  58322. this.lensFlareComposePostProcess.dispose(camera);
  58323. }
  58324. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58325. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58326. }
  58327. if (this.luminancePostProcess) {
  58328. this.luminancePostProcess.dispose(camera);
  58329. }
  58330. if (this.hdrPostProcess) {
  58331. this.hdrPostProcess.dispose(camera);
  58332. }
  58333. if (this.hdrFinalPostProcess) {
  58334. this.hdrFinalPostProcess.dispose(camera);
  58335. }
  58336. if (this.depthOfFieldPostProcess) {
  58337. this.depthOfFieldPostProcess.dispose(camera);
  58338. }
  58339. if (this.motionBlurPostProcess) {
  58340. this.motionBlurPostProcess.dispose(camera);
  58341. }
  58342. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58343. this.blurHPostProcesses[j].dispose(camera);
  58344. }
  58345. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58346. this.blurVPostProcesses[j].dispose(camera);
  58347. }
  58348. }
  58349. this.originalPostProcess = null;
  58350. this.downSampleX4PostProcess = null;
  58351. this.brightPassPostProcess = null;
  58352. this.textureAdderPostProcess = null;
  58353. this.textureAdderFinalPostProcess = null;
  58354. this.volumetricLightPostProcess = null;
  58355. this.volumetricLightSmoothXPostProcess = null;
  58356. this.volumetricLightSmoothYPostProcess = null;
  58357. this.volumetricLightMergePostProces = null;
  58358. this.volumetricLightFinalPostProcess = null;
  58359. this.lensFlarePostProcess = null;
  58360. this.lensFlareComposePostProcess = null;
  58361. this.luminancePostProcess = null;
  58362. this.hdrPostProcess = null;
  58363. this.hdrFinalPostProcess = null;
  58364. this.depthOfFieldPostProcess = null;
  58365. this.motionBlurPostProcess = null;
  58366. this.luminanceDownSamplePostProcesses = [];
  58367. this.blurHPostProcesses = [];
  58368. this.blurVPostProcesses = [];
  58369. };
  58370. // Dispose
  58371. StandardRenderingPipeline.prototype.dispose = function () {
  58372. this._disposePostProcesses();
  58373. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58374. _super.prototype.dispose.call(this);
  58375. };
  58376. // Serialize rendering pipeline
  58377. StandardRenderingPipeline.prototype.serialize = function () {
  58378. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58379. serializationObject.customType = "StandardRenderingPipeline";
  58380. return serializationObject;
  58381. };
  58382. /**
  58383. * Static members
  58384. */
  58385. // Parse serialized pipeline
  58386. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58387. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58388. };
  58389. // Luminance steps
  58390. StandardRenderingPipeline.LuminanceSteps = 6;
  58391. __decorate([
  58392. BABYLON.serialize()
  58393. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58394. __decorate([
  58395. BABYLON.serialize()
  58396. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58397. __decorate([
  58398. BABYLON.serialize()
  58399. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58400. __decorate([
  58401. BABYLON.serialize()
  58402. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58403. __decorate([
  58404. BABYLON.serializeAsTexture("lensTexture")
  58405. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58406. __decorate([
  58407. BABYLON.serialize()
  58408. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58409. __decorate([
  58410. BABYLON.serialize()
  58411. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58412. __decorate([
  58413. BABYLON.serialize()
  58414. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58415. __decorate([
  58416. BABYLON.serialize()
  58417. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58418. __decorate([
  58419. BABYLON.serialize()
  58420. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58421. __decorate([
  58422. BABYLON.serialize()
  58423. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58424. __decorate([
  58425. BABYLON.serializeAsTexture("lensColorTexture")
  58426. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58427. __decorate([
  58428. BABYLON.serialize()
  58429. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58430. __decorate([
  58431. BABYLON.serialize()
  58432. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58433. __decorate([
  58434. BABYLON.serialize()
  58435. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58436. __decorate([
  58437. BABYLON.serialize()
  58438. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58439. __decorate([
  58440. BABYLON.serializeAsTexture("lensStarTexture")
  58441. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58442. __decorate([
  58443. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58444. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58445. __decorate([
  58446. BABYLON.serialize()
  58447. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58448. __decorate([
  58449. BABYLON.serialize()
  58450. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58451. __decorate([
  58452. BABYLON.serialize()
  58453. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58454. __decorate([
  58455. BABYLON.serialize()
  58456. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58457. __decorate([
  58458. BABYLON.serialize()
  58459. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58460. __decorate([
  58461. BABYLON.serialize()
  58462. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58463. __decorate([
  58464. BABYLON.serialize()
  58465. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58466. __decorate([
  58467. BABYLON.serialize()
  58468. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58469. __decorate([
  58470. BABYLON.serialize()
  58471. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58472. __decorate([
  58473. BABYLON.serialize()
  58474. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58475. __decorate([
  58476. BABYLON.serialize()
  58477. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58478. return StandardRenderingPipeline;
  58479. }(BABYLON.PostProcessRenderPipeline));
  58480. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58481. })(BABYLON || (BABYLON = {}));
  58482. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58483. var BABYLON;
  58484. (function (BABYLON) {
  58485. var FxaaPostProcess = /** @class */ (function (_super) {
  58486. __extends(FxaaPostProcess, _super);
  58487. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58488. if (camera === void 0) { camera = null; }
  58489. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58490. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58491. _this.onApplyObservable.add(function (effect) {
  58492. var texelSize = _this.texelSize;
  58493. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58494. });
  58495. return _this;
  58496. }
  58497. return FxaaPostProcess;
  58498. }(BABYLON.PostProcess));
  58499. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58500. })(BABYLON || (BABYLON = {}));
  58501. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58502. var BABYLON;
  58503. (function (BABYLON) {
  58504. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58505. __extends(DefaultRenderingPipeline, _super);
  58506. /**
  58507. * @constructor
  58508. * @param {string} name - The rendering pipeline name
  58509. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58510. * @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)
  58511. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58512. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58513. */
  58514. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58515. if (automaticBuild === void 0) { automaticBuild = true; }
  58516. var _this = _super.call(this, scene.getEngine(), name) || this;
  58517. _this.PassPostProcessId = "PassPostProcessEffect";
  58518. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58519. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58520. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58521. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58522. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58523. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58524. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58525. // IAnimatable
  58526. _this.animations = [];
  58527. // Values
  58528. _this._bloomEnabled = false;
  58529. _this._fxaaEnabled = false;
  58530. _this._imageProcessingEnabled = true;
  58531. _this._bloomScale = 0.6;
  58532. _this._buildAllowed = true;
  58533. /**
  58534. * Specifies the size of the bloom blur kernel, relative to the final output size
  58535. */
  58536. _this.bloomKernel = 64;
  58537. /**
  58538. * Specifies the weight of the bloom in the final rendering
  58539. */
  58540. _this._bloomWeight = 0.15;
  58541. _this._cameras = cameras || [];
  58542. _this._buildAllowed = automaticBuild;
  58543. // Initialize
  58544. _this._scene = scene;
  58545. var caps = _this._scene.getEngine().getCaps();
  58546. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58547. // Misc
  58548. if (_this._hdr) {
  58549. if (caps.textureHalfFloatRender) {
  58550. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58551. }
  58552. else if (caps.textureFloatRender) {
  58553. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58554. }
  58555. }
  58556. else {
  58557. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58558. }
  58559. // Attach
  58560. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58561. _this._buildPipeline();
  58562. return _this;
  58563. }
  58564. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  58565. get: function () {
  58566. return this._bloomWeight;
  58567. },
  58568. set: function (value) {
  58569. if (this._bloomWeight === value) {
  58570. return;
  58571. }
  58572. this._bloomWeight = value;
  58573. if (this._hdr && this.copyBack) {
  58574. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  58575. }
  58576. },
  58577. enumerable: true,
  58578. configurable: true
  58579. });
  58580. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  58581. get: function () {
  58582. return this._bloomScale;
  58583. },
  58584. set: function (value) {
  58585. if (this._bloomScale === value) {
  58586. return;
  58587. }
  58588. this._bloomScale = value;
  58589. this._buildPipeline();
  58590. },
  58591. enumerable: true,
  58592. configurable: true
  58593. });
  58594. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  58595. get: function () {
  58596. return this._bloomEnabled;
  58597. },
  58598. set: function (enabled) {
  58599. if (this._bloomEnabled === enabled) {
  58600. return;
  58601. }
  58602. this._bloomEnabled = enabled;
  58603. this._buildPipeline();
  58604. },
  58605. enumerable: true,
  58606. configurable: true
  58607. });
  58608. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  58609. get: function () {
  58610. return this._fxaaEnabled;
  58611. },
  58612. set: function (enabled) {
  58613. if (this._fxaaEnabled === enabled) {
  58614. return;
  58615. }
  58616. this._fxaaEnabled = enabled;
  58617. this._buildPipeline();
  58618. },
  58619. enumerable: true,
  58620. configurable: true
  58621. });
  58622. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  58623. get: function () {
  58624. return this._imageProcessingEnabled;
  58625. },
  58626. set: function (enabled) {
  58627. if (this._imageProcessingEnabled === enabled) {
  58628. return;
  58629. }
  58630. this._imageProcessingEnabled = enabled;
  58631. this._buildPipeline();
  58632. },
  58633. enumerable: true,
  58634. configurable: true
  58635. });
  58636. /**
  58637. * Force the compilation of the entire pipeline.
  58638. */
  58639. DefaultRenderingPipeline.prototype.prepare = function () {
  58640. var previousState = this._buildAllowed;
  58641. this._buildAllowed = true;
  58642. this._buildPipeline();
  58643. this._buildAllowed = previousState;
  58644. };
  58645. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  58646. var _this = this;
  58647. if (!this._buildAllowed) {
  58648. return;
  58649. }
  58650. var engine = this._scene.getEngine();
  58651. this._disposePostProcesses();
  58652. this._reset();
  58653. if (this.bloomEnabled) {
  58654. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58655. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  58656. if (!this._hdr) {
  58657. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58658. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  58659. this.highlights.autoClear = false;
  58660. this.highlights.alwaysForcePOT = true;
  58661. }
  58662. 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);
  58663. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  58664. this.blurX.alwaysForcePOT = true;
  58665. this.blurX.autoClear = false;
  58666. this.blurX.onActivateObservable.add(function () {
  58667. var dw = _this.blurX.width / engine.getRenderWidth(true);
  58668. _this.blurX.kernel = _this.bloomKernel * dw;
  58669. });
  58670. 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);
  58671. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  58672. this.blurY.alwaysForcePOT = true;
  58673. this.blurY.autoClear = false;
  58674. this.blurY.onActivateObservable.add(function () {
  58675. var dh = _this.blurY.height / engine.getRenderHeight(true);
  58676. _this.blurY.kernel = _this.bloomKernel * dh;
  58677. });
  58678. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58679. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  58680. this.copyBack.alwaysForcePOT = true;
  58681. if (this._hdr) {
  58682. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  58683. var w = this.bloomWeight;
  58684. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  58685. }
  58686. else {
  58687. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  58688. }
  58689. this.copyBack.autoClear = false;
  58690. }
  58691. if (this._imageProcessingEnabled) {
  58692. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58693. if (this._hdr) {
  58694. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  58695. }
  58696. else {
  58697. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  58698. }
  58699. }
  58700. if (this.fxaaEnabled) {
  58701. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58702. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  58703. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58704. }
  58705. else {
  58706. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  58707. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  58708. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  58709. }
  58710. if (this.bloomEnabled) {
  58711. if (this._hdr) {
  58712. this.copyBack.shareOutputWith(this.blurX);
  58713. if (this.imageProcessing) {
  58714. this.imageProcessing.shareOutputWith(this.pass);
  58715. this.imageProcessing.autoClear = false;
  58716. }
  58717. else if (this.fxaa) {
  58718. this.fxaa.shareOutputWith(this.pass);
  58719. }
  58720. else {
  58721. this.finalMerge.shareOutputWith(this.pass);
  58722. }
  58723. }
  58724. else {
  58725. if (this.fxaa) {
  58726. this.fxaa.shareOutputWith(this.pass);
  58727. }
  58728. else {
  58729. this.finalMerge.shareOutputWith(this.pass);
  58730. }
  58731. }
  58732. }
  58733. if (this._cameras !== null) {
  58734. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58735. }
  58736. };
  58737. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  58738. for (var i = 0; i < this._cameras.length; i++) {
  58739. var camera = this._cameras[i];
  58740. if (this.pass) {
  58741. this.pass.dispose(camera);
  58742. }
  58743. if (this.highlights) {
  58744. this.highlights.dispose(camera);
  58745. }
  58746. if (this.blurX) {
  58747. this.blurX.dispose(camera);
  58748. }
  58749. if (this.blurY) {
  58750. this.blurY.dispose(camera);
  58751. }
  58752. if (this.copyBack) {
  58753. this.copyBack.dispose(camera);
  58754. }
  58755. if (this.imageProcessing) {
  58756. this.imageProcessing.dispose(camera);
  58757. }
  58758. if (this.fxaa) {
  58759. this.fxaa.dispose(camera);
  58760. }
  58761. if (this.finalMerge) {
  58762. this.finalMerge.dispose(camera);
  58763. }
  58764. }
  58765. this.pass = null;
  58766. this.highlights = null;
  58767. this.blurX = null;
  58768. this.blurY = null;
  58769. this.copyBack = null;
  58770. this.imageProcessing = null;
  58771. this.fxaa = null;
  58772. this.finalMerge = null;
  58773. };
  58774. // Dispose
  58775. DefaultRenderingPipeline.prototype.dispose = function () {
  58776. this._disposePostProcesses();
  58777. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58778. _super.prototype.dispose.call(this);
  58779. };
  58780. // Serialize rendering pipeline
  58781. DefaultRenderingPipeline.prototype.serialize = function () {
  58782. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58783. serializationObject.customType = "DefaultRenderingPipeline";
  58784. return serializationObject;
  58785. };
  58786. // Parse serialized pipeline
  58787. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58788. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  58789. };
  58790. __decorate([
  58791. BABYLON.serialize()
  58792. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  58793. __decorate([
  58794. BABYLON.serialize()
  58795. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  58796. __decorate([
  58797. BABYLON.serialize()
  58798. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  58799. __decorate([
  58800. BABYLON.serialize()
  58801. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  58802. __decorate([
  58803. BABYLON.serialize()
  58804. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  58805. __decorate([
  58806. BABYLON.serialize()
  58807. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  58808. __decorate([
  58809. BABYLON.serialize()
  58810. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  58811. __decorate([
  58812. BABYLON.serialize()
  58813. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  58814. return DefaultRenderingPipeline;
  58815. }(BABYLON.PostProcessRenderPipeline));
  58816. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  58817. })(BABYLON || (BABYLON = {}));
  58818. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  58819. var BABYLON;
  58820. (function (BABYLON) {
  58821. var GeometryBufferRenderer = /** @class */ (function () {
  58822. function GeometryBufferRenderer(scene, ratio) {
  58823. if (ratio === void 0) { ratio = 1; }
  58824. this._enablePosition = false;
  58825. this._scene = scene;
  58826. this._ratio = ratio;
  58827. // Render target
  58828. this._createRenderTargets();
  58829. }
  58830. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  58831. set: function (meshes) {
  58832. this._multiRenderTarget.renderList = meshes;
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  58838. get: function () {
  58839. return this._multiRenderTarget.isSupported;
  58840. },
  58841. enumerable: true,
  58842. configurable: true
  58843. });
  58844. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  58845. get: function () {
  58846. return this._enablePosition;
  58847. },
  58848. set: function (enable) {
  58849. this._enablePosition = enable;
  58850. this.dispose();
  58851. this._createRenderTargets();
  58852. },
  58853. enumerable: true,
  58854. configurable: true
  58855. });
  58856. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  58857. var material = subMesh.getMaterial();
  58858. if (material && material.disableDepthWrite) {
  58859. return false;
  58860. }
  58861. var defines = [];
  58862. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  58863. var mesh = subMesh.getMesh();
  58864. // Alpha test
  58865. if (material && material.needAlphaTesting()) {
  58866. defines.push("#define ALPHATEST");
  58867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58868. attribs.push(BABYLON.VertexBuffer.UVKind);
  58869. defines.push("#define UV1");
  58870. }
  58871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58872. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58873. defines.push("#define UV2");
  58874. }
  58875. }
  58876. // Buffers
  58877. if (this._enablePosition) {
  58878. defines.push("#define POSITION");
  58879. }
  58880. // Bones
  58881. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58884. if (mesh.numBoneInfluencers > 4) {
  58885. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58886. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58887. }
  58888. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58889. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58890. }
  58891. else {
  58892. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58893. }
  58894. // Instances
  58895. if (useInstances) {
  58896. defines.push("#define INSTANCES");
  58897. attribs.push("world0");
  58898. attribs.push("world1");
  58899. attribs.push("world2");
  58900. attribs.push("world3");
  58901. }
  58902. // Get correct effect
  58903. var join = defines.join("\n");
  58904. if (this._cachedDefines !== join) {
  58905. this._cachedDefines = join;
  58906. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  58907. }
  58908. return this._effect.isReady();
  58909. };
  58910. GeometryBufferRenderer.prototype.getGBuffer = function () {
  58911. return this._multiRenderTarget;
  58912. };
  58913. // Methods
  58914. GeometryBufferRenderer.prototype.dispose = function () {
  58915. this.getGBuffer().dispose();
  58916. };
  58917. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  58918. var _this = this;
  58919. var engine = this._scene.getEngine();
  58920. var count = this._enablePosition ? 3 : 2;
  58921. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  58922. if (!this.isSupported) {
  58923. return;
  58924. }
  58925. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58926. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58927. this._multiRenderTarget.refreshRate = 1;
  58928. this._multiRenderTarget.renderParticles = false;
  58929. this._multiRenderTarget.renderList = null;
  58930. // set default depth value to 1.0 (far away)
  58931. this._multiRenderTarget.onClearObservable.add(function (engine) {
  58932. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  58933. });
  58934. // Custom render function
  58935. var renderSubMesh = function (subMesh) {
  58936. var mesh = subMesh.getRenderingMesh();
  58937. var scene = _this._scene;
  58938. var engine = scene.getEngine();
  58939. var material = subMesh.getMaterial();
  58940. if (!material) {
  58941. return;
  58942. }
  58943. // Culling
  58944. engine.setState(material.backFaceCulling);
  58945. // Managing instances
  58946. var batch = mesh._getInstancesRenderList(subMesh._id);
  58947. if (batch.mustReturn) {
  58948. return;
  58949. }
  58950. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58951. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  58952. engine.enableEffect(_this._effect);
  58953. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58954. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58955. _this._effect.setMatrix("view", scene.getViewMatrix());
  58956. // Alpha test
  58957. if (material && material.needAlphaTesting()) {
  58958. var alphaTexture = material.getAlphaTestTexture();
  58959. if (alphaTexture) {
  58960. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58961. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58962. }
  58963. }
  58964. // Bones
  58965. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58966. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58967. }
  58968. // Draw
  58969. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58970. }
  58971. };
  58972. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58973. var index;
  58974. if (depthOnlySubMeshes.length) {
  58975. engine.setColorWrite(false);
  58976. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58977. renderSubMesh(depthOnlySubMeshes.data[index]);
  58978. }
  58979. engine.setColorWrite(true);
  58980. }
  58981. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58982. renderSubMesh(opaqueSubMeshes.data[index]);
  58983. }
  58984. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58985. renderSubMesh(alphaTestSubMeshes.data[index]);
  58986. }
  58987. };
  58988. };
  58989. return GeometryBufferRenderer;
  58990. }());
  58991. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  58992. })(BABYLON || (BABYLON = {}));
  58993. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  58994. var BABYLON;
  58995. (function (BABYLON) {
  58996. var RefractionPostProcess = /** @class */ (function (_super) {
  58997. __extends(RefractionPostProcess, _super);
  58998. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  58999. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59000. _this.color = color;
  59001. _this.depth = depth;
  59002. _this.colorLevel = colorLevel;
  59003. _this.onActivateObservable.add(function (cam) {
  59004. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59005. });
  59006. _this.onApplyObservable.add(function (effect) {
  59007. effect.setColor3("baseColor", _this.color);
  59008. effect.setFloat("depth", _this.depth);
  59009. effect.setFloat("colorLevel", _this.colorLevel);
  59010. effect.setTexture("refractionSampler", _this._refRexture);
  59011. });
  59012. return _this;
  59013. }
  59014. // Methods
  59015. RefractionPostProcess.prototype.dispose = function (camera) {
  59016. if (this._refRexture) {
  59017. this._refRexture.dispose();
  59018. }
  59019. _super.prototype.dispose.call(this, camera);
  59020. };
  59021. return RefractionPostProcess;
  59022. }(BABYLON.PostProcess));
  59023. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59024. })(BABYLON || (BABYLON = {}));
  59025. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59026. var BABYLON;
  59027. (function (BABYLON) {
  59028. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59029. __extends(BlackAndWhitePostProcess, _super);
  59030. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59031. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59032. _this.degree = 1;
  59033. _this.onApplyObservable.add(function (effect) {
  59034. effect.setFloat("degree", _this.degree);
  59035. });
  59036. return _this;
  59037. }
  59038. return BlackAndWhitePostProcess;
  59039. }(BABYLON.PostProcess));
  59040. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59041. })(BABYLON || (BABYLON = {}));
  59042. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59043. var BABYLON;
  59044. (function (BABYLON) {
  59045. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59046. __extends(ConvolutionPostProcess, _super);
  59047. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59048. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59049. _this.kernel = kernel;
  59050. _this.onApply = function (effect) {
  59051. effect.setFloat2("screenSize", _this.width, _this.height);
  59052. effect.setArray("kernel", _this.kernel);
  59053. };
  59054. return _this;
  59055. }
  59056. // Statics
  59057. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59058. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59059. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59060. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59061. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59062. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59063. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59064. return ConvolutionPostProcess;
  59065. }(BABYLON.PostProcess));
  59066. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59067. })(BABYLON || (BABYLON = {}));
  59068. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59069. var BABYLON;
  59070. (function (BABYLON) {
  59071. var FilterPostProcess = /** @class */ (function (_super) {
  59072. __extends(FilterPostProcess, _super);
  59073. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59074. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59075. _this.kernelMatrix = kernelMatrix;
  59076. _this.onApply = function (effect) {
  59077. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59078. };
  59079. return _this;
  59080. }
  59081. return FilterPostProcess;
  59082. }(BABYLON.PostProcess));
  59083. BABYLON.FilterPostProcess = FilterPostProcess;
  59084. })(BABYLON || (BABYLON = {}));
  59085. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59086. var BABYLON;
  59087. (function (BABYLON) {
  59088. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59089. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59090. __extends(VolumetricLightScatteringPostProcess, _super);
  59091. /**
  59092. * @constructor
  59093. * @param {string} name - The post-process name
  59094. * @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)
  59095. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59096. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59097. * @param {number} samples - The post-process quality, default 100
  59098. * @param {number} samplingMode - The post-process filtering mode
  59099. * @param {BABYLON.Engine} engine - The babylon engine
  59100. * @param {boolean} reusable - If the post-process is reusable
  59101. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59102. */
  59103. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59104. if (samples === void 0) { samples = 100; }
  59105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59106. 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;
  59107. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59108. /**
  59109. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59110. * @type {Vector3}
  59111. */
  59112. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59113. /**
  59114. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59115. * @type {boolean}
  59116. */
  59117. _this.useCustomMeshPosition = false;
  59118. /**
  59119. * If the post-process should inverse the light scattering direction
  59120. * @type {boolean}
  59121. */
  59122. _this.invert = true;
  59123. /**
  59124. * Array containing the excluded meshes not rendered in the internal pass
  59125. */
  59126. _this.excludedMeshes = new Array();
  59127. /**
  59128. * Controls the overall intensity of the post-process
  59129. * @type {number}
  59130. */
  59131. _this.exposure = 0.3;
  59132. /**
  59133. * Dissipates each sample's contribution in range [0, 1]
  59134. * @type {number}
  59135. */
  59136. _this.decay = 0.96815;
  59137. /**
  59138. * Controls the overall intensity of each sample
  59139. * @type {number}
  59140. */
  59141. _this.weight = 0.58767;
  59142. /**
  59143. * Controls the density of each sample
  59144. * @type {number}
  59145. */
  59146. _this.density = 0.926;
  59147. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59148. engine = scene.getEngine();
  59149. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59150. // Configure mesh
  59151. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59152. // Configure
  59153. _this._createPass(scene, ratio.passRatio || ratio);
  59154. _this.onActivate = function (camera) {
  59155. if (!_this.isSupported) {
  59156. _this.dispose(camera);
  59157. }
  59158. _this.onActivate = null;
  59159. };
  59160. _this.onApplyObservable.add(function (effect) {
  59161. _this._updateMeshScreenCoordinates(scene);
  59162. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59163. effect.setFloat("exposure", _this.exposure);
  59164. effect.setFloat("decay", _this.decay);
  59165. effect.setFloat("weight", _this.weight);
  59166. effect.setFloat("density", _this.density);
  59167. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59168. });
  59169. return _this;
  59170. }
  59171. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59172. get: function () {
  59173. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59174. return false;
  59175. },
  59176. set: function (useDiffuseColor) {
  59177. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59178. },
  59179. enumerable: true,
  59180. configurable: true
  59181. });
  59182. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59183. return "VolumetricLightScatteringPostProcess";
  59184. };
  59185. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59186. var mesh = subMesh.getMesh();
  59187. // Render this.mesh as default
  59188. if (mesh === this.mesh && mesh.material) {
  59189. return mesh.material.isReady(mesh);
  59190. }
  59191. var defines = [];
  59192. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59193. var material = subMesh.getMaterial();
  59194. // Alpha test
  59195. if (material) {
  59196. if (material.needAlphaTesting()) {
  59197. defines.push("#define ALPHATEST");
  59198. }
  59199. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59200. attribs.push(BABYLON.VertexBuffer.UVKind);
  59201. defines.push("#define UV1");
  59202. }
  59203. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59204. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59205. defines.push("#define UV2");
  59206. }
  59207. }
  59208. // Bones
  59209. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59210. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59211. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59212. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59213. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59214. }
  59215. else {
  59216. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59217. }
  59218. // Instances
  59219. if (useInstances) {
  59220. defines.push("#define INSTANCES");
  59221. attribs.push("world0");
  59222. attribs.push("world1");
  59223. attribs.push("world2");
  59224. attribs.push("world3");
  59225. }
  59226. // Get correct effect
  59227. var join = defines.join("\n");
  59228. if (this._cachedDefines !== join) {
  59229. this._cachedDefines = join;
  59230. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59231. }
  59232. return this._volumetricLightScatteringPass.isReady();
  59233. };
  59234. /**
  59235. * Sets the new light position for light scattering effect
  59236. * @param {BABYLON.Vector3} The new custom light position
  59237. */
  59238. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59239. this.customMeshPosition = position;
  59240. };
  59241. /**
  59242. * Returns the light position for light scattering effect
  59243. * @return {BABYLON.Vector3} The custom light position
  59244. */
  59245. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59246. return this.customMeshPosition;
  59247. };
  59248. /**
  59249. * Disposes the internal assets and detaches the post-process from the camera
  59250. */
  59251. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59252. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59253. if (rttIndex !== -1) {
  59254. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59255. }
  59256. this._volumetricLightScatteringRTT.dispose();
  59257. _super.prototype.dispose.call(this, camera);
  59258. };
  59259. /**
  59260. * Returns the render target texture used by the post-process
  59261. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59262. */
  59263. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59264. return this._volumetricLightScatteringRTT;
  59265. };
  59266. // Private methods
  59267. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59268. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59269. return true;
  59270. }
  59271. return false;
  59272. };
  59273. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59274. var _this = this;
  59275. var engine = scene.getEngine();
  59276. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59277. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59278. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59279. this._volumetricLightScatteringRTT.renderList = null;
  59280. this._volumetricLightScatteringRTT.renderParticles = false;
  59281. var camera = this.getCamera();
  59282. if (camera) {
  59283. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59284. }
  59285. else {
  59286. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59287. }
  59288. // Custom render function for submeshes
  59289. var renderSubMesh = function (subMesh) {
  59290. var mesh = subMesh.getRenderingMesh();
  59291. if (_this._meshExcluded(mesh)) {
  59292. return;
  59293. }
  59294. var material = subMesh.getMaterial();
  59295. if (!material) {
  59296. return;
  59297. }
  59298. var scene = mesh.getScene();
  59299. var engine = scene.getEngine();
  59300. // Culling
  59301. engine.setState(material.backFaceCulling);
  59302. // Managing instances
  59303. var batch = mesh._getInstancesRenderList(subMesh._id);
  59304. if (batch.mustReturn) {
  59305. return;
  59306. }
  59307. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59308. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59309. var effect = _this._volumetricLightScatteringPass;
  59310. if (mesh === _this.mesh) {
  59311. if (subMesh.effect) {
  59312. effect = subMesh.effect;
  59313. }
  59314. else {
  59315. effect = material.getEffect();
  59316. }
  59317. }
  59318. engine.enableEffect(effect);
  59319. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59320. if (mesh === _this.mesh) {
  59321. material.bind(mesh.getWorldMatrix(), mesh);
  59322. }
  59323. else {
  59324. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59325. // Alpha test
  59326. if (material && material.needAlphaTesting()) {
  59327. var alphaTexture = material.getAlphaTestTexture();
  59328. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59329. if (alphaTexture) {
  59330. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59331. }
  59332. }
  59333. // Bones
  59334. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59335. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59336. }
  59337. }
  59338. // Draw
  59339. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59340. }
  59341. };
  59342. // Render target texture callbacks
  59343. var savedSceneClearColor;
  59344. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59345. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59346. savedSceneClearColor = scene.clearColor;
  59347. scene.clearColor = sceneClearColor;
  59348. });
  59349. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59350. scene.clearColor = savedSceneClearColor;
  59351. });
  59352. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59353. var engine = scene.getEngine();
  59354. var index;
  59355. if (depthOnlySubMeshes.length) {
  59356. engine.setColorWrite(false);
  59357. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59358. renderSubMesh(depthOnlySubMeshes.data[index]);
  59359. }
  59360. engine.setColorWrite(true);
  59361. }
  59362. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59363. renderSubMesh(opaqueSubMeshes.data[index]);
  59364. }
  59365. engine.setAlphaTesting(true);
  59366. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59367. renderSubMesh(alphaTestSubMeshes.data[index]);
  59368. }
  59369. engine.setAlphaTesting(false);
  59370. if (transparentSubMeshes.length) {
  59371. // Sort sub meshes
  59372. for (index = 0; index < transparentSubMeshes.length; index++) {
  59373. var submesh = transparentSubMeshes.data[index];
  59374. var boundingInfo = submesh.getBoundingInfo();
  59375. if (boundingInfo && scene.activeCamera) {
  59376. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59377. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59378. }
  59379. }
  59380. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59381. sortedArray.sort(function (a, b) {
  59382. // Alpha index first
  59383. if (a._alphaIndex > b._alphaIndex) {
  59384. return 1;
  59385. }
  59386. if (a._alphaIndex < b._alphaIndex) {
  59387. return -1;
  59388. }
  59389. // Then distance to camera
  59390. if (a._distanceToCamera < b._distanceToCamera) {
  59391. return 1;
  59392. }
  59393. if (a._distanceToCamera > b._distanceToCamera) {
  59394. return -1;
  59395. }
  59396. return 0;
  59397. });
  59398. // Render sub meshes
  59399. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59400. for (index = 0; index < sortedArray.length; index++) {
  59401. renderSubMesh(sortedArray[index]);
  59402. }
  59403. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59404. }
  59405. };
  59406. };
  59407. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59408. var transform = scene.getTransformMatrix();
  59409. var meshPosition;
  59410. if (this.useCustomMeshPosition) {
  59411. meshPosition = this.customMeshPosition;
  59412. }
  59413. else if (this.attachedNode) {
  59414. meshPosition = this.attachedNode.position;
  59415. }
  59416. else {
  59417. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59418. }
  59419. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59420. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59421. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59422. if (this.invert)
  59423. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59424. };
  59425. // Static methods
  59426. /**
  59427. * Creates a default mesh for the Volumeric Light Scattering post-process
  59428. * @param {string} The mesh name
  59429. * @param {BABYLON.Scene} The scene where to create the mesh
  59430. * @return {BABYLON.Mesh} the default mesh
  59431. */
  59432. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59433. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59434. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59435. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59436. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59437. mesh.material = material;
  59438. return mesh;
  59439. };
  59440. __decorate([
  59441. BABYLON.serializeAsVector3()
  59442. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59443. __decorate([
  59444. BABYLON.serialize()
  59445. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59446. __decorate([
  59447. BABYLON.serialize()
  59448. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59449. __decorate([
  59450. BABYLON.serializeAsMeshReference()
  59451. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59452. __decorate([
  59453. BABYLON.serialize()
  59454. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59455. __decorate([
  59456. BABYLON.serialize()
  59457. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59458. __decorate([
  59459. BABYLON.serialize()
  59460. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59461. __decorate([
  59462. BABYLON.serialize()
  59463. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59464. __decorate([
  59465. BABYLON.serialize()
  59466. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59467. return VolumetricLightScatteringPostProcess;
  59468. }(BABYLON.PostProcess));
  59469. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59470. })(BABYLON || (BABYLON = {}));
  59471. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59472. //
  59473. // This post-process allows the modification of rendered colors by using
  59474. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59475. //
  59476. // The object needs to be provided an url to a texture containing the color
  59477. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59478. // Use an image editing software to tweak the LUT to match your needs.
  59479. //
  59480. // For an example of a color LUT, see here:
  59481. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59482. // For explanations on color grading, see here:
  59483. // http://udn.epicgames.com/Three/ColorGrading.html
  59484. //
  59485. var BABYLON;
  59486. (function (BABYLON) {
  59487. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59488. __extends(ColorCorrectionPostProcess, _super);
  59489. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59490. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59491. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59492. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59493. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59494. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59495. _this.onApply = function (effect) {
  59496. effect.setTexture("colorTable", _this._colorTableTexture);
  59497. };
  59498. return _this;
  59499. }
  59500. return ColorCorrectionPostProcess;
  59501. }(BABYLON.PostProcess));
  59502. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59503. })(BABYLON || (BABYLON = {}));
  59504. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59505. var BABYLON;
  59506. (function (BABYLON) {
  59507. var TonemappingOperator;
  59508. (function (TonemappingOperator) {
  59509. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59510. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59511. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59512. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59513. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59514. ;
  59515. var TonemapPostProcess = /** @class */ (function (_super) {
  59516. __extends(TonemapPostProcess, _super);
  59517. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59519. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59520. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59521. _this._operator = _operator;
  59522. _this.exposureAdjustment = exposureAdjustment;
  59523. var defines = "#define ";
  59524. if (_this._operator === TonemappingOperator.Hable)
  59525. defines += "HABLE_TONEMAPPING";
  59526. else if (_this._operator === TonemappingOperator.Reinhard)
  59527. defines += "REINHARD_TONEMAPPING";
  59528. else if (_this._operator === TonemappingOperator.HejiDawson)
  59529. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59530. else if (_this._operator === TonemappingOperator.Photographic)
  59531. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59532. //sadly a second call to create the effect.
  59533. _this.updateEffect(defines);
  59534. _this.onApply = function (effect) {
  59535. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59536. };
  59537. return _this;
  59538. }
  59539. return TonemapPostProcess;
  59540. }(BABYLON.PostProcess));
  59541. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59542. })(BABYLON || (BABYLON = {}));
  59543. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59544. var BABYLON;
  59545. (function (BABYLON) {
  59546. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59547. __extends(DisplayPassPostProcess, _super);
  59548. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59549. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59550. }
  59551. return DisplayPassPostProcess;
  59552. }(BABYLON.PostProcess));
  59553. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59554. })(BABYLON || (BABYLON = {}));
  59555. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59556. var BABYLON;
  59557. (function (BABYLON) {
  59558. var HighlightsPostProcess = /** @class */ (function (_super) {
  59559. __extends(HighlightsPostProcess, _super);
  59560. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59561. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59562. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  59563. }
  59564. return HighlightsPostProcess;
  59565. }(BABYLON.PostProcess));
  59566. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  59567. })(BABYLON || (BABYLON = {}));
  59568. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  59569. var BABYLON;
  59570. (function (BABYLON) {
  59571. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  59572. __extends(ImageProcessingPostProcess, _super);
  59573. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59574. if (camera === void 0) { camera = null; }
  59575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59576. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  59577. _this._fromLinearSpace = true;
  59578. /**
  59579. * Defines cache preventing GC.
  59580. */
  59581. _this._defines = {
  59582. IMAGEPROCESSING: false,
  59583. VIGNETTE: false,
  59584. VIGNETTEBLENDMODEMULTIPLY: false,
  59585. VIGNETTEBLENDMODEOPAQUE: false,
  59586. TONEMAPPING: false,
  59587. CONTRAST: false,
  59588. COLORCURVES: false,
  59589. COLORGRADING: false,
  59590. COLORGRADING3D: false,
  59591. FROMLINEARSPACE: false,
  59592. SAMPLER3DGREENDEPTH: false,
  59593. SAMPLER3DBGRMAP: false,
  59594. IMAGEPROCESSINGPOSTPROCESS: false,
  59595. EXPOSURE: false,
  59596. };
  59597. // Setup the default processing configuration to the scene.
  59598. _this._attachImageProcessingConfiguration(null, true);
  59599. _this.imageProcessingConfiguration.applyByPostProcess = true;
  59600. _this.onApply = function (effect) {
  59601. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  59602. };
  59603. return _this;
  59604. }
  59605. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  59606. /**
  59607. * Gets the image processing configuration used either in this material.
  59608. */
  59609. get: function () {
  59610. return this._imageProcessingConfiguration;
  59611. },
  59612. /**
  59613. * Sets the Default image processing configuration used either in the this material.
  59614. *
  59615. * If sets to null, the scene one is in use.
  59616. */
  59617. set: function (value) {
  59618. this._attachImageProcessingConfiguration(value);
  59619. },
  59620. enumerable: true,
  59621. configurable: true
  59622. });
  59623. /**
  59624. * Attaches a new image processing configuration to the PBR Material.
  59625. * @param configuration
  59626. */
  59627. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  59628. var _this = this;
  59629. if (doNotBuild === void 0) { doNotBuild = false; }
  59630. if (configuration === this._imageProcessingConfiguration) {
  59631. return;
  59632. }
  59633. // Detaches observer.
  59634. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59635. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59636. }
  59637. // Pick the scene configuration if needed.
  59638. if (!configuration) {
  59639. var scene = null;
  59640. var engine = this.getEngine();
  59641. var camera = this.getCamera();
  59642. if (camera) {
  59643. scene = camera.getScene();
  59644. }
  59645. else if (engine && engine.scenes) {
  59646. var scenes = engine.scenes;
  59647. scene = scenes[scenes.length - 1];
  59648. }
  59649. else {
  59650. scene = BABYLON.Engine.LastCreatedScene;
  59651. }
  59652. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  59653. }
  59654. else {
  59655. this._imageProcessingConfiguration = configuration;
  59656. }
  59657. // Attaches observer.
  59658. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  59659. _this._updateParameters();
  59660. });
  59661. // Ensure the effect will be rebuilt.
  59662. if (!doNotBuild) {
  59663. this._updateParameters();
  59664. }
  59665. };
  59666. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  59667. /**
  59668. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59669. */
  59670. get: function () {
  59671. return this.imageProcessingConfiguration.colorCurves;
  59672. },
  59673. /**
  59674. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  59675. */
  59676. set: function (value) {
  59677. this.imageProcessingConfiguration.colorCurves = value;
  59678. },
  59679. enumerable: true,
  59680. configurable: true
  59681. });
  59682. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  59683. /**
  59684. * Gets wether the color curves effect is enabled.
  59685. */
  59686. get: function () {
  59687. return this.imageProcessingConfiguration.colorCurvesEnabled;
  59688. },
  59689. /**
  59690. * Sets wether the color curves effect is enabled.
  59691. */
  59692. set: function (value) {
  59693. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  59694. },
  59695. enumerable: true,
  59696. configurable: true
  59697. });
  59698. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  59699. /**
  59700. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59701. */
  59702. get: function () {
  59703. return this.imageProcessingConfiguration.colorGradingTexture;
  59704. },
  59705. /**
  59706. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  59707. */
  59708. set: function (value) {
  59709. this.imageProcessingConfiguration.colorGradingTexture = value;
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  59715. /**
  59716. * Gets wether the color grading effect is enabled.
  59717. */
  59718. get: function () {
  59719. return this.imageProcessingConfiguration.colorGradingEnabled;
  59720. },
  59721. /**
  59722. * Gets wether the color grading effect is enabled.
  59723. */
  59724. set: function (value) {
  59725. this.imageProcessingConfiguration.colorGradingEnabled = value;
  59726. },
  59727. enumerable: true,
  59728. configurable: true
  59729. });
  59730. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  59731. /**
  59732. * Gets exposure used in the effect.
  59733. */
  59734. get: function () {
  59735. return this.imageProcessingConfiguration.exposure;
  59736. },
  59737. /**
  59738. * Sets exposure used in the effect.
  59739. */
  59740. set: function (value) {
  59741. this.imageProcessingConfiguration.exposure = value;
  59742. },
  59743. enumerable: true,
  59744. configurable: true
  59745. });
  59746. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  59747. /**
  59748. * Gets wether tonemapping is enabled or not.
  59749. */
  59750. get: function () {
  59751. return this._imageProcessingConfiguration.toneMappingEnabled;
  59752. },
  59753. /**
  59754. * Sets wether tonemapping is enabled or not
  59755. */
  59756. set: function (value) {
  59757. this._imageProcessingConfiguration.toneMappingEnabled = value;
  59758. },
  59759. enumerable: true,
  59760. configurable: true
  59761. });
  59762. ;
  59763. ;
  59764. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  59765. /**
  59766. * Gets contrast used in the effect.
  59767. */
  59768. get: function () {
  59769. return this.imageProcessingConfiguration.contrast;
  59770. },
  59771. /**
  59772. * Sets contrast used in the effect.
  59773. */
  59774. set: function (value) {
  59775. this.imageProcessingConfiguration.contrast = value;
  59776. },
  59777. enumerable: true,
  59778. configurable: true
  59779. });
  59780. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  59781. /**
  59782. * Gets Vignette stretch size.
  59783. */
  59784. get: function () {
  59785. return this.imageProcessingConfiguration.vignetteStretch;
  59786. },
  59787. /**
  59788. * Sets Vignette stretch size.
  59789. */
  59790. set: function (value) {
  59791. this.imageProcessingConfiguration.vignetteStretch = value;
  59792. },
  59793. enumerable: true,
  59794. configurable: true
  59795. });
  59796. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  59797. /**
  59798. * Gets Vignette centre X Offset.
  59799. */
  59800. get: function () {
  59801. return this.imageProcessingConfiguration.vignetteCentreX;
  59802. },
  59803. /**
  59804. * Sets Vignette centre X Offset.
  59805. */
  59806. set: function (value) {
  59807. this.imageProcessingConfiguration.vignetteCentreX = value;
  59808. },
  59809. enumerable: true,
  59810. configurable: true
  59811. });
  59812. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  59813. /**
  59814. * Gets Vignette centre Y Offset.
  59815. */
  59816. get: function () {
  59817. return this.imageProcessingConfiguration.vignetteCentreY;
  59818. },
  59819. /**
  59820. * Sets Vignette centre Y Offset.
  59821. */
  59822. set: function (value) {
  59823. this.imageProcessingConfiguration.vignetteCentreY = value;
  59824. },
  59825. enumerable: true,
  59826. configurable: true
  59827. });
  59828. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  59829. /**
  59830. * Gets Vignette weight or intensity of the vignette effect.
  59831. */
  59832. get: function () {
  59833. return this.imageProcessingConfiguration.vignetteWeight;
  59834. },
  59835. /**
  59836. * Sets Vignette weight or intensity of the vignette effect.
  59837. */
  59838. set: function (value) {
  59839. this.imageProcessingConfiguration.vignetteWeight = value;
  59840. },
  59841. enumerable: true,
  59842. configurable: true
  59843. });
  59844. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  59845. /**
  59846. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59847. * if vignetteEnabled is set to true.
  59848. */
  59849. get: function () {
  59850. return this.imageProcessingConfiguration.vignetteColor;
  59851. },
  59852. /**
  59853. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  59854. * if vignetteEnabled is set to true.
  59855. */
  59856. set: function (value) {
  59857. this.imageProcessingConfiguration.vignetteColor = value;
  59858. },
  59859. enumerable: true,
  59860. configurable: true
  59861. });
  59862. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  59863. /**
  59864. * Gets Camera field of view used by the Vignette effect.
  59865. */
  59866. get: function () {
  59867. return this.imageProcessingConfiguration.vignetteCameraFov;
  59868. },
  59869. /**
  59870. * Sets Camera field of view used by the Vignette effect.
  59871. */
  59872. set: function (value) {
  59873. this.imageProcessingConfiguration.vignetteCameraFov = value;
  59874. },
  59875. enumerable: true,
  59876. configurable: true
  59877. });
  59878. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  59879. /**
  59880. * Gets the vignette blend mode allowing different kind of effect.
  59881. */
  59882. get: function () {
  59883. return this.imageProcessingConfiguration.vignetteBlendMode;
  59884. },
  59885. /**
  59886. * Sets the vignette blend mode allowing different kind of effect.
  59887. */
  59888. set: function (value) {
  59889. this.imageProcessingConfiguration.vignetteBlendMode = value;
  59890. },
  59891. enumerable: true,
  59892. configurable: true
  59893. });
  59894. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  59895. /**
  59896. * Gets wether the vignette effect is enabled.
  59897. */
  59898. get: function () {
  59899. return this.imageProcessingConfiguration.vignetteEnabled;
  59900. },
  59901. /**
  59902. * Sets wether the vignette effect is enabled.
  59903. */
  59904. set: function (value) {
  59905. this.imageProcessingConfiguration.vignetteEnabled = value;
  59906. },
  59907. enumerable: true,
  59908. configurable: true
  59909. });
  59910. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  59911. /**
  59912. * Gets wether the input of the processing is in Gamma or Linear Space.
  59913. */
  59914. get: function () {
  59915. return this._fromLinearSpace;
  59916. },
  59917. /**
  59918. * Sets wether the input of the processing is in Gamma or Linear Space.
  59919. */
  59920. set: function (value) {
  59921. if (this._fromLinearSpace === value) {
  59922. return;
  59923. }
  59924. this._fromLinearSpace = value;
  59925. this._updateParameters();
  59926. },
  59927. enumerable: true,
  59928. configurable: true
  59929. });
  59930. ImageProcessingPostProcess.prototype.getClassName = function () {
  59931. return "ImageProcessingPostProcess";
  59932. };
  59933. ImageProcessingPostProcess.prototype._updateParameters = function () {
  59934. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  59935. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  59936. var defines = "";
  59937. for (var define in this._defines) {
  59938. if (this._defines[define]) {
  59939. defines += "#define " + define + ";\r\n";
  59940. }
  59941. }
  59942. var samplers = ["textureSampler"];
  59943. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  59944. var uniforms = ["scale"];
  59945. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  59946. this.updateEffect(defines, uniforms, samplers);
  59947. };
  59948. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  59949. _super.prototype.dispose.call(this, camera);
  59950. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  59951. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  59952. }
  59953. this.imageProcessingConfiguration.applyByPostProcess = false;
  59954. };
  59955. __decorate([
  59956. BABYLON.serialize()
  59957. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  59958. return ImageProcessingPostProcess;
  59959. }(BABYLON.PostProcess));
  59960. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  59961. })(BABYLON || (BABYLON = {}));
  59962. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  59963. var BABYLON;
  59964. (function (BABYLON) {
  59965. var BlurPostProcess = /** @class */ (function (_super) {
  59966. __extends(BlurPostProcess, _super);
  59967. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  59968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59969. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59970. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  59971. _this.direction = direction;
  59972. _this._packedFloat = false;
  59973. _this.onApplyObservable.add(function (effect) {
  59974. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  59975. });
  59976. _this.kernel = kernel;
  59977. return _this;
  59978. }
  59979. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  59980. /**
  59981. * Gets the length in pixels of the blur sample region
  59982. */
  59983. get: function () {
  59984. return this._idealKernel;
  59985. },
  59986. /**
  59987. * Sets the length in pixels of the blur sample region
  59988. */
  59989. set: function (v) {
  59990. if (this._idealKernel === v) {
  59991. return;
  59992. }
  59993. v = Math.max(v, 1);
  59994. this._idealKernel = v;
  59995. this._kernel = this._nearestBestKernel(v);
  59996. this._updateParameters();
  59997. },
  59998. enumerable: true,
  59999. configurable: true
  60000. });
  60001. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60002. /**
  60003. * Gets wether or not the blur is unpacking/repacking floats
  60004. */
  60005. get: function () {
  60006. return this._packedFloat;
  60007. },
  60008. /**
  60009. * Sets wether or not the blur needs to unpack/repack floats
  60010. */
  60011. set: function (v) {
  60012. if (this._packedFloat === v) {
  60013. return;
  60014. }
  60015. this._packedFloat = v;
  60016. this._updateParameters();
  60017. },
  60018. enumerable: true,
  60019. configurable: true
  60020. });
  60021. BlurPostProcess.prototype._updateParameters = function () {
  60022. // Generate sampling offsets and weights
  60023. var N = this._kernel;
  60024. var centerIndex = (N - 1) / 2;
  60025. // Generate Gaussian sampling weights over kernel
  60026. var offsets = [];
  60027. var weights = [];
  60028. var totalWeight = 0;
  60029. for (var i = 0; i < N; i++) {
  60030. var u = i / (N - 1);
  60031. var w = this._gaussianWeight(u * 2.0 - 1);
  60032. offsets[i] = (i - centerIndex);
  60033. weights[i] = w;
  60034. totalWeight += w;
  60035. }
  60036. // Normalize weights
  60037. for (var i = 0; i < weights.length; i++) {
  60038. weights[i] /= totalWeight;
  60039. }
  60040. // Optimize: combine samples to take advantage of hardware linear sampling
  60041. // Walk from left to center, combining pairs (symmetrically)
  60042. var linearSamplingWeights = [];
  60043. var linearSamplingOffsets = [];
  60044. var linearSamplingMap = [];
  60045. for (var i = 0; i <= centerIndex; i += 2) {
  60046. var j = Math.min(i + 1, Math.floor(centerIndex));
  60047. var singleCenterSample = i === j;
  60048. if (singleCenterSample) {
  60049. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60050. }
  60051. else {
  60052. var sharedCell = j === centerIndex;
  60053. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60054. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60055. if (offsetLinear === 0) {
  60056. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60057. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60058. }
  60059. else {
  60060. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60061. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60062. }
  60063. }
  60064. }
  60065. for (var i = 0; i < linearSamplingMap.length; i++) {
  60066. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60067. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60068. }
  60069. // Replace with optimized
  60070. offsets = linearSamplingOffsets;
  60071. weights = linearSamplingWeights;
  60072. // Generate shaders
  60073. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60074. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60075. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60076. var defines = "";
  60077. for (var i = 0; i < varyingCount; i++) {
  60078. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60079. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60080. }
  60081. var depCount = 0;
  60082. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60083. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60084. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60085. depCount++;
  60086. }
  60087. if (this.packedFloat) {
  60088. defines += "#define PACKEDFLOAT 1";
  60089. }
  60090. this.updateEffect(defines, null, null, {
  60091. varyingCount: varyingCount,
  60092. depCount: depCount
  60093. });
  60094. };
  60095. /**
  60096. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60097. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60098. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60099. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60100. * The gaps between physical kernels are compensated for in the weighting of the samples
  60101. * @param idealKernel Ideal blur kernel.
  60102. * @return Nearest best kernel.
  60103. */
  60104. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60105. var v = Math.round(idealKernel);
  60106. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60107. var k = _a[_i];
  60108. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60109. return Math.max(k, 3);
  60110. }
  60111. }
  60112. return Math.max(v, 3);
  60113. };
  60114. /**
  60115. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60116. * @param x The point on the Gaussian distribution to sample.
  60117. * @return the value of the Gaussian function at x.
  60118. */
  60119. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60120. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60121. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60122. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60123. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60124. // truncated at around 1.3% of peak strength.
  60125. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60126. var sigma = (1 / 3);
  60127. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60128. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60129. var weight = (1.0 / denominator) * Math.exp(exponent);
  60130. return weight;
  60131. };
  60132. /**
  60133. * Generates a string that can be used as a floating point number in GLSL.
  60134. * @param x Value to print.
  60135. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60136. * @return GLSL float string.
  60137. */
  60138. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60139. if (decimalFigures === void 0) { decimalFigures = 8; }
  60140. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60141. };
  60142. return BlurPostProcess;
  60143. }(BABYLON.PostProcess));
  60144. BABYLON.BlurPostProcess = BlurPostProcess;
  60145. })(BABYLON || (BABYLON = {}));
  60146. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60147. var BABYLON;
  60148. (function (BABYLON) {
  60149. var Bone = /** @class */ (function (_super) {
  60150. __extends(Bone, _super);
  60151. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60152. if (parentBone === void 0) { parentBone = null; }
  60153. if (localMatrix === void 0) { localMatrix = null; }
  60154. if (restPose === void 0) { restPose = null; }
  60155. if (baseMatrix === void 0) { baseMatrix = null; }
  60156. if (index === void 0) { index = null; }
  60157. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60158. _this.name = name;
  60159. _this.children = new Array();
  60160. _this.animations = new Array();
  60161. // Set this value to map this bone to a different index in the transform matrices.
  60162. // Set this value to -1 to exclude the bone from the transform matrices.
  60163. _this._index = null;
  60164. _this._worldTransform = new BABYLON.Matrix();
  60165. _this._absoluteTransform = new BABYLON.Matrix();
  60166. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60167. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60168. _this._scaleVector = BABYLON.Vector3.One();
  60169. _this._negateScaleChildren = BABYLON.Vector3.One();
  60170. _this._scalingDeterminant = 1;
  60171. _this._skeleton = skeleton;
  60172. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60173. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60174. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60175. _this._index = index;
  60176. skeleton.bones.push(_this);
  60177. _this.setParent(parentBone, false);
  60178. _this._updateDifferenceMatrix();
  60179. return _this;
  60180. }
  60181. Object.defineProperty(Bone.prototype, "_matrix", {
  60182. get: function () {
  60183. return this._localMatrix;
  60184. },
  60185. set: function (val) {
  60186. if (this._localMatrix) {
  60187. this._localMatrix.copyFrom(val);
  60188. }
  60189. else {
  60190. this._localMatrix = val;
  60191. }
  60192. },
  60193. enumerable: true,
  60194. configurable: true
  60195. });
  60196. // Members
  60197. Bone.prototype.getSkeleton = function () {
  60198. return this._skeleton;
  60199. };
  60200. Bone.prototype.getParent = function () {
  60201. return this._parent;
  60202. };
  60203. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60204. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60205. if (this._parent === parent) {
  60206. return;
  60207. }
  60208. if (this._parent) {
  60209. var index = this._parent.children.indexOf(this);
  60210. if (index !== -1) {
  60211. this._parent.children.splice(index, 1);
  60212. }
  60213. }
  60214. this._parent = parent;
  60215. if (this._parent) {
  60216. this._parent.children.push(this);
  60217. }
  60218. if (updateDifferenceMatrix) {
  60219. this._updateDifferenceMatrix();
  60220. }
  60221. };
  60222. Bone.prototype.getLocalMatrix = function () {
  60223. return this._localMatrix;
  60224. };
  60225. Bone.prototype.getBaseMatrix = function () {
  60226. return this._baseMatrix;
  60227. };
  60228. Bone.prototype.getRestPose = function () {
  60229. return this._restPose;
  60230. };
  60231. Bone.prototype.returnToRest = function () {
  60232. this.updateMatrix(this._restPose.clone());
  60233. };
  60234. Bone.prototype.getWorldMatrix = function () {
  60235. return this._worldTransform;
  60236. };
  60237. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60238. return this._invertedAbsoluteTransform;
  60239. };
  60240. Bone.prototype.getAbsoluteTransform = function () {
  60241. return this._absoluteTransform;
  60242. };
  60243. Object.defineProperty(Bone.prototype, "position", {
  60244. // Properties (matches AbstractMesh properties)
  60245. get: function () {
  60246. return this.getPosition();
  60247. },
  60248. set: function (newPosition) {
  60249. this.setPosition(newPosition);
  60250. },
  60251. enumerable: true,
  60252. configurable: true
  60253. });
  60254. Object.defineProperty(Bone.prototype, "rotation", {
  60255. get: function () {
  60256. return this.getRotation();
  60257. },
  60258. set: function (newRotation) {
  60259. this.setRotation(newRotation);
  60260. },
  60261. enumerable: true,
  60262. configurable: true
  60263. });
  60264. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60265. get: function () {
  60266. return this.getRotationQuaternion();
  60267. },
  60268. set: function (newRotation) {
  60269. this.setRotationQuaternion(newRotation);
  60270. },
  60271. enumerable: true,
  60272. configurable: true
  60273. });
  60274. Object.defineProperty(Bone.prototype, "scaling", {
  60275. get: function () {
  60276. return this.getScale();
  60277. },
  60278. set: function (newScaling) {
  60279. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60280. },
  60281. enumerable: true,
  60282. configurable: true
  60283. });
  60284. // Methods
  60285. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60286. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60287. this._baseMatrix = matrix.clone();
  60288. this._localMatrix = matrix.clone();
  60289. this._skeleton._markAsDirty();
  60290. if (updateDifferenceMatrix) {
  60291. this._updateDifferenceMatrix();
  60292. }
  60293. };
  60294. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60295. if (!rootMatrix) {
  60296. rootMatrix = this._baseMatrix;
  60297. }
  60298. if (this._parent) {
  60299. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60300. }
  60301. else {
  60302. this._absoluteTransform.copyFrom(rootMatrix);
  60303. }
  60304. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60305. for (var index = 0; index < this.children.length; index++) {
  60306. this.children[index]._updateDifferenceMatrix();
  60307. }
  60308. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60309. };
  60310. Bone.prototype.markAsDirty = function () {
  60311. this._currentRenderId++;
  60312. this._skeleton._markAsDirty();
  60313. };
  60314. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60315. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60316. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60317. // all animation may be coming from a library skeleton, so may need to create animation
  60318. if (this.animations.length === 0) {
  60319. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60320. this.animations[0].setKeys([]);
  60321. }
  60322. // get animation info / verify there is such a range from the source bone
  60323. var sourceRange = source.animations[0].getRange(rangeName);
  60324. if (!sourceRange) {
  60325. return false;
  60326. }
  60327. var from = sourceRange.from;
  60328. var to = sourceRange.to;
  60329. var sourceKeys = source.animations[0].getKeys();
  60330. // rescaling prep
  60331. var sourceBoneLength = source.length;
  60332. var sourceParent = source.getParent();
  60333. var parent = this.getParent();
  60334. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60335. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60336. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60337. var destKeys = this.animations[0].getKeys();
  60338. // loop vars declaration
  60339. var orig;
  60340. var origTranslation;
  60341. var mat;
  60342. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60343. orig = sourceKeys[key];
  60344. if (orig.frame >= from && orig.frame <= to) {
  60345. if (rescaleAsRequired) {
  60346. mat = orig.value.clone();
  60347. // scale based on parent ratio, when bone has parent
  60348. if (parentScalingReqd) {
  60349. origTranslation = mat.getTranslation();
  60350. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60351. // scale based on skeleton dimension ratio when root bone, and value is passed
  60352. }
  60353. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60354. origTranslation = mat.getTranslation();
  60355. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60356. // use original when root bone, and no data for skelDimensionsRatio
  60357. }
  60358. else {
  60359. mat = orig.value;
  60360. }
  60361. }
  60362. else {
  60363. mat = orig.value;
  60364. }
  60365. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60366. }
  60367. }
  60368. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60369. return true;
  60370. };
  60371. /**
  60372. * Translate the bone in local or world space.
  60373. * @param vec The amount to translate the bone.
  60374. * @param space The space that the translation is in.
  60375. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60376. */
  60377. Bone.prototype.translate = function (vec, space, mesh) {
  60378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60379. var lm = this.getLocalMatrix();
  60380. if (space == BABYLON.Space.LOCAL) {
  60381. lm.m[12] += vec.x;
  60382. lm.m[13] += vec.y;
  60383. lm.m[14] += vec.z;
  60384. }
  60385. else {
  60386. var wm = null;
  60387. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60388. if (mesh) {
  60389. wm = mesh.getWorldMatrix();
  60390. }
  60391. this._skeleton.computeAbsoluteTransforms();
  60392. var tmat = Bone._tmpMats[0];
  60393. var tvec = Bone._tmpVecs[0];
  60394. if (this._parent) {
  60395. if (mesh && wm) {
  60396. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60397. tmat.multiplyToRef(wm, tmat);
  60398. }
  60399. else {
  60400. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60401. }
  60402. }
  60403. tmat.m[12] = 0;
  60404. tmat.m[13] = 0;
  60405. tmat.m[14] = 0;
  60406. tmat.invert();
  60407. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60408. lm.m[12] += tvec.x;
  60409. lm.m[13] += tvec.y;
  60410. lm.m[14] += tvec.z;
  60411. }
  60412. this.markAsDirty();
  60413. };
  60414. /**
  60415. * Set the postion of the bone in local or world space.
  60416. * @param position The position to set the bone.
  60417. * @param space The space that the position is in.
  60418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60419. */
  60420. Bone.prototype.setPosition = function (position, space, mesh) {
  60421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60422. var lm = this.getLocalMatrix();
  60423. if (space == BABYLON.Space.LOCAL) {
  60424. lm.m[12] = position.x;
  60425. lm.m[13] = position.y;
  60426. lm.m[14] = position.z;
  60427. }
  60428. else {
  60429. var wm = null;
  60430. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60431. if (mesh) {
  60432. wm = mesh.getWorldMatrix();
  60433. }
  60434. this._skeleton.computeAbsoluteTransforms();
  60435. var tmat = Bone._tmpMats[0];
  60436. var vec = Bone._tmpVecs[0];
  60437. if (this._parent) {
  60438. if (mesh && wm) {
  60439. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60440. tmat.multiplyToRef(wm, tmat);
  60441. }
  60442. else {
  60443. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60444. }
  60445. }
  60446. tmat.invert();
  60447. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60448. lm.m[12] = vec.x;
  60449. lm.m[13] = vec.y;
  60450. lm.m[14] = vec.z;
  60451. }
  60452. this.markAsDirty();
  60453. };
  60454. /**
  60455. * Set the absolute postion of the bone (world space).
  60456. * @param position The position to set the bone.
  60457. * @param mesh The mesh that this bone is attached to.
  60458. */
  60459. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60460. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60461. };
  60462. /**
  60463. * Set the scale of the bone on the x, y and z axes.
  60464. * @param x The scale of the bone on the x axis.
  60465. * @param x The scale of the bone on the y axis.
  60466. * @param z The scale of the bone on the z axis.
  60467. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60468. */
  60469. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60470. if (scaleChildren === void 0) { scaleChildren = false; }
  60471. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60472. if (!scaleChildren) {
  60473. this._negateScaleChildren.x = 1 / x;
  60474. this._negateScaleChildren.y = 1 / y;
  60475. this._negateScaleChildren.z = 1 / z;
  60476. }
  60477. this._syncScaleVector();
  60478. }
  60479. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60480. };
  60481. /**
  60482. * Scale the bone on the x, y and z axes.
  60483. * @param x The amount to scale the bone on the x axis.
  60484. * @param x The amount to scale the bone on the y axis.
  60485. * @param z The amount to scale the bone on the z axis.
  60486. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60487. */
  60488. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60489. if (scaleChildren === void 0) { scaleChildren = false; }
  60490. var locMat = this.getLocalMatrix();
  60491. var origLocMat = Bone._tmpMats[0];
  60492. origLocMat.copyFrom(locMat);
  60493. var origLocMatInv = Bone._tmpMats[1];
  60494. origLocMatInv.copyFrom(origLocMat);
  60495. origLocMatInv.invert();
  60496. var scaleMat = Bone._tmpMats[2];
  60497. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60498. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60499. this._scaleVector.x *= x;
  60500. this._scaleVector.y *= y;
  60501. this._scaleVector.z *= z;
  60502. locMat.multiplyToRef(origLocMatInv, locMat);
  60503. locMat.multiplyToRef(scaleMat, locMat);
  60504. locMat.multiplyToRef(origLocMat, locMat);
  60505. var parent = this.getParent();
  60506. if (parent) {
  60507. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60508. }
  60509. else {
  60510. this.getAbsoluteTransform().copyFrom(locMat);
  60511. }
  60512. var len = this.children.length;
  60513. scaleMat.invert();
  60514. for (var i = 0; i < len; i++) {
  60515. var child = this.children[i];
  60516. var cm = child.getLocalMatrix();
  60517. cm.multiplyToRef(scaleMat, cm);
  60518. var lm = child.getLocalMatrix();
  60519. lm.m[12] *= x;
  60520. lm.m[13] *= y;
  60521. lm.m[14] *= z;
  60522. }
  60523. this.computeAbsoluteTransforms();
  60524. if (scaleChildren) {
  60525. for (var i = 0; i < len; i++) {
  60526. this.children[i].scale(x, y, z, scaleChildren);
  60527. }
  60528. }
  60529. this.markAsDirty();
  60530. };
  60531. /**
  60532. * Set the yaw, pitch, and roll of the bone in local or world space.
  60533. * @param yaw The rotation of the bone on the y axis.
  60534. * @param pitch The rotation of the bone on the x axis.
  60535. * @param roll The rotation of the bone on the z axis.
  60536. * @param space The space that the axes of rotation are in.
  60537. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60538. */
  60539. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60541. var rotMat = Bone._tmpMats[0];
  60542. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60543. var rotMatInv = Bone._tmpMats[1];
  60544. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60545. rotMatInv.multiplyToRef(rotMat, rotMat);
  60546. this._rotateWithMatrix(rotMat, space, mesh);
  60547. };
  60548. /**
  60549. * Rotate the bone on an axis in local or world space.
  60550. * @param axis The axis to rotate the bone on.
  60551. * @param amount The amount to rotate the bone.
  60552. * @param space The space that the axis is in.
  60553. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60554. */
  60555. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60556. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60557. var rmat = Bone._tmpMats[0];
  60558. rmat.m[12] = 0;
  60559. rmat.m[13] = 0;
  60560. rmat.m[14] = 0;
  60561. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60562. this._rotateWithMatrix(rmat, space, mesh);
  60563. };
  60564. /**
  60565. * Set the rotation of the bone to a particular axis angle in local or world space.
  60566. * @param axis The axis to rotate the bone on.
  60567. * @param angle The angle that the bone should be rotated to.
  60568. * @param space The space that the axis is in.
  60569. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60570. */
  60571. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  60572. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60573. var rotMat = Bone._tmpMats[0];
  60574. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  60575. var rotMatInv = Bone._tmpMats[1];
  60576. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60577. rotMatInv.multiplyToRef(rotMat, rotMat);
  60578. this._rotateWithMatrix(rotMat, space, mesh);
  60579. };
  60580. /**
  60581. * Set the euler rotation of the bone in local of world space.
  60582. * @param rotation The euler rotation that the bone should be set to.
  60583. * @param space The space that the rotation is in.
  60584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60585. */
  60586. Bone.prototype.setRotation = function (rotation, space, mesh) {
  60587. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60588. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  60589. };
  60590. /**
  60591. * Set the quaternion rotation of the bone in local of world space.
  60592. * @param quat The quaternion rotation that the bone should be set to.
  60593. * @param space The space that the rotation is in.
  60594. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60595. */
  60596. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  60597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60598. var rotMatInv = Bone._tmpMats[0];
  60599. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60600. var rotMat = Bone._tmpMats[1];
  60601. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  60602. rotMatInv.multiplyToRef(rotMat, rotMat);
  60603. this._rotateWithMatrix(rotMat, space, mesh);
  60604. };
  60605. /**
  60606. * Set the rotation matrix of the bone in local of world space.
  60607. * @param rotMat The rotation matrix that the bone should be set to.
  60608. * @param space The space that the rotation is in.
  60609. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60610. */
  60611. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  60612. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60613. var rotMatInv = Bone._tmpMats[0];
  60614. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60615. var rotMat2 = Bone._tmpMats[1];
  60616. rotMat2.copyFrom(rotMat);
  60617. rotMatInv.multiplyToRef(rotMat, rotMat2);
  60618. this._rotateWithMatrix(rotMat2, space, mesh);
  60619. };
  60620. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  60621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60622. var lmat = this.getLocalMatrix();
  60623. var lx = lmat.m[12];
  60624. var ly = lmat.m[13];
  60625. var lz = lmat.m[14];
  60626. var parent = this.getParent();
  60627. var parentScale = Bone._tmpMats[3];
  60628. var parentScaleInv = Bone._tmpMats[4];
  60629. if (parent) {
  60630. if (space == BABYLON.Space.WORLD) {
  60631. if (mesh) {
  60632. parentScale.copyFrom(mesh.getWorldMatrix());
  60633. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  60634. }
  60635. else {
  60636. parentScale.copyFrom(parent.getAbsoluteTransform());
  60637. }
  60638. }
  60639. else {
  60640. parentScale = parent._scaleMatrix;
  60641. }
  60642. parentScaleInv.copyFrom(parentScale);
  60643. parentScaleInv.invert();
  60644. lmat.multiplyToRef(parentScale, lmat);
  60645. lmat.multiplyToRef(rmat, lmat);
  60646. lmat.multiplyToRef(parentScaleInv, lmat);
  60647. }
  60648. else {
  60649. if (space == BABYLON.Space.WORLD && mesh) {
  60650. parentScale.copyFrom(mesh.getWorldMatrix());
  60651. parentScaleInv.copyFrom(parentScale);
  60652. parentScaleInv.invert();
  60653. lmat.multiplyToRef(parentScale, lmat);
  60654. lmat.multiplyToRef(rmat, lmat);
  60655. lmat.multiplyToRef(parentScaleInv, lmat);
  60656. }
  60657. else {
  60658. lmat.multiplyToRef(rmat, lmat);
  60659. }
  60660. }
  60661. lmat.m[12] = lx;
  60662. lmat.m[13] = ly;
  60663. lmat.m[14] = lz;
  60664. this.computeAbsoluteTransforms();
  60665. this.markAsDirty();
  60666. };
  60667. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  60668. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60669. if (space == BABYLON.Space.WORLD) {
  60670. var scaleMatrix = Bone._tmpMats[2];
  60671. scaleMatrix.copyFrom(this._scaleMatrix);
  60672. rotMatInv.copyFrom(this.getAbsoluteTransform());
  60673. if (mesh) {
  60674. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  60675. var meshScale = Bone._tmpMats[3];
  60676. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  60677. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  60678. }
  60679. rotMatInv.invert();
  60680. scaleMatrix.m[0] *= this._scalingDeterminant;
  60681. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60682. }
  60683. else {
  60684. rotMatInv.copyFrom(this.getLocalMatrix());
  60685. rotMatInv.invert();
  60686. var scaleMatrix = Bone._tmpMats[2];
  60687. scaleMatrix.copyFrom(this._scaleMatrix);
  60688. if (this._parent) {
  60689. var pscaleMatrix = Bone._tmpMats[3];
  60690. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  60691. pscaleMatrix.invert();
  60692. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  60693. }
  60694. else {
  60695. scaleMatrix.m[0] *= this._scalingDeterminant;
  60696. }
  60697. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  60698. }
  60699. };
  60700. /**
  60701. * Get the scale of the bone
  60702. * @returns the scale of the bone
  60703. */
  60704. Bone.prototype.getScale = function () {
  60705. return this._scaleVector.clone();
  60706. };
  60707. /**
  60708. * Copy the scale of the bone to a vector3.
  60709. * @param result The vector3 to copy the scale to
  60710. */
  60711. Bone.prototype.getScaleToRef = function (result) {
  60712. result.copyFrom(this._scaleVector);
  60713. };
  60714. /**
  60715. * Get the position of the bone in local or world space.
  60716. * @param space The space that the returned position is in.
  60717. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60718. * @returns The position of the bone
  60719. */
  60720. Bone.prototype.getPosition = function (space, mesh) {
  60721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60722. if (mesh === void 0) { mesh = null; }
  60723. var pos = BABYLON.Vector3.Zero();
  60724. this.getPositionToRef(space, mesh, pos);
  60725. return pos;
  60726. };
  60727. /**
  60728. * Copy the position of the bone to a vector3 in local or world space.
  60729. * @param space The space that the returned position is in.
  60730. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60731. * @param result The vector3 to copy the position to.
  60732. */
  60733. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  60734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60735. if (space == BABYLON.Space.LOCAL) {
  60736. var lm = this.getLocalMatrix();
  60737. result.x = lm.m[12];
  60738. result.y = lm.m[13];
  60739. result.z = lm.m[14];
  60740. }
  60741. else {
  60742. var wm = null;
  60743. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60744. if (mesh) {
  60745. wm = mesh.getWorldMatrix();
  60746. }
  60747. this._skeleton.computeAbsoluteTransforms();
  60748. var tmat = Bone._tmpMats[0];
  60749. if (mesh && wm) {
  60750. tmat.copyFrom(this.getAbsoluteTransform());
  60751. tmat.multiplyToRef(wm, tmat);
  60752. }
  60753. else {
  60754. tmat = this.getAbsoluteTransform();
  60755. }
  60756. result.x = tmat.m[12];
  60757. result.y = tmat.m[13];
  60758. result.z = tmat.m[14];
  60759. }
  60760. };
  60761. /**
  60762. * Get the absolute position of the bone (world space).
  60763. * @param mesh The mesh that this bone is attached to.
  60764. * @returns The absolute position of the bone
  60765. */
  60766. Bone.prototype.getAbsolutePosition = function (mesh) {
  60767. if (mesh === void 0) { mesh = null; }
  60768. var pos = BABYLON.Vector3.Zero();
  60769. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  60770. return pos;
  60771. };
  60772. /**
  60773. * Copy the absolute position of the bone (world space) to the result param.
  60774. * @param mesh The mesh that this bone is attached to.
  60775. * @param result The vector3 to copy the absolute position to.
  60776. */
  60777. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  60778. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  60779. };
  60780. /**
  60781. * Compute the absolute transforms of this bone and its children.
  60782. */
  60783. Bone.prototype.computeAbsoluteTransforms = function () {
  60784. if (this._parent) {
  60785. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60786. }
  60787. else {
  60788. this._absoluteTransform.copyFrom(this._localMatrix);
  60789. var poseMatrix = this._skeleton.getPoseMatrix();
  60790. if (poseMatrix) {
  60791. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  60792. }
  60793. }
  60794. var children = this.children;
  60795. var len = children.length;
  60796. for (var i = 0; i < len; i++) {
  60797. children[i].computeAbsoluteTransforms();
  60798. }
  60799. };
  60800. Bone.prototype._syncScaleVector = function () {
  60801. var lm = this.getLocalMatrix();
  60802. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  60803. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  60804. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  60805. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  60806. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  60807. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  60808. this._scaleVector.x = xs * Math.sqrt(xsq);
  60809. this._scaleVector.y = ys * Math.sqrt(ysq);
  60810. this._scaleVector.z = zs * Math.sqrt(zsq);
  60811. if (this._parent) {
  60812. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  60813. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  60814. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  60815. }
  60816. 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);
  60817. };
  60818. /**
  60819. * Get the world direction from an axis that is in the local space of the bone.
  60820. * @param localAxis The local direction that is used to compute the world direction.
  60821. * @param mesh The mesh that this bone is attached to.
  60822. * @returns The world direction
  60823. */
  60824. Bone.prototype.getDirection = function (localAxis, mesh) {
  60825. if (mesh === void 0) { mesh = null; }
  60826. var result = BABYLON.Vector3.Zero();
  60827. this.getDirectionToRef(localAxis, mesh, result);
  60828. return result;
  60829. };
  60830. /**
  60831. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  60832. * @param localAxis The local direction that is used to compute the world direction.
  60833. * @param mesh The mesh that this bone is attached to.
  60834. * @param result The vector3 that the world direction will be copied to.
  60835. */
  60836. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  60837. if (mesh === void 0) { mesh = null; }
  60838. var wm = null;
  60839. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60840. if (mesh) {
  60841. wm = mesh.getWorldMatrix();
  60842. }
  60843. this._skeleton.computeAbsoluteTransforms();
  60844. var mat = Bone._tmpMats[0];
  60845. mat.copyFrom(this.getAbsoluteTransform());
  60846. if (mesh && wm) {
  60847. mat.multiplyToRef(wm, mat);
  60848. }
  60849. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  60850. result.normalize();
  60851. };
  60852. /**
  60853. * Get the euler rotation of the bone in local or world space.
  60854. * @param space The space that the rotation should be in.
  60855. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60856. * @returns The euler rotation
  60857. */
  60858. Bone.prototype.getRotation = function (space, mesh) {
  60859. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60860. if (mesh === void 0) { mesh = null; }
  60861. var result = BABYLON.Vector3.Zero();
  60862. this.getRotationToRef(space, mesh, result);
  60863. return result;
  60864. };
  60865. /**
  60866. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  60867. * @param space The space that the rotation should be in.
  60868. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60869. * @param result The vector3 that the rotation should be copied to.
  60870. */
  60871. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  60872. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60873. if (mesh === void 0) { mesh = null; }
  60874. var quat = Bone._tmpQuat;
  60875. this.getRotationQuaternionToRef(space, mesh, quat);
  60876. quat.toEulerAnglesToRef(result);
  60877. };
  60878. /**
  60879. * Get the quaternion rotation of the bone in either local or world space.
  60880. * @param space The space that the rotation should be in.
  60881. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60882. * @returns The quaternion rotation
  60883. */
  60884. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  60885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60886. if (mesh === void 0) { mesh = null; }
  60887. var result = BABYLON.Quaternion.Identity();
  60888. this.getRotationQuaternionToRef(space, mesh, result);
  60889. return result;
  60890. };
  60891. /**
  60892. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  60893. * @param space The space that the rotation should be in.
  60894. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60895. * @param result The quaternion that the rotation should be copied to.
  60896. */
  60897. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  60898. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60899. if (mesh === void 0) { mesh = null; }
  60900. if (space == BABYLON.Space.LOCAL) {
  60901. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60902. }
  60903. else {
  60904. var mat = Bone._tmpMats[0];
  60905. var amat = this.getAbsoluteTransform();
  60906. if (mesh) {
  60907. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60908. }
  60909. else {
  60910. mat.copyFrom(amat);
  60911. }
  60912. mat.m[0] *= this._scalingDeterminant;
  60913. mat.m[1] *= this._scalingDeterminant;
  60914. mat.m[2] *= this._scalingDeterminant;
  60915. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  60916. }
  60917. };
  60918. /**
  60919. * Get the rotation matrix of the bone in local or world space.
  60920. * @param space The space that the rotation should be in.
  60921. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60922. * @returns The rotation matrix
  60923. */
  60924. Bone.prototype.getRotationMatrix = function (space, mesh) {
  60925. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60926. var result = BABYLON.Matrix.Identity();
  60927. this.getRotationMatrixToRef(space, mesh, result);
  60928. return result;
  60929. };
  60930. /**
  60931. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  60932. * @param space The space that the rotation should be in.
  60933. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60934. * @param result The quaternion that the rotation should be copied to.
  60935. */
  60936. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  60937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60938. if (space == BABYLON.Space.LOCAL) {
  60939. this.getLocalMatrix().getRotationMatrixToRef(result);
  60940. }
  60941. else {
  60942. var mat = Bone._tmpMats[0];
  60943. var amat = this.getAbsoluteTransform();
  60944. if (mesh) {
  60945. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  60946. }
  60947. else {
  60948. mat.copyFrom(amat);
  60949. }
  60950. mat.m[0] *= this._scalingDeterminant;
  60951. mat.m[1] *= this._scalingDeterminant;
  60952. mat.m[2] *= this._scalingDeterminant;
  60953. mat.getRotationMatrixToRef(result);
  60954. }
  60955. };
  60956. /**
  60957. * Get the world position of a point that is in the local space of the bone.
  60958. * @param position The local position
  60959. * @param mesh The mesh that this bone is attached to.
  60960. * @returns The world position
  60961. */
  60962. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  60963. if (mesh === void 0) { mesh = null; }
  60964. var result = BABYLON.Vector3.Zero();
  60965. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  60966. return result;
  60967. };
  60968. /**
  60969. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  60970. * @param position The local position
  60971. * @param mesh The mesh that this bone is attached to.
  60972. * @param result The vector3 that the world position should be copied to.
  60973. */
  60974. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  60975. if (mesh === void 0) { mesh = null; }
  60976. var wm = null;
  60977. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60978. if (mesh) {
  60979. wm = mesh.getWorldMatrix();
  60980. }
  60981. this._skeleton.computeAbsoluteTransforms();
  60982. var tmat = Bone._tmpMats[0];
  60983. if (mesh && wm) {
  60984. tmat.copyFrom(this.getAbsoluteTransform());
  60985. tmat.multiplyToRef(wm, tmat);
  60986. }
  60987. else {
  60988. tmat = this.getAbsoluteTransform();
  60989. }
  60990. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  60991. };
  60992. /**
  60993. * Get the local position of a point that is in world space.
  60994. * @param position The world position
  60995. * @param mesh The mesh that this bone is attached to.
  60996. * @returns The local position
  60997. */
  60998. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  60999. if (mesh === void 0) { mesh = null; }
  61000. var result = BABYLON.Vector3.Zero();
  61001. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61002. return result;
  61003. };
  61004. /**
  61005. * Get the local position of a point that is in world space and copy it to the result param.
  61006. * @param position The world position
  61007. * @param mesh The mesh that this bone is attached to.
  61008. * @param result The vector3 that the local position should be copied to.
  61009. */
  61010. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61011. if (mesh === void 0) { mesh = null; }
  61012. var wm = null;
  61013. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61014. if (mesh) {
  61015. wm = mesh.getWorldMatrix();
  61016. }
  61017. this._skeleton.computeAbsoluteTransforms();
  61018. var tmat = Bone._tmpMats[0];
  61019. tmat.copyFrom(this.getAbsoluteTransform());
  61020. if (mesh && wm) {
  61021. tmat.multiplyToRef(wm, tmat);
  61022. }
  61023. tmat.invert();
  61024. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61025. };
  61026. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61027. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61028. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61029. return Bone;
  61030. }(BABYLON.Node));
  61031. BABYLON.Bone = Bone;
  61032. })(BABYLON || (BABYLON = {}));
  61033. //# sourceMappingURL=babylon.bone.js.map
  61034. var BABYLON;
  61035. (function (BABYLON) {
  61036. var BoneIKController = /** @class */ (function () {
  61037. function BoneIKController(mesh, bone, options) {
  61038. this.targetPosition = BABYLON.Vector3.Zero();
  61039. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61040. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61041. this.poleAngle = 0;
  61042. this.slerpAmount = 1;
  61043. this._bone1Quat = BABYLON.Quaternion.Identity();
  61044. this._bone1Mat = BABYLON.Matrix.Identity();
  61045. this._bone2Ang = Math.PI;
  61046. this._maxAngle = Math.PI;
  61047. this._rightHandedSystem = false;
  61048. this._bendAxis = BABYLON.Vector3.Right();
  61049. this._slerping = false;
  61050. this._adjustRoll = 0;
  61051. this._bone2 = bone;
  61052. this._bone1 = bone.getParent();
  61053. if (!this._bone1) {
  61054. return;
  61055. }
  61056. this.mesh = mesh;
  61057. var bonePos = bone.getPosition();
  61058. if (bone.getAbsoluteTransform().determinant() > 0) {
  61059. this._rightHandedSystem = true;
  61060. this._bendAxis.x = 0;
  61061. this._bendAxis.y = 0;
  61062. this._bendAxis.z = -1;
  61063. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61064. this._adjustRoll = Math.PI * .5;
  61065. this._bendAxis.z = 1;
  61066. }
  61067. }
  61068. if (this._bone1.length) {
  61069. var boneScale1 = this._bone1.getScale();
  61070. var boneScale2 = this._bone2.getScale();
  61071. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61072. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61073. }
  61074. else if (this._bone1.children[0]) {
  61075. mesh.computeWorldMatrix(true);
  61076. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61077. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61078. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61079. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61080. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61081. }
  61082. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61083. this.maxAngle = Math.PI;
  61084. if (options) {
  61085. if (options.targetMesh) {
  61086. this.targetMesh = options.targetMesh;
  61087. this.targetMesh.computeWorldMatrix(true);
  61088. }
  61089. if (options.poleTargetMesh) {
  61090. this.poleTargetMesh = options.poleTargetMesh;
  61091. this.poleTargetMesh.computeWorldMatrix(true);
  61092. }
  61093. else if (options.poleTargetBone) {
  61094. this.poleTargetBone = options.poleTargetBone;
  61095. }
  61096. else if (this._bone1.getParent()) {
  61097. this.poleTargetBone = this._bone1.getParent();
  61098. }
  61099. if (options.poleTargetLocalOffset) {
  61100. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61101. }
  61102. if (options.poleAngle) {
  61103. this.poleAngle = options.poleAngle;
  61104. }
  61105. if (options.bendAxis) {
  61106. this._bendAxis.copyFrom(options.bendAxis);
  61107. }
  61108. if (options.maxAngle) {
  61109. this.maxAngle = options.maxAngle;
  61110. }
  61111. if (options.slerpAmount) {
  61112. this.slerpAmount = options.slerpAmount;
  61113. }
  61114. }
  61115. }
  61116. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61117. get: function () {
  61118. return this._maxAngle;
  61119. },
  61120. set: function (value) {
  61121. this._setMaxAngle(value);
  61122. },
  61123. enumerable: true,
  61124. configurable: true
  61125. });
  61126. BoneIKController.prototype._setMaxAngle = function (ang) {
  61127. if (ang < 0) {
  61128. ang = 0;
  61129. }
  61130. if (ang > Math.PI || ang == undefined) {
  61131. ang = Math.PI;
  61132. }
  61133. this._maxAngle = ang;
  61134. var a = this._bone1Length;
  61135. var b = this._bone2Length;
  61136. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61137. };
  61138. BoneIKController.prototype.update = function () {
  61139. var bone1 = this._bone1;
  61140. if (!bone1) {
  61141. return;
  61142. }
  61143. var target = this.targetPosition;
  61144. var poleTarget = this.poleTargetPosition;
  61145. var mat1 = BoneIKController._tmpMats[0];
  61146. var mat2 = BoneIKController._tmpMats[1];
  61147. if (this.targetMesh) {
  61148. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61149. }
  61150. if (this.poleTargetBone) {
  61151. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61152. }
  61153. else if (this.poleTargetMesh) {
  61154. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61155. }
  61156. var bonePos = BoneIKController._tmpVecs[0];
  61157. var zaxis = BoneIKController._tmpVecs[1];
  61158. var xaxis = BoneIKController._tmpVecs[2];
  61159. var yaxis = BoneIKController._tmpVecs[3];
  61160. var upAxis = BoneIKController._tmpVecs[4];
  61161. var _tmpQuat = BoneIKController._tmpQuat;
  61162. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61163. poleTarget.subtractToRef(bonePos, upAxis);
  61164. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61165. upAxis.y = 1;
  61166. }
  61167. else {
  61168. upAxis.normalize();
  61169. }
  61170. target.subtractToRef(bonePos, yaxis);
  61171. yaxis.normalize();
  61172. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61173. zaxis.normalize();
  61174. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61175. xaxis.normalize();
  61176. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61177. var a = this._bone1Length;
  61178. var b = this._bone2Length;
  61179. var c = BABYLON.Vector3.Distance(bonePos, target);
  61180. if (this._maxReach > 0) {
  61181. c = Math.min(this._maxReach, c);
  61182. }
  61183. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61184. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61185. if (acosa > 1) {
  61186. acosa = 1;
  61187. }
  61188. if (acosb > 1) {
  61189. acosb = 1;
  61190. }
  61191. if (acosa < -1) {
  61192. acosa = -1;
  61193. }
  61194. if (acosb < -1) {
  61195. acosb = -1;
  61196. }
  61197. var angA = Math.acos(acosa);
  61198. var angB = Math.acos(acosb);
  61199. var angC = -angA - angB;
  61200. if (this._rightHandedSystem) {
  61201. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61202. mat2.multiplyToRef(mat1, mat1);
  61203. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61204. mat2.multiplyToRef(mat1, mat1);
  61205. }
  61206. else {
  61207. var _tmpVec = BoneIKController._tmpVecs[5];
  61208. _tmpVec.copyFrom(this._bendAxis);
  61209. _tmpVec.x *= -1;
  61210. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61211. mat2.multiplyToRef(mat1, mat1);
  61212. }
  61213. if (this.poleAngle) {
  61214. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61215. mat1.multiplyToRef(mat2, mat1);
  61216. }
  61217. if (this._bone1) {
  61218. if (this.slerpAmount < 1) {
  61219. if (!this._slerping) {
  61220. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61221. }
  61222. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61223. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61224. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61225. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61226. this._slerping = true;
  61227. }
  61228. else {
  61229. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61230. this._bone1Mat.copyFrom(mat1);
  61231. this._slerping = false;
  61232. }
  61233. }
  61234. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61235. this._bone2Ang = angC;
  61236. };
  61237. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61238. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61239. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61240. return BoneIKController;
  61241. }());
  61242. BABYLON.BoneIKController = BoneIKController;
  61243. })(BABYLON || (BABYLON = {}));
  61244. //# sourceMappingURL=babylon.boneIKController.js.map
  61245. var BABYLON;
  61246. (function (BABYLON) {
  61247. var BoneLookController = /** @class */ (function () {
  61248. /**
  61249. * Create a BoneLookController
  61250. * @param mesh the mesh that the bone belongs to
  61251. * @param bone the bone that will be looking to the target
  61252. * @param target the target Vector3 to look at
  61253. * @param settings optional settings:
  61254. * - maxYaw: the maximum angle the bone will yaw to
  61255. * - minYaw: the minimum angle the bone will yaw to
  61256. * - maxPitch: the maximum angle the bone will pitch to
  61257. * - minPitch: the minimum angle the bone will yaw to
  61258. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61259. * - upAxis: the up axis of the coordinate system
  61260. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61261. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61262. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61263. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61264. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61265. * - adjustRoll: used to make an adjustment to the roll of the bone
  61266. **/
  61267. function BoneLookController(mesh, bone, target, options) {
  61268. /**
  61269. * The up axis of the coordinate system that is used when the bone is rotated.
  61270. */
  61271. this.upAxis = BABYLON.Vector3.Up();
  61272. /**
  61273. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61274. */
  61275. this.upAxisSpace = BABYLON.Space.LOCAL;
  61276. /**
  61277. * Used to make an adjustment to the yaw of the bone.
  61278. */
  61279. this.adjustYaw = 0;
  61280. /**
  61281. * Used to make an adjustment to the pitch of the bone.
  61282. */
  61283. this.adjustPitch = 0;
  61284. /**
  61285. * Used to make an adjustment to the roll of the bone.
  61286. */
  61287. this.adjustRoll = 0;
  61288. /**
  61289. * 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).
  61290. */
  61291. this.slerpAmount = 1;
  61292. this._boneQuat = BABYLON.Quaternion.Identity();
  61293. this._slerping = false;
  61294. this._firstFrameSkipped = false;
  61295. this._fowardAxis = BABYLON.Vector3.Forward();
  61296. this.mesh = mesh;
  61297. this.bone = bone;
  61298. this.target = target;
  61299. if (options) {
  61300. if (options.adjustYaw) {
  61301. this.adjustYaw = options.adjustYaw;
  61302. }
  61303. if (options.adjustPitch) {
  61304. this.adjustPitch = options.adjustPitch;
  61305. }
  61306. if (options.adjustRoll) {
  61307. this.adjustRoll = options.adjustRoll;
  61308. }
  61309. if (options.maxYaw != null) {
  61310. this.maxYaw = options.maxYaw;
  61311. }
  61312. else {
  61313. this.maxYaw = Math.PI;
  61314. }
  61315. if (options.minYaw != null) {
  61316. this.minYaw = options.minYaw;
  61317. }
  61318. else {
  61319. this.minYaw = -Math.PI;
  61320. }
  61321. if (options.maxPitch != null) {
  61322. this.maxPitch = options.maxPitch;
  61323. }
  61324. else {
  61325. this.maxPitch = Math.PI;
  61326. }
  61327. if (options.minPitch != null) {
  61328. this.minPitch = options.minPitch;
  61329. }
  61330. else {
  61331. this.minPitch = -Math.PI;
  61332. }
  61333. if (options.slerpAmount != null) {
  61334. this.slerpAmount = options.slerpAmount;
  61335. }
  61336. if (options.upAxis != null) {
  61337. this.upAxis = options.upAxis;
  61338. }
  61339. if (options.upAxisSpace != null) {
  61340. this.upAxisSpace = options.upAxisSpace;
  61341. }
  61342. if (options.yawAxis != null || options.pitchAxis != null) {
  61343. var newYawAxis = BABYLON.Axis.Y;
  61344. var newPitchAxis = BABYLON.Axis.X;
  61345. if (options.yawAxis != null) {
  61346. newYawAxis = options.yawAxis.clone();
  61347. newYawAxis.normalize();
  61348. }
  61349. if (options.pitchAxis != null) {
  61350. newPitchAxis = options.pitchAxis.clone();
  61351. newPitchAxis.normalize();
  61352. }
  61353. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61354. this._transformYawPitch = BABYLON.Matrix.Identity();
  61355. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61356. this._transformYawPitchInv = this._transformYawPitch.clone();
  61357. this._transformYawPitch.invert();
  61358. }
  61359. }
  61360. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61361. this.upAxisSpace = BABYLON.Space.LOCAL;
  61362. }
  61363. }
  61364. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61365. /**
  61366. * Get/set the minimum yaw angle that the bone can look to.
  61367. */
  61368. get: function () {
  61369. return this._minYaw;
  61370. },
  61371. set: function (value) {
  61372. this._minYaw = value;
  61373. this._minYawSin = Math.sin(value);
  61374. this._minYawCos = Math.cos(value);
  61375. if (this._maxYaw != null) {
  61376. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61377. this._yawRange = this._maxYaw - this._minYaw;
  61378. }
  61379. },
  61380. enumerable: true,
  61381. configurable: true
  61382. });
  61383. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61384. /**
  61385. * Get/set the maximum yaw angle that the bone can look to.
  61386. */
  61387. get: function () {
  61388. return this._maxYaw;
  61389. },
  61390. set: function (value) {
  61391. this._maxYaw = value;
  61392. this._maxYawSin = Math.sin(value);
  61393. this._maxYawCos = Math.cos(value);
  61394. if (this._minYaw != null) {
  61395. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61396. this._yawRange = this._maxYaw - this._minYaw;
  61397. }
  61398. },
  61399. enumerable: true,
  61400. configurable: true
  61401. });
  61402. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61403. /**
  61404. * Get/set the minimum pitch angle that the bone can look to.
  61405. */
  61406. get: function () {
  61407. return this._minPitch;
  61408. },
  61409. set: function (value) {
  61410. this._minPitch = value;
  61411. this._minPitchTan = Math.tan(value);
  61412. },
  61413. enumerable: true,
  61414. configurable: true
  61415. });
  61416. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61417. /**
  61418. * Get/set the maximum pitch angle that the bone can look to.
  61419. */
  61420. get: function () {
  61421. return this._maxPitch;
  61422. },
  61423. set: function (value) {
  61424. this._maxPitch = value;
  61425. this._maxPitchTan = Math.tan(value);
  61426. },
  61427. enumerable: true,
  61428. configurable: true
  61429. });
  61430. /**
  61431. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61432. */
  61433. BoneLookController.prototype.update = function () {
  61434. //skip the first frame when slerping so that the mesh rotation is correct
  61435. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61436. this._firstFrameSkipped = true;
  61437. return;
  61438. }
  61439. var bone = this.bone;
  61440. var bonePos = BoneLookController._tmpVecs[0];
  61441. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61442. var target = this.target;
  61443. var _tmpMat1 = BoneLookController._tmpMats[0];
  61444. var _tmpMat2 = BoneLookController._tmpMats[1];
  61445. var mesh = this.mesh;
  61446. var parentBone = bone.getParent();
  61447. var upAxis = BoneLookController._tmpVecs[1];
  61448. upAxis.copyFrom(this.upAxis);
  61449. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61450. if (this._transformYawPitch) {
  61451. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61452. }
  61453. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61454. }
  61455. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61456. mesh.getDirectionToRef(upAxis, upAxis);
  61457. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61458. upAxis.normalize();
  61459. }
  61460. }
  61461. var checkYaw = false;
  61462. var checkPitch = false;
  61463. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61464. checkYaw = true;
  61465. }
  61466. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61467. checkPitch = true;
  61468. }
  61469. if (checkYaw || checkPitch) {
  61470. var spaceMat = BoneLookController._tmpMats[2];
  61471. var spaceMatInv = BoneLookController._tmpMats[3];
  61472. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61473. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61474. }
  61475. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61476. spaceMat.copyFrom(mesh.getWorldMatrix());
  61477. }
  61478. else {
  61479. var forwardAxis = BoneLookController._tmpVecs[2];
  61480. forwardAxis.copyFrom(this._fowardAxis);
  61481. if (this._transformYawPitch) {
  61482. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61483. }
  61484. if (parentBone) {
  61485. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61486. }
  61487. else {
  61488. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61489. }
  61490. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61491. rightAxis.normalize();
  61492. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61493. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61494. }
  61495. spaceMat.invertToRef(spaceMatInv);
  61496. var xzlen = null;
  61497. if (checkPitch) {
  61498. var localTarget = BoneLookController._tmpVecs[3];
  61499. target.subtractToRef(bonePos, localTarget);
  61500. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61501. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61502. var pitch = Math.atan2(localTarget.y, xzlen);
  61503. var newPitch = pitch;
  61504. if (pitch > this._maxPitch) {
  61505. localTarget.y = this._maxPitchTan * xzlen;
  61506. newPitch = this._maxPitch;
  61507. }
  61508. else if (pitch < this._minPitch) {
  61509. localTarget.y = this._minPitchTan * xzlen;
  61510. newPitch = this._minPitch;
  61511. }
  61512. if (pitch != newPitch) {
  61513. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61514. localTarget.addInPlace(bonePos);
  61515. target = localTarget;
  61516. }
  61517. }
  61518. if (checkYaw) {
  61519. var localTarget = BoneLookController._tmpVecs[4];
  61520. target.subtractToRef(bonePos, localTarget);
  61521. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61522. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61523. var newYaw = yaw;
  61524. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61525. if (xzlen == null) {
  61526. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61527. }
  61528. if (this._yawRange > Math.PI) {
  61529. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61530. localTarget.z = this._maxYawCos * xzlen;
  61531. localTarget.x = this._maxYawSin * xzlen;
  61532. newYaw = this._maxYaw;
  61533. }
  61534. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61535. localTarget.z = this._minYawCos * xzlen;
  61536. localTarget.x = this._minYawSin * xzlen;
  61537. newYaw = this._minYaw;
  61538. }
  61539. }
  61540. else {
  61541. if (yaw > this._maxYaw) {
  61542. localTarget.z = this._maxYawCos * xzlen;
  61543. localTarget.x = this._maxYawSin * xzlen;
  61544. newYaw = this._maxYaw;
  61545. }
  61546. else if (yaw < this._minYaw) {
  61547. localTarget.z = this._minYawCos * xzlen;
  61548. localTarget.x = this._minYawSin * xzlen;
  61549. newYaw = this._minYaw;
  61550. }
  61551. }
  61552. }
  61553. if (this._slerping && this._yawRange > Math.PI) {
  61554. //are we going to be crossing into the min/max region?
  61555. var boneFwd = BoneLookController._tmpVecs[8];
  61556. boneFwd.copyFrom(BABYLON.Axis.Z);
  61557. if (this._transformYawPitch) {
  61558. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61559. }
  61560. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61561. this._boneQuat.toRotationMatrix(boneRotMat);
  61562. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  61563. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  61564. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  61565. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  61566. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  61567. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  61568. if (angBtwTar > angBtwMidYaw) {
  61569. if (xzlen == null) {
  61570. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61571. }
  61572. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  61573. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  61574. if (angBtwMin < angBtwMax) {
  61575. newYaw = boneYaw + Math.PI * .75;
  61576. localTarget.z = Math.cos(newYaw) * xzlen;
  61577. localTarget.x = Math.sin(newYaw) * xzlen;
  61578. }
  61579. else {
  61580. newYaw = boneYaw - Math.PI * .75;
  61581. localTarget.z = Math.cos(newYaw) * xzlen;
  61582. localTarget.x = Math.sin(newYaw) * xzlen;
  61583. }
  61584. }
  61585. }
  61586. if (yaw != newYaw) {
  61587. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61588. localTarget.addInPlace(bonePos);
  61589. target = localTarget;
  61590. }
  61591. }
  61592. }
  61593. var zaxis = BoneLookController._tmpVecs[5];
  61594. var xaxis = BoneLookController._tmpVecs[6];
  61595. var yaxis = BoneLookController._tmpVecs[7];
  61596. var _tmpQuat = BoneLookController._tmpQuat;
  61597. target.subtractToRef(bonePos, zaxis);
  61598. zaxis.normalize();
  61599. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  61600. xaxis.normalize();
  61601. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  61602. yaxis.normalize();
  61603. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  61604. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  61605. return;
  61606. }
  61607. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  61608. return;
  61609. }
  61610. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  61611. return;
  61612. }
  61613. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  61614. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  61615. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  61616. }
  61617. if (this.slerpAmount < 1) {
  61618. if (!this._slerping) {
  61619. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  61620. }
  61621. if (this._transformYawPitch) {
  61622. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61623. }
  61624. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  61625. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  61626. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  61627. this._slerping = true;
  61628. }
  61629. else {
  61630. if (this._transformYawPitch) {
  61631. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  61632. }
  61633. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  61634. this._slerping = false;
  61635. }
  61636. };
  61637. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  61638. var angDiff = ang2 - ang1;
  61639. angDiff %= Math.PI * 2;
  61640. if (angDiff > Math.PI) {
  61641. angDiff -= Math.PI * 2;
  61642. }
  61643. else if (angDiff < -Math.PI) {
  61644. angDiff += Math.PI * 2;
  61645. }
  61646. return angDiff;
  61647. };
  61648. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  61649. ang1 %= (2 * Math.PI);
  61650. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61651. ang2 %= (2 * Math.PI);
  61652. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61653. var ab = 0;
  61654. if (ang1 < ang2) {
  61655. ab = ang2 - ang1;
  61656. }
  61657. else {
  61658. ab = ang1 - ang2;
  61659. }
  61660. if (ab > Math.PI) {
  61661. ab = Math.PI * 2 - ab;
  61662. }
  61663. return ab;
  61664. };
  61665. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  61666. ang %= (2 * Math.PI);
  61667. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  61668. ang1 %= (2 * Math.PI);
  61669. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  61670. ang2 %= (2 * Math.PI);
  61671. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  61672. if (ang1 < ang2) {
  61673. if (ang > ang1 && ang < ang2) {
  61674. return true;
  61675. }
  61676. }
  61677. else {
  61678. if (ang > ang2 && ang < ang1) {
  61679. return true;
  61680. }
  61681. }
  61682. return false;
  61683. };
  61684. 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()];
  61685. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  61686. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61687. return BoneLookController;
  61688. }());
  61689. BABYLON.BoneLookController = BoneLookController;
  61690. })(BABYLON || (BABYLON = {}));
  61691. //# sourceMappingURL=babylon.boneLookController.js.map
  61692. var BABYLON;
  61693. (function (BABYLON) {
  61694. var Skeleton = /** @class */ (function () {
  61695. function Skeleton(name, id, scene) {
  61696. this.name = name;
  61697. this.id = id;
  61698. this.bones = new Array();
  61699. this.needInitialSkinMatrix = false;
  61700. this._isDirty = true;
  61701. this._meshesWithPoseMatrix = new Array();
  61702. this._identity = BABYLON.Matrix.Identity();
  61703. this._ranges = {};
  61704. this._lastAbsoluteTransformsUpdateId = -1;
  61705. // Events
  61706. /**
  61707. * An event triggered before computing the skeleton's matrices
  61708. * @type {BABYLON.Observable}
  61709. */
  61710. this.onBeforeComputeObservable = new BABYLON.Observable();
  61711. this.bones = [];
  61712. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61713. scene.skeletons.push(this);
  61714. //make sure it will recalculate the matrix next time prepare is called.
  61715. this._isDirty = true;
  61716. }
  61717. // Members
  61718. Skeleton.prototype.getTransformMatrices = function (mesh) {
  61719. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  61720. return mesh._bonesTransformMatrices;
  61721. }
  61722. if (!this._transformMatrices) {
  61723. this.prepare();
  61724. }
  61725. return this._transformMatrices;
  61726. };
  61727. Skeleton.prototype.getScene = function () {
  61728. return this._scene;
  61729. };
  61730. // Methods
  61731. /**
  61732. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  61733. */
  61734. Skeleton.prototype.toString = function (fullDetails) {
  61735. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  61736. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  61737. if (fullDetails) {
  61738. ret += ", Ranges: {";
  61739. var first = true;
  61740. for (var name_1 in this._ranges) {
  61741. if (first) {
  61742. ret += ", ";
  61743. first = false;
  61744. }
  61745. ret += name_1;
  61746. }
  61747. ret += "}";
  61748. }
  61749. return ret;
  61750. };
  61751. /**
  61752. * Get bone's index searching by name
  61753. * @param {string} name is bone's name to search for
  61754. * @return {number} Indice of the bone. Returns -1 if not found
  61755. */
  61756. Skeleton.prototype.getBoneIndexByName = function (name) {
  61757. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  61758. if (this.bones[boneIndex].name === name) {
  61759. return boneIndex;
  61760. }
  61761. }
  61762. return -1;
  61763. };
  61764. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  61765. // check name not already in use
  61766. if (!this._ranges[name]) {
  61767. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  61768. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61769. if (this.bones[i].animations[0]) {
  61770. this.bones[i].animations[0].createRange(name, from, to);
  61771. }
  61772. }
  61773. }
  61774. };
  61775. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  61776. if (deleteFrames === void 0) { deleteFrames = true; }
  61777. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61778. if (this.bones[i].animations[0]) {
  61779. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  61780. }
  61781. }
  61782. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  61783. };
  61784. Skeleton.prototype.getAnimationRange = function (name) {
  61785. return this._ranges[name];
  61786. };
  61787. /**
  61788. * Returns as an Array, all AnimationRanges defined on this skeleton
  61789. */
  61790. Skeleton.prototype.getAnimationRanges = function () {
  61791. var animationRanges = [];
  61792. var name;
  61793. var i = 0;
  61794. for (name in this._ranges) {
  61795. animationRanges[i] = this._ranges[name];
  61796. i++;
  61797. }
  61798. return animationRanges;
  61799. };
  61800. /**
  61801. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  61802. */
  61803. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  61804. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61805. if (this._ranges[name] || !source.getAnimationRange(name)) {
  61806. return false;
  61807. }
  61808. var ret = true;
  61809. var frameOffset = this._getHighestAnimationFrame() + 1;
  61810. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  61811. var boneDict = {};
  61812. var sourceBones = source.bones;
  61813. var nBones;
  61814. var i;
  61815. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  61816. boneDict[sourceBones[i].name] = sourceBones[i];
  61817. }
  61818. if (this.bones.length !== sourceBones.length) {
  61819. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  61820. ret = false;
  61821. }
  61822. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  61823. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  61824. var boneName = this.bones[i].name;
  61825. var sourceBone = boneDict[boneName];
  61826. if (sourceBone) {
  61827. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  61828. }
  61829. else {
  61830. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  61831. ret = false;
  61832. }
  61833. }
  61834. // do not call createAnimationRange(), since it also is done to bones, which was already done
  61835. var range = source.getAnimationRange(name);
  61836. if (range) {
  61837. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  61838. }
  61839. return ret;
  61840. };
  61841. Skeleton.prototype.returnToRest = function () {
  61842. for (var index = 0; index < this.bones.length; index++) {
  61843. this.bones[index].returnToRest();
  61844. }
  61845. };
  61846. Skeleton.prototype._getHighestAnimationFrame = function () {
  61847. var ret = 0;
  61848. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  61849. if (this.bones[i].animations[0]) {
  61850. var highest = this.bones[i].animations[0].getHighestFrame();
  61851. if (ret < highest) {
  61852. ret = highest;
  61853. }
  61854. }
  61855. }
  61856. return ret;
  61857. };
  61858. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  61859. var range = this.getAnimationRange(name);
  61860. if (!range) {
  61861. return null;
  61862. }
  61863. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  61864. };
  61865. Skeleton.prototype._markAsDirty = function () {
  61866. this._isDirty = true;
  61867. };
  61868. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  61869. this._meshesWithPoseMatrix.push(mesh);
  61870. };
  61871. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  61872. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  61873. if (index > -1) {
  61874. this._meshesWithPoseMatrix.splice(index, 1);
  61875. }
  61876. };
  61877. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  61878. this.onBeforeComputeObservable.notifyObservers(this);
  61879. for (var index = 0; index < this.bones.length; index++) {
  61880. var bone = this.bones[index];
  61881. var parentBone = bone.getParent();
  61882. if (parentBone) {
  61883. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  61884. }
  61885. else {
  61886. if (initialSkinMatrix) {
  61887. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  61888. }
  61889. else {
  61890. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  61891. }
  61892. }
  61893. if (bone._index !== -1) {
  61894. var mappedIndex = bone._index === null ? index : bone._index;
  61895. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  61896. }
  61897. }
  61898. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  61899. };
  61900. Skeleton.prototype.prepare = function () {
  61901. if (!this._isDirty) {
  61902. return;
  61903. }
  61904. if (this.needInitialSkinMatrix) {
  61905. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  61906. var mesh = this._meshesWithPoseMatrix[index];
  61907. var poseMatrix = mesh.getPoseMatrix();
  61908. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  61909. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61910. }
  61911. if (this._synchronizedWithMesh !== mesh) {
  61912. this._synchronizedWithMesh = mesh;
  61913. // Prepare bones
  61914. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  61915. var bone = this.bones[boneIndex];
  61916. if (!bone.getParent()) {
  61917. var matrix = bone.getBaseMatrix();
  61918. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  61919. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  61920. }
  61921. }
  61922. }
  61923. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  61924. }
  61925. }
  61926. else {
  61927. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  61928. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  61929. }
  61930. this._computeTransformMatrices(this._transformMatrices, null);
  61931. }
  61932. this._isDirty = false;
  61933. this._scene._activeBones.addCount(this.bones.length, false);
  61934. };
  61935. Skeleton.prototype.getAnimatables = function () {
  61936. if (!this._animatables || this._animatables.length !== this.bones.length) {
  61937. this._animatables = [];
  61938. for (var index = 0; index < this.bones.length; index++) {
  61939. this._animatables.push(this.bones[index]);
  61940. }
  61941. }
  61942. return this._animatables;
  61943. };
  61944. Skeleton.prototype.clone = function (name, id) {
  61945. var result = new Skeleton(name, id || name, this._scene);
  61946. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61947. for (var index = 0; index < this.bones.length; index++) {
  61948. var source = this.bones[index];
  61949. var parentBone = null;
  61950. var parent_1 = source.getParent();
  61951. if (parent_1) {
  61952. var parentIndex = this.bones.indexOf(parent_1);
  61953. parentBone = result.bones[parentIndex];
  61954. }
  61955. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  61956. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  61957. }
  61958. if (this._ranges) {
  61959. result._ranges = {};
  61960. for (var rangeName in this._ranges) {
  61961. var range = this._ranges[rangeName];
  61962. if (range) {
  61963. result._ranges[rangeName] = range.clone();
  61964. }
  61965. }
  61966. }
  61967. this._isDirty = true;
  61968. return result;
  61969. };
  61970. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  61971. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  61972. this.bones.forEach(function (bone) {
  61973. bone.animations.forEach(function (animation) {
  61974. animation.enableBlending = true;
  61975. animation.blendingSpeed = blendingSpeed;
  61976. });
  61977. });
  61978. };
  61979. Skeleton.prototype.dispose = function () {
  61980. this._meshesWithPoseMatrix = [];
  61981. // Animations
  61982. this.getScene().stopAnimation(this);
  61983. // Remove from scene
  61984. this.getScene().removeSkeleton(this);
  61985. };
  61986. Skeleton.prototype.serialize = function () {
  61987. var serializationObject = {};
  61988. serializationObject.name = this.name;
  61989. serializationObject.id = this.id;
  61990. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  61991. serializationObject.bones = [];
  61992. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  61993. for (var index = 0; index < this.bones.length; index++) {
  61994. var bone = this.bones[index];
  61995. var parent_2 = bone.getParent();
  61996. var serializedBone = {
  61997. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  61998. name: bone.name,
  61999. matrix: bone.getBaseMatrix().toArray(),
  62000. rest: bone.getRestPose().toArray()
  62001. };
  62002. serializationObject.bones.push(serializedBone);
  62003. if (bone.length) {
  62004. serializedBone.length = bone.length;
  62005. }
  62006. if (bone.animations && bone.animations.length > 0) {
  62007. serializedBone.animation = bone.animations[0].serialize();
  62008. }
  62009. serializationObject.ranges = [];
  62010. for (var name in this._ranges) {
  62011. var source = this._ranges[name];
  62012. if (!source) {
  62013. continue;
  62014. }
  62015. var range = {};
  62016. range.name = name;
  62017. range.from = source.from;
  62018. range.to = source.to;
  62019. serializationObject.ranges.push(range);
  62020. }
  62021. }
  62022. return serializationObject;
  62023. };
  62024. Skeleton.Parse = function (parsedSkeleton, scene) {
  62025. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62026. if (parsedSkeleton.dimensionsAtRest) {
  62027. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62028. }
  62029. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62030. var index;
  62031. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62032. var parsedBone = parsedSkeleton.bones[index];
  62033. var parentBone = null;
  62034. if (parsedBone.parentBoneIndex > -1) {
  62035. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62036. }
  62037. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62038. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62039. if (parsedBone.length) {
  62040. bone.length = parsedBone.length;
  62041. }
  62042. if (parsedBone.animation) {
  62043. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62044. }
  62045. }
  62046. // placed after bones, so createAnimationRange can cascade down
  62047. if (parsedSkeleton.ranges) {
  62048. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62049. var data = parsedSkeleton.ranges[index];
  62050. skeleton.createAnimationRange(data.name, data.from, data.to);
  62051. }
  62052. }
  62053. return skeleton;
  62054. };
  62055. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62056. if (forceUpdate === void 0) { forceUpdate = false; }
  62057. var renderId = this._scene.getRenderId();
  62058. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62059. this.bones[0].computeAbsoluteTransforms();
  62060. this._lastAbsoluteTransformsUpdateId = renderId;
  62061. }
  62062. };
  62063. Skeleton.prototype.getPoseMatrix = function () {
  62064. var poseMatrix = null;
  62065. if (this._meshesWithPoseMatrix.length > 0) {
  62066. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62067. }
  62068. return poseMatrix;
  62069. };
  62070. Skeleton.prototype.sortBones = function () {
  62071. var bones = new Array();
  62072. var visited = new Array(this.bones.length);
  62073. for (var index = 0; index < this.bones.length; index++) {
  62074. this._sortBones(index, bones, visited);
  62075. }
  62076. this.bones = bones;
  62077. };
  62078. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62079. if (visited[index]) {
  62080. return;
  62081. }
  62082. visited[index] = true;
  62083. var bone = this.bones[index];
  62084. if (bone._index === undefined) {
  62085. bone._index = index;
  62086. }
  62087. var parentBone = bone.getParent();
  62088. if (parentBone) {
  62089. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62090. }
  62091. bones.push(bone);
  62092. };
  62093. return Skeleton;
  62094. }());
  62095. BABYLON.Skeleton = Skeleton;
  62096. })(BABYLON || (BABYLON = {}));
  62097. //# sourceMappingURL=babylon.skeleton.js.map
  62098. var BABYLON;
  62099. (function (BABYLON) {
  62100. var SphericalPolynomial = /** @class */ (function () {
  62101. function SphericalPolynomial() {
  62102. this.x = BABYLON.Vector3.Zero();
  62103. this.y = BABYLON.Vector3.Zero();
  62104. this.z = BABYLON.Vector3.Zero();
  62105. this.xx = BABYLON.Vector3.Zero();
  62106. this.yy = BABYLON.Vector3.Zero();
  62107. this.zz = BABYLON.Vector3.Zero();
  62108. this.xy = BABYLON.Vector3.Zero();
  62109. this.yz = BABYLON.Vector3.Zero();
  62110. this.zx = BABYLON.Vector3.Zero();
  62111. }
  62112. SphericalPolynomial.prototype.addAmbient = function (color) {
  62113. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62114. this.xx = this.xx.add(colorVector);
  62115. this.yy = this.yy.add(colorVector);
  62116. this.zz = this.zz.add(colorVector);
  62117. };
  62118. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62119. var result = new SphericalPolynomial();
  62120. result.x = harmonics.L11.scale(1.02333);
  62121. result.y = harmonics.L1_1.scale(1.02333);
  62122. result.z = harmonics.L10.scale(1.02333);
  62123. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62124. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62125. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62126. result.yz = harmonics.L2_1.scale(0.858086);
  62127. result.zx = harmonics.L21.scale(0.858086);
  62128. result.xy = harmonics.L2_2.scale(0.858086);
  62129. result.scale(1.0 / Math.PI);
  62130. return result;
  62131. };
  62132. SphericalPolynomial.prototype.scale = function (scale) {
  62133. this.x = this.x.scale(scale);
  62134. this.y = this.y.scale(scale);
  62135. this.z = this.z.scale(scale);
  62136. this.xx = this.xx.scale(scale);
  62137. this.yy = this.yy.scale(scale);
  62138. this.zz = this.zz.scale(scale);
  62139. this.yz = this.yz.scale(scale);
  62140. this.zx = this.zx.scale(scale);
  62141. this.xy = this.xy.scale(scale);
  62142. };
  62143. return SphericalPolynomial;
  62144. }());
  62145. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62146. var SphericalHarmonics = /** @class */ (function () {
  62147. function SphericalHarmonics() {
  62148. this.L00 = BABYLON.Vector3.Zero();
  62149. this.L1_1 = BABYLON.Vector3.Zero();
  62150. this.L10 = BABYLON.Vector3.Zero();
  62151. this.L11 = BABYLON.Vector3.Zero();
  62152. this.L2_2 = BABYLON.Vector3.Zero();
  62153. this.L2_1 = BABYLON.Vector3.Zero();
  62154. this.L20 = BABYLON.Vector3.Zero();
  62155. this.L21 = BABYLON.Vector3.Zero();
  62156. this.L22 = BABYLON.Vector3.Zero();
  62157. }
  62158. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62159. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62160. var c = colorVector.scale(deltaSolidAngle);
  62161. this.L00 = this.L00.add(c.scale(0.282095));
  62162. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62163. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62164. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62165. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62166. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62167. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62168. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62169. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62170. };
  62171. SphericalHarmonics.prototype.scale = function (scale) {
  62172. this.L00 = this.L00.scale(scale);
  62173. this.L1_1 = this.L1_1.scale(scale);
  62174. this.L10 = this.L10.scale(scale);
  62175. this.L11 = this.L11.scale(scale);
  62176. this.L2_2 = this.L2_2.scale(scale);
  62177. this.L2_1 = this.L2_1.scale(scale);
  62178. this.L20 = this.L20.scale(scale);
  62179. this.L21 = this.L21.scale(scale);
  62180. this.L22 = this.L22.scale(scale);
  62181. };
  62182. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62183. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62184. //
  62185. // E_lm = A_l * L_lm
  62186. //
  62187. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62188. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62189. // the scaling factors are given in equation 9.
  62190. // Constant (Band 0)
  62191. this.L00 = this.L00.scale(3.141593);
  62192. // Linear (Band 1)
  62193. this.L1_1 = this.L1_1.scale(2.094395);
  62194. this.L10 = this.L10.scale(2.094395);
  62195. this.L11 = this.L11.scale(2.094395);
  62196. // Quadratic (Band 2)
  62197. this.L2_2 = this.L2_2.scale(0.785398);
  62198. this.L2_1 = this.L2_1.scale(0.785398);
  62199. this.L20 = this.L20.scale(0.785398);
  62200. this.L21 = this.L21.scale(0.785398);
  62201. this.L22 = this.L22.scale(0.785398);
  62202. };
  62203. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62204. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62205. // L = (1/pi) * E * rho
  62206. //
  62207. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62208. this.scale(1.0 / Math.PI);
  62209. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62210. // (The pixel shader must apply albedo after texture fetches, etc).
  62211. };
  62212. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62213. var result = new SphericalHarmonics();
  62214. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62215. result.L1_1 = polynomial.y.scale(0.977204);
  62216. result.L10 = polynomial.z.scale(0.977204);
  62217. result.L11 = polynomial.x.scale(0.977204);
  62218. result.L2_2 = polynomial.xy.scale(1.16538);
  62219. result.L2_1 = polynomial.yz.scale(1.16538);
  62220. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62221. result.L21 = polynomial.zx.scale(1.16538);
  62222. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62223. result.scale(Math.PI);
  62224. return result;
  62225. };
  62226. return SphericalHarmonics;
  62227. }());
  62228. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62229. })(BABYLON || (BABYLON = {}));
  62230. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62231. var BABYLON;
  62232. (function (BABYLON) {
  62233. var Internals;
  62234. (function (Internals) {
  62235. var FileFaceOrientation = /** @class */ (function () {
  62236. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62237. this.name = name;
  62238. this.worldAxisForNormal = worldAxisForNormal;
  62239. this.worldAxisForFileX = worldAxisForFileX;
  62240. this.worldAxisForFileY = worldAxisForFileY;
  62241. }
  62242. return FileFaceOrientation;
  62243. }());
  62244. ;
  62245. /**
  62246. * Helper class dealing with the extraction of spherical polynomial dataArray
  62247. * from a cube map.
  62248. */
  62249. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62250. function CubeMapToSphericalPolynomialTools() {
  62251. }
  62252. /**
  62253. * Converts a texture to the according Spherical Polynomial data.
  62254. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62255. *
  62256. * @param texture The texture to extract the information from.
  62257. * @return The Spherical Polynomial data.
  62258. */
  62259. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62260. if (!texture.isCube) {
  62261. // Only supports cube Textures currently.
  62262. return null;
  62263. }
  62264. var size = texture.getSize().width;
  62265. var right = texture.readPixels(0);
  62266. var left = texture.readPixels(1);
  62267. var up;
  62268. var down;
  62269. if (texture.isRenderTarget) {
  62270. up = texture.readPixels(3);
  62271. down = texture.readPixels(2);
  62272. }
  62273. else {
  62274. up = texture.readPixels(2);
  62275. down = texture.readPixels(3);
  62276. }
  62277. var front = texture.readPixels(4);
  62278. var back = texture.readPixels(5);
  62279. var gammaSpace = texture.gammaSpace;
  62280. // Always read as RGBA.
  62281. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62282. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62283. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62284. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62285. }
  62286. var cubeInfo = {
  62287. size: size,
  62288. right: right,
  62289. left: left,
  62290. up: up,
  62291. down: down,
  62292. front: front,
  62293. back: back,
  62294. format: format,
  62295. type: type,
  62296. gammaSpace: gammaSpace,
  62297. };
  62298. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62299. };
  62300. /**
  62301. * Converts a cubemap to the according Spherical Polynomial data.
  62302. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62303. *
  62304. * @param cubeInfo The Cube map to extract the information from.
  62305. * @return The Spherical Polynomial data.
  62306. */
  62307. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62308. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62309. var totalSolidAngle = 0.0;
  62310. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62311. var du = 2.0 / cubeInfo.size;
  62312. var dv = du;
  62313. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62314. var minUV = du * 0.5 - 1.0;
  62315. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62316. var fileFace = this.FileFaces[faceIndex];
  62317. var dataArray = cubeInfo[fileFace.name];
  62318. var v = minUV;
  62319. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62320. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62321. // Because SP is still linear, so summation is fine in that basis.
  62322. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62323. for (var y = 0; y < cubeInfo.size; y++) {
  62324. var u = minUV;
  62325. for (var x = 0; x < cubeInfo.size; x++) {
  62326. // World direction (not normalised)
  62327. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62328. worldDirection.normalize();
  62329. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62330. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62331. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62332. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62333. // Handle Integer types.
  62334. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62335. r /= 255;
  62336. g /= 255;
  62337. b /= 255;
  62338. }
  62339. // Handle Gamma space textures.
  62340. if (cubeInfo.gammaSpace) {
  62341. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62342. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62343. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62344. }
  62345. var color = new BABYLON.Color3(r, g, b);
  62346. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62347. totalSolidAngle += deltaSolidAngle;
  62348. u += du;
  62349. }
  62350. v += dv;
  62351. }
  62352. }
  62353. // Solid angle for entire sphere is 4*pi
  62354. var sphereSolidAngle = 4.0 * Math.PI;
  62355. // Adjust the solid angle to allow for how many faces we processed.
  62356. var facesProcessed = 6.0;
  62357. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62358. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62359. // This is needed because the numerical integration over the cube uses a
  62360. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62361. // and also to compensate for accumulative error due to float precision in the summation.
  62362. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62363. sphericalHarmonics.scale(correctionFactor);
  62364. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62365. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62366. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62367. };
  62368. CubeMapToSphericalPolynomialTools.FileFaces = [
  62369. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62370. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62371. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62372. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62373. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62374. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62375. ];
  62376. return CubeMapToSphericalPolynomialTools;
  62377. }());
  62378. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62379. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62380. })(BABYLON || (BABYLON = {}));
  62381. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62382. var BABYLON;
  62383. (function (BABYLON) {
  62384. var Internals;
  62385. (function (Internals) {
  62386. /**
  62387. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62388. */
  62389. var PanoramaToCubeMapTools = /** @class */ (function () {
  62390. function PanoramaToCubeMapTools() {
  62391. }
  62392. /**
  62393. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62394. *
  62395. * @param float32Array The source data.
  62396. * @param inputWidth The width of the input panorama.
  62397. * @param inputhHeight The height of the input panorama.
  62398. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62399. * @return The cubemap data
  62400. */
  62401. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62402. if (!float32Array) {
  62403. throw "ConvertPanoramaToCubemap: input cannot be null";
  62404. }
  62405. if (float32Array.length != inputWidth * inputHeight * 3) {
  62406. throw "ConvertPanoramaToCubemap: input size is wrong";
  62407. }
  62408. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62409. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62410. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62411. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62412. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62413. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62414. return {
  62415. front: textureFront,
  62416. back: textureBack,
  62417. left: textureLeft,
  62418. right: textureRight,
  62419. up: textureUp,
  62420. down: textureDown,
  62421. size: size,
  62422. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62423. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62424. gammaSpace: false,
  62425. };
  62426. };
  62427. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62428. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62429. var textureArray = new Float32Array(buffer);
  62430. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62431. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62432. var dy = 1 / texSize;
  62433. var fy = 0;
  62434. for (var y = 0; y < texSize; y++) {
  62435. var xv1 = faceData[0];
  62436. var xv2 = faceData[2];
  62437. for (var x = 0; x < texSize; x++) {
  62438. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62439. v.normalize();
  62440. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62441. // 3 channels per pixels
  62442. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62443. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62444. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62445. xv1 = xv1.add(rotDX1);
  62446. xv2 = xv2.add(rotDX2);
  62447. }
  62448. fy += dy;
  62449. }
  62450. return textureArray;
  62451. };
  62452. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62453. var theta = Math.atan2(vDir.z, vDir.x);
  62454. var phi = Math.acos(vDir.y);
  62455. while (theta < -Math.PI)
  62456. theta += 2 * Math.PI;
  62457. while (theta > Math.PI)
  62458. theta -= 2 * Math.PI;
  62459. var dx = theta / Math.PI;
  62460. var dy = phi / Math.PI;
  62461. // recenter.
  62462. dx = dx * 0.5 + 0.5;
  62463. var px = Math.round(dx * inputWidth);
  62464. if (px < 0)
  62465. px = 0;
  62466. else if (px >= inputWidth)
  62467. px = inputWidth - 1;
  62468. var py = Math.round(dy * inputHeight);
  62469. if (py < 0)
  62470. py = 0;
  62471. else if (py >= inputHeight)
  62472. py = inputHeight - 1;
  62473. var inputY = (inputHeight - py - 1);
  62474. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62475. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62476. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62477. return {
  62478. r: r,
  62479. g: g,
  62480. b: b
  62481. };
  62482. };
  62483. PanoramaToCubeMapTools.FACE_FRONT = [
  62484. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62485. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62486. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62487. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62488. ];
  62489. PanoramaToCubeMapTools.FACE_BACK = [
  62490. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62491. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62492. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62493. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62494. ];
  62495. PanoramaToCubeMapTools.FACE_RIGHT = [
  62496. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62497. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62498. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62499. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62500. ];
  62501. PanoramaToCubeMapTools.FACE_LEFT = [
  62502. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62503. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62504. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62505. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62506. ];
  62507. PanoramaToCubeMapTools.FACE_DOWN = [
  62508. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62509. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62510. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62511. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62512. ];
  62513. PanoramaToCubeMapTools.FACE_UP = [
  62514. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62515. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62516. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62517. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62518. ];
  62519. return PanoramaToCubeMapTools;
  62520. }());
  62521. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62522. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62523. })(BABYLON || (BABYLON = {}));
  62524. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62525. var BABYLON;
  62526. (function (BABYLON) {
  62527. var Internals;
  62528. (function (Internals) {
  62529. ;
  62530. /**
  62531. * This groups tools to convert HDR texture to native colors array.
  62532. */
  62533. var HDRTools = /** @class */ (function () {
  62534. function HDRTools() {
  62535. }
  62536. HDRTools.Ldexp = function (mantissa, exponent) {
  62537. if (exponent > 1023) {
  62538. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62539. }
  62540. if (exponent < -1074) {
  62541. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62542. }
  62543. return mantissa * Math.pow(2, exponent);
  62544. };
  62545. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62546. if (exponent > 0) {
  62547. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62548. float32array[index + 0] = red * exponent;
  62549. float32array[index + 1] = green * exponent;
  62550. float32array[index + 2] = blue * exponent;
  62551. }
  62552. else {
  62553. float32array[index + 0] = 0;
  62554. float32array[index + 1] = 0;
  62555. float32array[index + 2] = 0;
  62556. }
  62557. };
  62558. HDRTools.readStringLine = function (uint8array, startIndex) {
  62559. var line = "";
  62560. var character = "";
  62561. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62562. character = String.fromCharCode(uint8array[i]);
  62563. if (character == "\n") {
  62564. break;
  62565. }
  62566. line += character;
  62567. }
  62568. return line;
  62569. };
  62570. /**
  62571. * Reads header information from an RGBE texture stored in a native array.
  62572. * More information on this format are available here:
  62573. * https://en.wikipedia.org/wiki/RGBE_image_format
  62574. *
  62575. * @param uint8array The binary file stored in native array.
  62576. * @return The header information.
  62577. */
  62578. HDRTools.RGBE_ReadHeader = function (uint8array) {
  62579. var height = 0;
  62580. var width = 0;
  62581. var line = this.readStringLine(uint8array, 0);
  62582. if (line[0] != '#' || line[1] != '?') {
  62583. throw "Bad HDR Format.";
  62584. }
  62585. var endOfHeader = false;
  62586. var findFormat = false;
  62587. var lineIndex = 0;
  62588. do {
  62589. lineIndex += (line.length + 1);
  62590. line = this.readStringLine(uint8array, lineIndex);
  62591. if (line == "FORMAT=32-bit_rle_rgbe") {
  62592. findFormat = true;
  62593. }
  62594. else if (line.length == 0) {
  62595. endOfHeader = true;
  62596. }
  62597. } while (!endOfHeader);
  62598. if (!findFormat) {
  62599. throw "HDR Bad header format, unsupported FORMAT";
  62600. }
  62601. lineIndex += (line.length + 1);
  62602. line = this.readStringLine(uint8array, lineIndex);
  62603. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  62604. var match = sizeRegexp.exec(line);
  62605. // TODO. Support +Y and -X if needed.
  62606. if (!match || match.length < 3) {
  62607. throw "HDR Bad header format, no size";
  62608. }
  62609. width = parseInt(match[2]);
  62610. height = parseInt(match[1]);
  62611. if (width < 8 || width > 0x7fff) {
  62612. throw "HDR Bad header format, unsupported size";
  62613. }
  62614. lineIndex += (line.length + 1);
  62615. return {
  62616. height: height,
  62617. width: width,
  62618. dataPosition: lineIndex
  62619. };
  62620. };
  62621. /**
  62622. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  62623. * This RGBE texture needs to store the information as a panorama.
  62624. *
  62625. * More information on this format are available here:
  62626. * https://en.wikipedia.org/wiki/RGBE_image_format
  62627. *
  62628. * @param buffer The binary file stored in an array buffer.
  62629. * @param size The expected size of the extracted cubemap.
  62630. * @return The Cube Map information.
  62631. */
  62632. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  62633. var uint8array = new Uint8Array(buffer);
  62634. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  62635. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62636. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  62637. return cubeMapData;
  62638. };
  62639. /**
  62640. * Returns the pixels data extracted from an RGBE texture.
  62641. * This pixels will be stored left to right up to down in the R G B order in one array.
  62642. *
  62643. * More information on this format are available here:
  62644. * https://en.wikipedia.org/wiki/RGBE_image_format
  62645. *
  62646. * @param uint8array The binary file stored in an array buffer.
  62647. * @param hdrInfo The header information of the file.
  62648. * @return The pixels data in RGB right to left up to down order.
  62649. */
  62650. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  62651. // Keep for multi format supports.
  62652. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  62653. };
  62654. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  62655. var num_scanlines = hdrInfo.height;
  62656. var scanline_width = hdrInfo.width;
  62657. var a, b, c, d, count;
  62658. var dataIndex = hdrInfo.dataPosition;
  62659. var index = 0, endIndex = 0, i = 0;
  62660. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  62661. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  62662. // 3 channels of 4 bytes per pixel in float.
  62663. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  62664. var resultArray = new Float32Array(resultBuffer);
  62665. // read in each successive scanline
  62666. while (num_scanlines > 0) {
  62667. a = uint8array[dataIndex++];
  62668. b = uint8array[dataIndex++];
  62669. c = uint8array[dataIndex++];
  62670. d = uint8array[dataIndex++];
  62671. if (a != 2 || b != 2 || (c & 0x80)) {
  62672. // this file is not run length encoded
  62673. throw "HDR Bad header format, not RLE";
  62674. }
  62675. if (((c << 8) | d) != scanline_width) {
  62676. throw "HDR Bad header format, wrong scan line width";
  62677. }
  62678. index = 0;
  62679. // read each of the four channels for the scanline into the buffer
  62680. for (i = 0; i < 4; i++) {
  62681. endIndex = (i + 1) * scanline_width;
  62682. while (index < endIndex) {
  62683. a = uint8array[dataIndex++];
  62684. b = uint8array[dataIndex++];
  62685. if (a > 128) {
  62686. // a run of the same value
  62687. count = a - 128;
  62688. if ((count == 0) || (count > endIndex - index)) {
  62689. throw "HDR Bad Format, bad scanline data (run)";
  62690. }
  62691. while (count-- > 0) {
  62692. scanLineArray[index++] = b;
  62693. }
  62694. }
  62695. else {
  62696. // a non-run
  62697. count = a;
  62698. if ((count == 0) || (count > endIndex - index)) {
  62699. throw "HDR Bad Format, bad scanline data (non-run)";
  62700. }
  62701. scanLineArray[index++] = b;
  62702. if (--count > 0) {
  62703. for (var j = 0; j < count; j++) {
  62704. scanLineArray[index++] = uint8array[dataIndex++];
  62705. }
  62706. }
  62707. }
  62708. }
  62709. }
  62710. // now convert data from buffer into floats
  62711. for (i = 0; i < scanline_width; i++) {
  62712. a = scanLineArray[i];
  62713. b = scanLineArray[i + scanline_width];
  62714. c = scanLineArray[i + 2 * scanline_width];
  62715. d = scanLineArray[i + 3 * scanline_width];
  62716. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  62717. }
  62718. num_scanlines--;
  62719. }
  62720. return resultArray;
  62721. };
  62722. return HDRTools;
  62723. }());
  62724. Internals.HDRTools = HDRTools;
  62725. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62726. })(BABYLON || (BABYLON = {}));
  62727. //# sourceMappingURL=babylon.hdr.js.map
  62728. var BABYLON;
  62729. (function (BABYLON) {
  62730. /**
  62731. * This represents a texture coming from an HDR input.
  62732. *
  62733. * The only supported format is currently panorama picture stored in RGBE format.
  62734. * Example of such files can be found on HDRLib: http://hdrlib.com/
  62735. */
  62736. var HDRCubeTexture = /** @class */ (function (_super) {
  62737. __extends(HDRCubeTexture, _super);
  62738. /**
  62739. * Instantiates an HDRTexture from the following parameters.
  62740. *
  62741. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  62742. * @param scene The scene the texture will be used in
  62743. * @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.
  62744. * @param noMipmap Forces to not generate the mipmap if true
  62745. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  62746. * @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)
  62747. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  62748. */
  62749. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  62750. if (noMipmap === void 0) { noMipmap = false; }
  62751. if (generateHarmonics === void 0) { generateHarmonics = true; }
  62752. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  62753. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  62754. if (onLoad === void 0) { onLoad = null; }
  62755. if (onError === void 0) { onError = null; }
  62756. var _this = _super.call(this, scene) || this;
  62757. _this._useInGammaSpace = false;
  62758. _this._generateHarmonics = true;
  62759. _this._isBABYLONPreprocessed = false;
  62760. _this._onLoad = null;
  62761. _this._onError = null;
  62762. /**
  62763. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  62764. */
  62765. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62766. /**
  62767. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  62768. * This is usefull at run time to apply the good shader.
  62769. */
  62770. _this.isPMREM = false;
  62771. _this._isBlocking = true;
  62772. if (!url) {
  62773. return _this;
  62774. }
  62775. _this.name = url;
  62776. _this.url = url;
  62777. _this.hasAlpha = false;
  62778. _this.isCube = true;
  62779. _this._textureMatrix = BABYLON.Matrix.Identity();
  62780. _this._onLoad = onLoad;
  62781. _this._onError = onError;
  62782. _this.gammaSpace = false;
  62783. var caps = scene.getEngine().getCaps();
  62784. if (size) {
  62785. _this._isBABYLONPreprocessed = false;
  62786. _this._noMipmap = noMipmap;
  62787. _this._size = size;
  62788. _this._useInGammaSpace = useInGammaSpace;
  62789. _this._usePMREMGenerator = usePMREMGenerator &&
  62790. caps.textureLOD &&
  62791. caps.textureFloat &&
  62792. !_this._useInGammaSpace;
  62793. }
  62794. else {
  62795. _this._isBABYLONPreprocessed = true;
  62796. _this._noMipmap = false;
  62797. _this._useInGammaSpace = false;
  62798. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  62799. !_this._useInGammaSpace;
  62800. }
  62801. _this.isPMREM = _this._usePMREMGenerator;
  62802. _this._texture = _this._getFromCache(url, _this._noMipmap);
  62803. if (!_this._texture) {
  62804. if (!scene.useDelayedTextureLoading) {
  62805. _this.loadTexture();
  62806. }
  62807. else {
  62808. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62809. }
  62810. }
  62811. return _this;
  62812. }
  62813. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  62814. /**
  62815. * Gets wether or not the texture is blocking during loading.
  62816. */
  62817. get: function () {
  62818. return this._isBlocking;
  62819. },
  62820. /**
  62821. * Sets wether or not the texture is blocking during loading.
  62822. */
  62823. set: function (value) {
  62824. this._isBlocking = value;
  62825. },
  62826. enumerable: true,
  62827. configurable: true
  62828. });
  62829. /**
  62830. * Occurs when the file is a preprocessed .babylon.hdr file.
  62831. */
  62832. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  62833. var _this = this;
  62834. var mipLevels = 0;
  62835. var floatArrayView = null;
  62836. var scene = this.getScene();
  62837. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  62838. var mips = new Array();
  62839. if (!floatArrayView) {
  62840. return mips;
  62841. }
  62842. var startIndex = 30;
  62843. for (var level = 0; level < mipLevels; level++) {
  62844. mips.push([]);
  62845. // Fill each pixel of the mip level.
  62846. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  62847. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62848. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  62849. mips[level].push(faceData);
  62850. startIndex += faceSize;
  62851. }
  62852. }
  62853. return mips;
  62854. } : null;
  62855. var callback = function (buffer) {
  62856. var scene = _this.getScene();
  62857. if (!scene) {
  62858. return null;
  62859. }
  62860. // Create Native Array Views
  62861. var intArrayView = new Int32Array(buffer);
  62862. floatArrayView = new Float32Array(buffer);
  62863. // Fill header.
  62864. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  62865. _this._size = intArrayView[1]; // CubeMap max mip face size.
  62866. // Update Texture Information.
  62867. if (!_this._texture) {
  62868. return null;
  62869. }
  62870. _this._texture.updateSize(_this._size, _this._size);
  62871. // Fill polynomial information.
  62872. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  62873. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  62874. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  62875. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  62876. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  62877. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  62878. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  62879. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  62880. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  62881. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  62882. _this.sphericalPolynomial = sphericalPolynomial;
  62883. // Fill pixel data.
  62884. mipLevels = intArrayView[29]; // Number of mip levels.
  62885. var startIndex = 30;
  62886. var data = [];
  62887. var faceSize = Math.pow(_this._size, 2) * 3;
  62888. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62889. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  62890. startIndex += faceSize;
  62891. }
  62892. var results = [];
  62893. var byteArray = null;
  62894. // Push each faces.
  62895. for (var k = 0; k < 6; k++) {
  62896. var dataFace = null;
  62897. // To be deprecated.
  62898. if (version === 1) {
  62899. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  62900. dataFace = data[j];
  62901. }
  62902. // If special cases.
  62903. if (!mipmapGenerator && dataFace) {
  62904. if (!scene.getEngine().getCaps().textureFloat) {
  62905. // 3 channels of 1 bytes per pixel in bytes.
  62906. var byteBuffer = new ArrayBuffer(faceSize);
  62907. byteArray = new Uint8Array(byteBuffer);
  62908. }
  62909. for (var i = 0; i < _this._size * _this._size; i++) {
  62910. // Put in gamma space if requested.
  62911. if (_this._useInGammaSpace) {
  62912. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62913. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62914. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62915. }
  62916. // Convert to int texture for fallback.
  62917. if (byteArray) {
  62918. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62919. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62920. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62921. // May use luminance instead if the result is not accurate.
  62922. var max = Math.max(Math.max(r, g), b);
  62923. if (max > 255) {
  62924. var scale = 255 / max;
  62925. r *= scale;
  62926. g *= scale;
  62927. b *= scale;
  62928. }
  62929. byteArray[(i * 3) + 0] = r;
  62930. byteArray[(i * 3) + 1] = g;
  62931. byteArray[(i * 3) + 2] = b;
  62932. }
  62933. }
  62934. }
  62935. // Fill the array accordingly.
  62936. if (byteArray) {
  62937. results.push(byteArray);
  62938. }
  62939. else {
  62940. results.push(dataFace);
  62941. }
  62942. }
  62943. return results;
  62944. };
  62945. if (scene) {
  62946. 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);
  62947. }
  62948. };
  62949. /**
  62950. * Occurs when the file is raw .hdr file.
  62951. */
  62952. HDRCubeTexture.prototype.loadHDRTexture = function () {
  62953. var _this = this;
  62954. var callback = function (buffer) {
  62955. var scene = _this.getScene();
  62956. if (!scene) {
  62957. return null;
  62958. }
  62959. // Extract the raw linear data.
  62960. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  62961. // Generate harmonics if needed.
  62962. if (_this._generateHarmonics) {
  62963. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  62964. _this.sphericalPolynomial = sphericalPolynomial;
  62965. }
  62966. var results = [];
  62967. var byteArray = null;
  62968. // Push each faces.
  62969. for (var j = 0; j < 6; j++) {
  62970. // Create uintarray fallback.
  62971. if (!scene.getEngine().getCaps().textureFloat) {
  62972. // 3 channels of 1 bytes per pixel in bytes.
  62973. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  62974. byteArray = new Uint8Array(byteBuffer);
  62975. }
  62976. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  62977. // If special cases.
  62978. if (_this._useInGammaSpace || byteArray) {
  62979. for (var i = 0; i < _this._size * _this._size; i++) {
  62980. // Put in gamma space if requested.
  62981. if (_this._useInGammaSpace) {
  62982. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  62983. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  62984. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  62985. }
  62986. // Convert to int texture for fallback.
  62987. if (byteArray) {
  62988. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  62989. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  62990. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  62991. // May use luminance instead if the result is not accurate.
  62992. var max = Math.max(Math.max(r, g), b);
  62993. if (max > 255) {
  62994. var scale = 255 / max;
  62995. r *= scale;
  62996. g *= scale;
  62997. b *= scale;
  62998. }
  62999. byteArray[(i * 3) + 0] = r;
  63000. byteArray[(i * 3) + 1] = g;
  63001. byteArray[(i * 3) + 2] = b;
  63002. }
  63003. }
  63004. }
  63005. if (byteArray) {
  63006. results.push(byteArray);
  63007. }
  63008. else {
  63009. results.push(dataFace);
  63010. }
  63011. }
  63012. return results;
  63013. };
  63014. var mipmapGenerator = null;
  63015. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63016. // if (!this._noMipmap &&
  63017. // this._usePMREMGenerator) {
  63018. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63019. // // Custom setup of the generator matching with the PBR shader values.
  63020. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63021. // this._size,
  63022. // this._size,
  63023. // 0,
  63024. // 3,
  63025. // this.getScene().getEngine().getCaps().textureFloat,
  63026. // 2048,
  63027. // 0.25,
  63028. // false,
  63029. // true);
  63030. // return generator.filterCubeMap();
  63031. // };
  63032. // }
  63033. var scene = this.getScene();
  63034. if (scene) {
  63035. 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);
  63036. }
  63037. };
  63038. /**
  63039. * Starts the loading process of the texture.
  63040. */
  63041. HDRCubeTexture.prototype.loadTexture = function () {
  63042. if (this._isBABYLONPreprocessed) {
  63043. this.loadBabylonTexture();
  63044. }
  63045. else {
  63046. this.loadHDRTexture();
  63047. }
  63048. };
  63049. HDRCubeTexture.prototype.clone = function () {
  63050. var scene = this.getScene();
  63051. if (!scene) {
  63052. return this;
  63053. }
  63054. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63055. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63056. // Base texture
  63057. newTexture.level = this.level;
  63058. newTexture.wrapU = this.wrapU;
  63059. newTexture.wrapV = this.wrapV;
  63060. newTexture.coordinatesIndex = this.coordinatesIndex;
  63061. newTexture.coordinatesMode = this.coordinatesMode;
  63062. return newTexture;
  63063. };
  63064. // Methods
  63065. HDRCubeTexture.prototype.delayLoad = function () {
  63066. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63067. return;
  63068. }
  63069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63070. this._texture = this._getFromCache(this.url, this._noMipmap);
  63071. if (!this._texture) {
  63072. this.loadTexture();
  63073. }
  63074. };
  63075. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63076. return this._textureMatrix;
  63077. };
  63078. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63079. this._textureMatrix = value;
  63080. };
  63081. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63082. var texture = null;
  63083. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63084. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63085. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63086. texture.name = parsedTexture.name;
  63087. texture.hasAlpha = parsedTexture.hasAlpha;
  63088. texture.level = parsedTexture.level;
  63089. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63090. texture.isBlocking = parsedTexture.isBlocking;
  63091. }
  63092. return texture;
  63093. };
  63094. HDRCubeTexture.prototype.serialize = function () {
  63095. if (!this.name) {
  63096. return null;
  63097. }
  63098. var serializationObject = {};
  63099. serializationObject.name = this.name;
  63100. serializationObject.hasAlpha = this.hasAlpha;
  63101. serializationObject.isCube = true;
  63102. serializationObject.level = this.level;
  63103. serializationObject.size = this._size;
  63104. serializationObject.coordinatesMode = this.coordinatesMode;
  63105. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63106. serializationObject.generateHarmonics = this._generateHarmonics;
  63107. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63108. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63109. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63110. serializationObject.noMipmap = this._noMipmap;
  63111. serializationObject.isBlocking = this._isBlocking;
  63112. return serializationObject;
  63113. };
  63114. /**
  63115. * Saves as a file the data contained in the texture in a binary format.
  63116. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63117. * as the spherical used in the lighting.
  63118. * @param url The HDR file url.
  63119. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63120. * @param onError Method called if any error happens during download.
  63121. * @return The packed binary data.
  63122. */
  63123. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63124. if (onError === void 0) { onError = null; }
  63125. var callback = function (buffer) {
  63126. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63127. // Returns a URL you can use as a href.
  63128. var objUrl = window.URL.createObjectURL(data);
  63129. // Simulates a link to it and click to dowload.
  63130. var a = document.createElement("a");
  63131. document.body.appendChild(a);
  63132. a.style.display = "none";
  63133. a.href = objUrl;
  63134. a.download = "envmap.babylon.hdr";
  63135. a.click();
  63136. };
  63137. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63138. };
  63139. /**
  63140. * Serializes the data contained in the texture in a binary format.
  63141. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63142. * as the spherical used in the lighting.
  63143. * @param url The HDR file url.
  63144. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63145. * @param onError Method called if any error happens during download.
  63146. * @return The packed binary data.
  63147. */
  63148. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63149. if (onError === void 0) { onError = null; }
  63150. // Needs the url tho create the texture.
  63151. if (!url) {
  63152. return;
  63153. }
  63154. // Check Power of two size.
  63155. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63156. return;
  63157. }
  63158. // Coming Back in 3.x.
  63159. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63160. };
  63161. HDRCubeTexture._facesMapping = [
  63162. "right",
  63163. "left",
  63164. "up",
  63165. "down",
  63166. "front",
  63167. "back"
  63168. ];
  63169. return HDRCubeTexture;
  63170. }(BABYLON.BaseTexture));
  63171. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63172. })(BABYLON || (BABYLON = {}));
  63173. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63174. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63175. // Huge respect for a such great lib.
  63176. // Earcut license:
  63177. // Copyright (c) 2016, Mapbox
  63178. //
  63179. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63180. // with or without fee is hereby granted, provided that the above copyright notice
  63181. // and this permission notice appear in all copies.
  63182. //
  63183. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63184. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63185. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63186. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63187. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63188. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63189. // THIS SOFTWARE.
  63190. var Earcut;
  63191. (function (Earcut) {
  63192. /**
  63193. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63194. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63195. * @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).
  63196. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63197. */
  63198. function earcut(data, holeIndices, dim) {
  63199. dim = dim || 2;
  63200. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63201. if (!outerNode)
  63202. return triangles;
  63203. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63204. if (hasHoles)
  63205. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63206. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63207. if (data.length > 80 * dim) {
  63208. minX = maxX = data[0];
  63209. minY = maxY = data[1];
  63210. for (var i = dim; i < outerLen; i += dim) {
  63211. x = data[i];
  63212. y = data[i + 1];
  63213. if (x < minX)
  63214. minX = x;
  63215. if (y < minY)
  63216. minY = y;
  63217. if (x > maxX)
  63218. maxX = x;
  63219. if (y > maxY)
  63220. maxY = y;
  63221. }
  63222. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63223. size = Math.max(maxX - minX, maxY - minY);
  63224. }
  63225. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63226. return triangles;
  63227. }
  63228. Earcut.earcut = earcut;
  63229. var Node = /** @class */ (function () {
  63230. function Node(i, x, y) {
  63231. this.i = i;
  63232. this.x = x;
  63233. this.y = y;
  63234. this.prev = null;
  63235. this.next = null;
  63236. this.z = null;
  63237. this.prevZ = null;
  63238. this.nextZ = null;
  63239. this.steiner = false;
  63240. }
  63241. return Node;
  63242. }());
  63243. // create a circular doubly linked list from polygon points in the specified winding order
  63244. function linkedList(data, start, end, dim, clockwise) {
  63245. var i, last = null;
  63246. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63247. for (i = start; i < end; i += dim)
  63248. last = insertNode(i, data[i], data[i + 1], last);
  63249. }
  63250. else {
  63251. for (i = end - dim; i >= start; i -= dim)
  63252. last = insertNode(i, data[i], data[i + 1], last);
  63253. }
  63254. if (last && equals(last, last.next)) {
  63255. removeNode(last);
  63256. last = last.next;
  63257. }
  63258. return last;
  63259. }
  63260. // eliminate colinear or duplicate points
  63261. function filterPoints(start, end) {
  63262. if (!start)
  63263. return start;
  63264. if (!end)
  63265. end = start;
  63266. var p = start, again;
  63267. do {
  63268. again = false;
  63269. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63270. removeNode(p);
  63271. p = end = p.prev;
  63272. if (p === p.next)
  63273. return undefined;
  63274. again = true;
  63275. }
  63276. else {
  63277. p = p.next;
  63278. }
  63279. } while (again || p !== end);
  63280. return end;
  63281. }
  63282. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63283. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63284. if (!ear)
  63285. return;
  63286. // interlink polygon nodes in z-order
  63287. if (!pass && size)
  63288. indexCurve(ear, minX, minY, size);
  63289. var stop = ear, prev, next;
  63290. // iterate through ears, slicing them one by one
  63291. while (ear.prev !== ear.next) {
  63292. prev = ear.prev;
  63293. next = ear.next;
  63294. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63295. // cut off the triangle
  63296. triangles.push(prev.i / dim);
  63297. triangles.push(ear.i / dim);
  63298. triangles.push(next.i / dim);
  63299. removeNode(ear);
  63300. // skipping the next vertice leads to less sliver triangles
  63301. ear = next.next;
  63302. stop = next.next;
  63303. continue;
  63304. }
  63305. ear = next;
  63306. // if we looped through the whole remaining polygon and can't find any more ears
  63307. if (ear === stop) {
  63308. // try filtering points and slicing again
  63309. if (!pass) {
  63310. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63311. // if this didn't work, try curing all small self-intersections locally
  63312. }
  63313. else if (pass === 1) {
  63314. ear = cureLocalIntersections(ear, triangles, dim);
  63315. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63316. // as a last resort, try splitting the remaining polygon into two
  63317. }
  63318. else if (pass === 2) {
  63319. splitEarcut(ear, triangles, dim, minX, minY, size);
  63320. }
  63321. break;
  63322. }
  63323. }
  63324. }
  63325. // check whether a polygon node forms a valid ear with adjacent nodes
  63326. function isEar(ear) {
  63327. var a = ear.prev, b = ear, c = ear.next;
  63328. if (area(a, b, c) >= 0)
  63329. return false; // reflex, can't be an ear
  63330. // now make sure we don't have other points inside the potential ear
  63331. var p = ear.next.next;
  63332. while (p !== ear.prev) {
  63333. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63334. area(p.prev, p, p.next) >= 0)
  63335. return false;
  63336. p = p.next;
  63337. }
  63338. return true;
  63339. }
  63340. function isEarHashed(ear, minX, minY, size) {
  63341. var a = ear.prev, b = ear, c = ear.next;
  63342. if (area(a, b, c) >= 0)
  63343. return false; // reflex, can't be an ear
  63344. // triangle bbox; min & max are calculated like this for speed
  63345. 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);
  63346. // z-order range for the current triangle bbox;
  63347. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63348. // first look for points inside the triangle in increasing z-order
  63349. var p = ear.nextZ;
  63350. while (p && p.z <= maxZ) {
  63351. if (p !== ear.prev &&
  63352. p !== ear.next &&
  63353. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63354. area(p.prev, p, p.next) >= 0)
  63355. return false;
  63356. p = p.nextZ;
  63357. }
  63358. // then look for points in decreasing z-order
  63359. p = ear.prevZ;
  63360. while (p && p.z >= minZ) {
  63361. if (p !== ear.prev &&
  63362. p !== ear.next &&
  63363. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63364. area(p.prev, p, p.next) >= 0)
  63365. return false;
  63366. p = p.prevZ;
  63367. }
  63368. return true;
  63369. }
  63370. // go through all polygon nodes and cure small local self-intersections
  63371. function cureLocalIntersections(start, triangles, dim) {
  63372. var p = start;
  63373. do {
  63374. var a = p.prev, b = p.next.next;
  63375. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63376. triangles.push(a.i / dim);
  63377. triangles.push(p.i / dim);
  63378. triangles.push(b.i / dim);
  63379. // remove two nodes involved
  63380. removeNode(p);
  63381. removeNode(p.next);
  63382. p = start = b;
  63383. }
  63384. p = p.next;
  63385. } while (p !== start);
  63386. return p;
  63387. }
  63388. // try splitting polygon into two and triangulate them independently
  63389. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63390. // look for a valid diagonal that divides the polygon into two
  63391. var a = start;
  63392. do {
  63393. var b = a.next.next;
  63394. while (b !== a.prev) {
  63395. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63396. // split the polygon in two by the diagonal
  63397. var c = splitPolygon(a, b);
  63398. // filter colinear points around the cuts
  63399. a = filterPoints(a, a.next);
  63400. c = filterPoints(c, c.next);
  63401. // run earcut on each half
  63402. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63403. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63404. return;
  63405. }
  63406. b = b.next;
  63407. }
  63408. a = a.next;
  63409. } while (a !== start);
  63410. }
  63411. // link every hole into the outer loop, producing a single-ring polygon without holes
  63412. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63413. var queue = [], i, len, start, end, list;
  63414. for (i = 0, len = holeIndices.length; i < len; i++) {
  63415. start = holeIndices[i] * dim;
  63416. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63417. list = linkedList(data, start, end, dim, false);
  63418. if (list === list.next)
  63419. list.steiner = true;
  63420. queue.push(getLeftmost(list));
  63421. }
  63422. queue.sort(compareX);
  63423. // process holes from left to right
  63424. for (i = 0; i < queue.length; i++) {
  63425. eliminateHole(queue[i], outerNode);
  63426. outerNode = filterPoints(outerNode, outerNode.next);
  63427. }
  63428. return outerNode;
  63429. }
  63430. function compareX(a, b) {
  63431. return a.x - b.x;
  63432. }
  63433. // find a bridge between vertices that connects hole with an outer ring and and link it
  63434. function eliminateHole(hole, outerNode) {
  63435. outerNode = findHoleBridge(hole, outerNode);
  63436. if (outerNode) {
  63437. var b = splitPolygon(outerNode, hole);
  63438. filterPoints(b, b.next);
  63439. }
  63440. }
  63441. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63442. function findHoleBridge(hole, outerNode) {
  63443. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63444. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63445. // segment's endpoint with lesser x will be potential connection point
  63446. do {
  63447. if (hy <= p.y && hy >= p.next.y) {
  63448. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63449. if (x <= hx && x > qx) {
  63450. qx = x;
  63451. if (x === hx) {
  63452. if (hy === p.y)
  63453. return p;
  63454. if (hy === p.next.y)
  63455. return p.next;
  63456. }
  63457. m = p.x < p.next.x ? p : p.next;
  63458. }
  63459. }
  63460. p = p.next;
  63461. } while (p !== outerNode);
  63462. if (!m)
  63463. return null;
  63464. if (hx === qx)
  63465. return m.prev; // hole touches outer segment; pick lower endpoint
  63466. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63467. // if there are no points found, we have a valid connection;
  63468. // otherwise choose the point of the minimum angle with the ray as connection point
  63469. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63470. p = m.next;
  63471. while (p !== stop) {
  63472. if (hx >= p.x &&
  63473. p.x >= mx &&
  63474. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63475. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63476. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63477. m = p;
  63478. tanMin = tan;
  63479. }
  63480. }
  63481. p = p.next;
  63482. }
  63483. return m;
  63484. }
  63485. // interlink polygon nodes in z-order
  63486. function indexCurve(start, minX, minY, size) {
  63487. var p = start;
  63488. do {
  63489. if (p.z === null)
  63490. p.z = zOrder(p.x, p.y, minX, minY, size);
  63491. p.prevZ = p.prev;
  63492. p.nextZ = p.next;
  63493. p = p.next;
  63494. } while (p !== start);
  63495. p.prevZ.nextZ = null;
  63496. p.prevZ = null;
  63497. sortLinked(p);
  63498. }
  63499. // Simon Tatham's linked list merge sort algorithm
  63500. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63501. function sortLinked(list) {
  63502. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63503. do {
  63504. p = list;
  63505. list = null;
  63506. tail = null;
  63507. numMerges = 0;
  63508. while (p) {
  63509. numMerges++;
  63510. q = p;
  63511. pSize = 0;
  63512. for (i = 0; i < inSize; i++) {
  63513. pSize++;
  63514. q = q.nextZ;
  63515. if (!q)
  63516. break;
  63517. }
  63518. qSize = inSize;
  63519. while (pSize > 0 || (qSize > 0 && q)) {
  63520. if (pSize === 0) {
  63521. e = q;
  63522. q = q.nextZ;
  63523. qSize--;
  63524. }
  63525. else if (qSize === 0 || !q) {
  63526. e = p;
  63527. p = p.nextZ;
  63528. pSize--;
  63529. }
  63530. else if (p.z <= q.z) {
  63531. e = p;
  63532. p = p.nextZ;
  63533. pSize--;
  63534. }
  63535. else {
  63536. e = q;
  63537. q = q.nextZ;
  63538. qSize--;
  63539. }
  63540. if (tail)
  63541. tail.nextZ = e;
  63542. else
  63543. list = e;
  63544. e.prevZ = tail;
  63545. tail = e;
  63546. }
  63547. p = q;
  63548. }
  63549. tail.nextZ = null;
  63550. inSize *= 2;
  63551. } while (numMerges > 1);
  63552. return list;
  63553. }
  63554. // z-order of a point given coords and size of the data bounding box
  63555. function zOrder(x, y, minX, minY, size) {
  63556. // coords are transformed into non-negative 15-bit integer range
  63557. x = 32767 * (x - minX) / size;
  63558. y = 32767 * (y - minY) / size;
  63559. x = (x | (x << 8)) & 0x00FF00FF;
  63560. x = (x | (x << 4)) & 0x0F0F0F0F;
  63561. x = (x | (x << 2)) & 0x33333333;
  63562. x = (x | (x << 1)) & 0x55555555;
  63563. y = (y | (y << 8)) & 0x00FF00FF;
  63564. y = (y | (y << 4)) & 0x0F0F0F0F;
  63565. y = (y | (y << 2)) & 0x33333333;
  63566. y = (y | (y << 1)) & 0x55555555;
  63567. return x | (y << 1);
  63568. }
  63569. // find the leftmost node of a polygon ring
  63570. function getLeftmost(start) {
  63571. var p = start, leftmost = start;
  63572. do {
  63573. if (p.x < leftmost.x)
  63574. leftmost = p;
  63575. p = p.next;
  63576. } while (p !== start);
  63577. return leftmost;
  63578. }
  63579. // check if a point lies within a convex triangle
  63580. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  63581. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  63582. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  63583. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  63584. }
  63585. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  63586. function isValidDiagonal(a, b) {
  63587. return a.next.i !== b.i &&
  63588. a.prev.i !== b.i &&
  63589. !intersectsPolygon(a, b) &&
  63590. locallyInside(a, b) &&
  63591. locallyInside(b, a) &&
  63592. middleInside(a, b);
  63593. }
  63594. // signed area of a triangle
  63595. function area(p, q, r) {
  63596. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  63597. }
  63598. // check if two points are equal
  63599. function equals(p1, p2) {
  63600. return p1.x === p2.x && p1.y === p2.y;
  63601. }
  63602. // check if two segments intersect
  63603. function intersects(p1, q1, p2, q2) {
  63604. if ((equals(p1, q1) && equals(p2, q2)) ||
  63605. (equals(p1, q2) && equals(p2, q1)))
  63606. return true;
  63607. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  63608. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  63609. }
  63610. // check if a polygon diagonal intersects any polygon segments
  63611. function intersectsPolygon(a, b) {
  63612. var p = a;
  63613. do {
  63614. if (p.i !== a.i &&
  63615. p.next.i !== a.i &&
  63616. p.i !== b.i &&
  63617. p.next.i !== b.i &&
  63618. intersects(p, p.next, a, b))
  63619. return true;
  63620. p = p.next;
  63621. } while (p !== a);
  63622. return false;
  63623. }
  63624. // check if a polygon diagonal is locally inside the polygon
  63625. function locallyInside(a, b) {
  63626. return area(a.prev, a, a.next) < 0
  63627. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  63628. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  63629. }
  63630. // check if the middle point of a polygon diagonal is inside the polygon
  63631. function middleInside(a, b) {
  63632. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  63633. do {
  63634. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  63635. inside = !inside;
  63636. p = p.next;
  63637. } while (p !== a);
  63638. return inside;
  63639. }
  63640. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  63641. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  63642. function splitPolygon(a, b) {
  63643. 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;
  63644. a.next = b;
  63645. b.prev = a;
  63646. a2.next = an;
  63647. an.prev = a2;
  63648. b2.next = a2;
  63649. a2.prev = b2;
  63650. bp.next = b2;
  63651. b2.prev = bp;
  63652. return b2;
  63653. }
  63654. // create a node and optionally link it with previous one (in a circular doubly linked list)
  63655. function insertNode(i, x, y, last) {
  63656. var p = new Node(i, x, y);
  63657. if (!last) {
  63658. p.prev = p;
  63659. p.next = p;
  63660. }
  63661. else {
  63662. p.next = last.next;
  63663. p.prev = last;
  63664. last.next.prev = p;
  63665. last.next = p;
  63666. }
  63667. return p;
  63668. }
  63669. function removeNode(p) {
  63670. p.next.prev = p.prev;
  63671. p.prev.next = p.next;
  63672. if (p.prevZ)
  63673. p.prevZ.nextZ = p.nextZ;
  63674. if (p.nextZ)
  63675. p.nextZ.prevZ = p.prevZ;
  63676. }
  63677. /**
  63678. * return a percentage difference between the polygon area and its triangulation area;
  63679. * used to verify correctness of triangulation
  63680. */
  63681. function deviation(data, holeIndices, dim, triangles) {
  63682. var hasHoles = holeIndices && holeIndices.length;
  63683. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  63684. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  63685. if (hasHoles) {
  63686. for (var i = 0, len = holeIndices.length; i < len; i++) {
  63687. var start = holeIndices[i] * dim;
  63688. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63689. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  63690. }
  63691. }
  63692. var trianglesArea = 0;
  63693. for (i = 0; i < triangles.length; i += 3) {
  63694. var a = triangles[i] * dim;
  63695. var b = triangles[i + 1] * dim;
  63696. var c = triangles[i + 2] * dim;
  63697. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  63698. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  63699. }
  63700. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  63701. }
  63702. Earcut.deviation = deviation;
  63703. ;
  63704. function signedArea(data, start, end, dim) {
  63705. var sum = 0;
  63706. for (var i = start, j = end - dim; i < end; i += dim) {
  63707. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  63708. j = i;
  63709. }
  63710. return sum;
  63711. }
  63712. /**
  63713. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  63714. */
  63715. function flatten(data) {
  63716. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  63717. for (var i = 0; i < data.length; i++) {
  63718. for (var j = 0; j < data[i].length; j++) {
  63719. for (var d = 0; d < dim; d++)
  63720. result.vertices.push(data[i][j][d]);
  63721. }
  63722. if (i > 0) {
  63723. holeIndex += data[i - 1].length;
  63724. result.holes.push(holeIndex);
  63725. }
  63726. }
  63727. return result;
  63728. }
  63729. Earcut.flatten = flatten;
  63730. ;
  63731. })(Earcut || (Earcut = {}));
  63732. //# sourceMappingURL=babylon.earcut.js.map
  63733. var BABYLON;
  63734. (function (BABYLON) {
  63735. var IndexedVector2 = /** @class */ (function (_super) {
  63736. __extends(IndexedVector2, _super);
  63737. function IndexedVector2(original, index) {
  63738. var _this = _super.call(this, original.x, original.y) || this;
  63739. _this.index = index;
  63740. return _this;
  63741. }
  63742. return IndexedVector2;
  63743. }(BABYLON.Vector2));
  63744. var PolygonPoints = /** @class */ (function () {
  63745. function PolygonPoints() {
  63746. this.elements = new Array();
  63747. }
  63748. PolygonPoints.prototype.add = function (originalPoints) {
  63749. var _this = this;
  63750. var result = new Array();
  63751. originalPoints.forEach(function (point) {
  63752. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  63753. var newPoint = new IndexedVector2(point, _this.elements.length);
  63754. result.push(newPoint);
  63755. _this.elements.push(newPoint);
  63756. }
  63757. });
  63758. return result;
  63759. };
  63760. PolygonPoints.prototype.computeBounds = function () {
  63761. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63762. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  63763. this.elements.forEach(function (point) {
  63764. // x
  63765. if (point.x < lmin.x) {
  63766. lmin.x = point.x;
  63767. }
  63768. else if (point.x > lmax.x) {
  63769. lmax.x = point.x;
  63770. }
  63771. // y
  63772. if (point.y < lmin.y) {
  63773. lmin.y = point.y;
  63774. }
  63775. else if (point.y > lmax.y) {
  63776. lmax.y = point.y;
  63777. }
  63778. });
  63779. return {
  63780. min: lmin,
  63781. max: lmax,
  63782. width: lmax.x - lmin.x,
  63783. height: lmax.y - lmin.y
  63784. };
  63785. };
  63786. return PolygonPoints;
  63787. }());
  63788. var Polygon = /** @class */ (function () {
  63789. function Polygon() {
  63790. }
  63791. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  63792. return [
  63793. new BABYLON.Vector2(xmin, ymin),
  63794. new BABYLON.Vector2(xmax, ymin),
  63795. new BABYLON.Vector2(xmax, ymax),
  63796. new BABYLON.Vector2(xmin, ymax)
  63797. ];
  63798. };
  63799. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  63800. if (cx === void 0) { cx = 0; }
  63801. if (cy === void 0) { cy = 0; }
  63802. if (numberOfSides === void 0) { numberOfSides = 32; }
  63803. var result = new Array();
  63804. var angle = 0;
  63805. var increment = (Math.PI * 2) / numberOfSides;
  63806. for (var i = 0; i < numberOfSides; i++) {
  63807. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  63808. angle -= increment;
  63809. }
  63810. return result;
  63811. };
  63812. Polygon.Parse = function (input) {
  63813. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  63814. var i, result = [];
  63815. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  63816. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  63817. }
  63818. return result;
  63819. };
  63820. Polygon.StartingAt = function (x, y) {
  63821. return BABYLON.Path2.StartingAt(x, y);
  63822. };
  63823. return Polygon;
  63824. }());
  63825. BABYLON.Polygon = Polygon;
  63826. var PolygonMeshBuilder = /** @class */ (function () {
  63827. function PolygonMeshBuilder(name, contours, scene) {
  63828. this._points = new PolygonPoints();
  63829. this._outlinepoints = new PolygonPoints();
  63830. this._holes = new Array();
  63831. this._epoints = new Array();
  63832. this._eholes = new Array();
  63833. this._name = name;
  63834. this._scene = scene;
  63835. var points;
  63836. if (contours instanceof BABYLON.Path2) {
  63837. points = contours.getPoints();
  63838. }
  63839. else {
  63840. points = contours;
  63841. }
  63842. this._addToepoint(points);
  63843. this._points.add(points);
  63844. this._outlinepoints.add(points);
  63845. }
  63846. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  63847. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  63848. var p = points_1[_i];
  63849. this._epoints.push(p.x, p.y);
  63850. }
  63851. };
  63852. PolygonMeshBuilder.prototype.addHole = function (hole) {
  63853. this._points.add(hole);
  63854. var holepoints = new PolygonPoints();
  63855. holepoints.add(hole);
  63856. this._holes.push(holepoints);
  63857. this._eholes.push(this._epoints.length / 2);
  63858. this._addToepoint(hole);
  63859. return this;
  63860. };
  63861. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  63862. var _this = this;
  63863. if (updatable === void 0) { updatable = false; }
  63864. if (depth === void 0) { depth = 0; }
  63865. var result = new BABYLON.Mesh(this._name, this._scene);
  63866. var normals = new Array();
  63867. var positions = new Array();
  63868. var uvs = new Array();
  63869. var bounds = this._points.computeBounds();
  63870. this._points.elements.forEach(function (p) {
  63871. normals.push(0, 1.0, 0);
  63872. positions.push(p.x, 0, p.y);
  63873. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  63874. });
  63875. var indices = new Array();
  63876. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  63877. for (var i = 0; i < res.length; i++) {
  63878. indices.push(res[i]);
  63879. }
  63880. if (depth > 0) {
  63881. var positionscount = (positions.length / 3); //get the current pointcount
  63882. this._points.elements.forEach(function (p) {
  63883. normals.push(0, -1.0, 0);
  63884. positions.push(p.x, -depth, p.y);
  63885. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  63886. });
  63887. var totalCount = indices.length;
  63888. for (var i = 0; i < totalCount; i += 3) {
  63889. var i0 = indices[i + 0];
  63890. var i1 = indices[i + 1];
  63891. var i2 = indices[i + 2];
  63892. indices.push(i2 + positionscount);
  63893. indices.push(i1 + positionscount);
  63894. indices.push(i0 + positionscount);
  63895. }
  63896. //Add the sides
  63897. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  63898. this._holes.forEach(function (hole) {
  63899. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  63900. });
  63901. }
  63902. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  63903. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  63904. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  63905. result.setIndices(indices);
  63906. return result;
  63907. };
  63908. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  63909. var StartIndex = positions.length / 3;
  63910. var ulength = 0;
  63911. for (var i = 0; i < points.elements.length; i++) {
  63912. var p = points.elements[i];
  63913. var p1;
  63914. if ((i + 1) > points.elements.length - 1) {
  63915. p1 = points.elements[0];
  63916. }
  63917. else {
  63918. p1 = points.elements[i + 1];
  63919. }
  63920. positions.push(p.x, 0, p.y);
  63921. positions.push(p.x, -depth, p.y);
  63922. positions.push(p1.x, 0, p1.y);
  63923. positions.push(p1.x, -depth, p1.y);
  63924. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  63925. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  63926. var v3 = v2.subtract(v1);
  63927. var v4 = new BABYLON.Vector3(0, 1, 0);
  63928. var vn = BABYLON.Vector3.Cross(v3, v4);
  63929. vn = vn.normalize();
  63930. uvs.push(ulength / bounds.width, 0);
  63931. uvs.push(ulength / bounds.width, 1);
  63932. ulength += v3.length();
  63933. uvs.push((ulength / bounds.width), 0);
  63934. uvs.push((ulength / bounds.width), 1);
  63935. if (!flip) {
  63936. normals.push(-vn.x, -vn.y, -vn.z);
  63937. normals.push(-vn.x, -vn.y, -vn.z);
  63938. normals.push(-vn.x, -vn.y, -vn.z);
  63939. normals.push(-vn.x, -vn.y, -vn.z);
  63940. indices.push(StartIndex);
  63941. indices.push(StartIndex + 1);
  63942. indices.push(StartIndex + 2);
  63943. indices.push(StartIndex + 1);
  63944. indices.push(StartIndex + 3);
  63945. indices.push(StartIndex + 2);
  63946. }
  63947. else {
  63948. normals.push(vn.x, vn.y, vn.z);
  63949. normals.push(vn.x, vn.y, vn.z);
  63950. normals.push(vn.x, vn.y, vn.z);
  63951. normals.push(vn.x, vn.y, vn.z);
  63952. indices.push(StartIndex);
  63953. indices.push(StartIndex + 2);
  63954. indices.push(StartIndex + 1);
  63955. indices.push(StartIndex + 1);
  63956. indices.push(StartIndex + 2);
  63957. indices.push(StartIndex + 3);
  63958. }
  63959. StartIndex += 4;
  63960. }
  63961. ;
  63962. };
  63963. return PolygonMeshBuilder;
  63964. }());
  63965. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  63966. })(BABYLON || (BABYLON = {}));
  63967. //# sourceMappingURL=babylon.polygonMesh.js.map
  63968. var BABYLON;
  63969. (function (BABYLON) {
  63970. // Unique ID when we import meshes from Babylon to CSG
  63971. var currentCSGMeshId = 0;
  63972. // # class Vertex
  63973. // Represents a vertex of a polygon. Use your own vertex class instead of this
  63974. // one to provide additional features like texture coordinates and vertex
  63975. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  63976. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  63977. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  63978. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  63979. // is not used anywhere else.
  63980. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  63981. var Vertex = /** @class */ (function () {
  63982. function Vertex(pos, normal, uv) {
  63983. this.pos = pos;
  63984. this.normal = normal;
  63985. this.uv = uv;
  63986. }
  63987. Vertex.prototype.clone = function () {
  63988. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  63989. };
  63990. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  63991. // orientation of a polygon is flipped.
  63992. Vertex.prototype.flip = function () {
  63993. this.normal = this.normal.scale(-1);
  63994. };
  63995. // Create a new vertex between this vertex and `other` by linearly
  63996. // interpolating all properties using a parameter of `t`. Subclasses should
  63997. // override this to interpolate additional properties.
  63998. Vertex.prototype.interpolate = function (other, t) {
  63999. 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));
  64000. };
  64001. return Vertex;
  64002. }());
  64003. // # class Plane
  64004. // Represents a plane in 3D space.
  64005. var Plane = /** @class */ (function () {
  64006. function Plane(normal, w) {
  64007. this.normal = normal;
  64008. this.w = w;
  64009. }
  64010. Plane.FromPoints = function (a, b, c) {
  64011. var v0 = c.subtract(a);
  64012. var v1 = b.subtract(a);
  64013. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64014. return null;
  64015. }
  64016. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64017. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64018. };
  64019. Plane.prototype.clone = function () {
  64020. return new Plane(this.normal.clone(), this.w);
  64021. };
  64022. Plane.prototype.flip = function () {
  64023. this.normal.scaleInPlace(-1);
  64024. this.w = -this.w;
  64025. };
  64026. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64027. // fragments in the appropriate lists. Coplanar polygons go into either
  64028. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64029. // respect to this plane. Polygons in front or in back of this plane go into
  64030. // either `front` or `back`.
  64031. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64032. var COPLANAR = 0;
  64033. var FRONT = 1;
  64034. var BACK = 2;
  64035. var SPANNING = 3;
  64036. // Classify each point as well as the entire polygon into one of the above
  64037. // four classes.
  64038. var polygonType = 0;
  64039. var types = [];
  64040. var i;
  64041. var t;
  64042. for (i = 0; i < polygon.vertices.length; i++) {
  64043. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64044. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64045. polygonType |= type;
  64046. types.push(type);
  64047. }
  64048. // Put the polygon in the correct list, splitting it when necessary.
  64049. switch (polygonType) {
  64050. case COPLANAR:
  64051. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64052. break;
  64053. case FRONT:
  64054. front.push(polygon);
  64055. break;
  64056. case BACK:
  64057. back.push(polygon);
  64058. break;
  64059. case SPANNING:
  64060. var f = [], b = [];
  64061. for (i = 0; i < polygon.vertices.length; i++) {
  64062. var j = (i + 1) % polygon.vertices.length;
  64063. var ti = types[i], tj = types[j];
  64064. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64065. if (ti !== BACK)
  64066. f.push(vi);
  64067. if (ti !== FRONT)
  64068. b.push(ti !== BACK ? vi.clone() : vi);
  64069. if ((ti | tj) === SPANNING) {
  64070. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64071. var v = vi.interpolate(vj, t);
  64072. f.push(v);
  64073. b.push(v.clone());
  64074. }
  64075. }
  64076. var poly;
  64077. if (f.length >= 3) {
  64078. poly = new Polygon(f, polygon.shared);
  64079. if (poly.plane)
  64080. front.push(poly);
  64081. }
  64082. if (b.length >= 3) {
  64083. poly = new Polygon(b, polygon.shared);
  64084. if (poly.plane)
  64085. back.push(poly);
  64086. }
  64087. break;
  64088. }
  64089. };
  64090. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64091. // point is on the plane.
  64092. Plane.EPSILON = 1e-5;
  64093. return Plane;
  64094. }());
  64095. // # class Polygon
  64096. // Represents a convex polygon. The vertices used to initialize a polygon must
  64097. // be coplanar and form a convex loop.
  64098. //
  64099. // Each convex polygon has a `shared` property, which is shared between all
  64100. // polygons that are clones of each other or were split from the same polygon.
  64101. // This can be used to define per-polygon properties (such as surface color).
  64102. var Polygon = /** @class */ (function () {
  64103. function Polygon(vertices, shared) {
  64104. this.vertices = vertices;
  64105. this.shared = shared;
  64106. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64107. }
  64108. Polygon.prototype.clone = function () {
  64109. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64110. return new Polygon(vertices, this.shared);
  64111. };
  64112. Polygon.prototype.flip = function () {
  64113. this.vertices.reverse().map(function (v) { v.flip(); });
  64114. this.plane.flip();
  64115. };
  64116. return Polygon;
  64117. }());
  64118. // # class Node
  64119. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64120. // by picking a polygon to split along. That polygon (and all other coplanar
  64121. // polygons) are added directly to that node and the other polygons are added to
  64122. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64123. // no distinction between internal and leaf nodes.
  64124. var Node = /** @class */ (function () {
  64125. function Node(polygons) {
  64126. this.plane = null;
  64127. this.front = null;
  64128. this.back = null;
  64129. this.polygons = new Array();
  64130. if (polygons) {
  64131. this.build(polygons);
  64132. }
  64133. }
  64134. Node.prototype.clone = function () {
  64135. var node = new Node();
  64136. node.plane = this.plane && this.plane.clone();
  64137. node.front = this.front && this.front.clone();
  64138. node.back = this.back && this.back.clone();
  64139. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64140. return node;
  64141. };
  64142. // Convert solid space to empty space and empty space to solid space.
  64143. Node.prototype.invert = function () {
  64144. for (var i = 0; i < this.polygons.length; i++) {
  64145. this.polygons[i].flip();
  64146. }
  64147. if (this.plane) {
  64148. this.plane.flip();
  64149. }
  64150. if (this.front) {
  64151. this.front.invert();
  64152. }
  64153. if (this.back) {
  64154. this.back.invert();
  64155. }
  64156. var temp = this.front;
  64157. this.front = this.back;
  64158. this.back = temp;
  64159. };
  64160. // Recursively remove all polygons in `polygons` that are inside this BSP
  64161. // tree.
  64162. Node.prototype.clipPolygons = function (polygons) {
  64163. if (!this.plane)
  64164. return polygons.slice();
  64165. var front = new Array(), back = new Array();
  64166. for (var i = 0; i < polygons.length; i++) {
  64167. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64168. }
  64169. if (this.front) {
  64170. front = this.front.clipPolygons(front);
  64171. }
  64172. if (this.back) {
  64173. back = this.back.clipPolygons(back);
  64174. }
  64175. else {
  64176. back = [];
  64177. }
  64178. return front.concat(back);
  64179. };
  64180. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64181. // `bsp`.
  64182. Node.prototype.clipTo = function (bsp) {
  64183. this.polygons = bsp.clipPolygons(this.polygons);
  64184. if (this.front)
  64185. this.front.clipTo(bsp);
  64186. if (this.back)
  64187. this.back.clipTo(bsp);
  64188. };
  64189. // Return a list of all polygons in this BSP tree.
  64190. Node.prototype.allPolygons = function () {
  64191. var polygons = this.polygons.slice();
  64192. if (this.front)
  64193. polygons = polygons.concat(this.front.allPolygons());
  64194. if (this.back)
  64195. polygons = polygons.concat(this.back.allPolygons());
  64196. return polygons;
  64197. };
  64198. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64199. // new polygons are filtered down to the bottom of the tree and become new
  64200. // nodes there. Each set of polygons is partitioned using the first polygon
  64201. // (no heuristic is used to pick a good split).
  64202. Node.prototype.build = function (polygons) {
  64203. if (!polygons.length)
  64204. return;
  64205. if (!this.plane)
  64206. this.plane = polygons[0].plane.clone();
  64207. var front = new Array(), back = new Array();
  64208. for (var i = 0; i < polygons.length; i++) {
  64209. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64210. }
  64211. if (front.length) {
  64212. if (!this.front)
  64213. this.front = new Node();
  64214. this.front.build(front);
  64215. }
  64216. if (back.length) {
  64217. if (!this.back)
  64218. this.back = new Node();
  64219. this.back.build(back);
  64220. }
  64221. };
  64222. return Node;
  64223. }());
  64224. var CSG = /** @class */ (function () {
  64225. function CSG() {
  64226. this.polygons = new Array();
  64227. }
  64228. // Convert BABYLON.Mesh to BABYLON.CSG
  64229. CSG.FromMesh = function (mesh) {
  64230. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64231. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64232. if (mesh instanceof BABYLON.Mesh) {
  64233. mesh.computeWorldMatrix(true);
  64234. matrix = mesh.getWorldMatrix();
  64235. meshPosition = mesh.position.clone();
  64236. meshRotation = mesh.rotation.clone();
  64237. if (mesh.rotationQuaternion) {
  64238. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64239. }
  64240. meshScaling = mesh.scaling.clone();
  64241. }
  64242. else {
  64243. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64244. }
  64245. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64246. var subMeshes = mesh.subMeshes;
  64247. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64248. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64249. vertices = [];
  64250. for (var j = 0; j < 3; j++) {
  64251. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64252. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64253. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64254. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64255. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64256. vertex = new Vertex(position, normal, uv);
  64257. vertices.push(vertex);
  64258. }
  64259. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64260. // To handle the case of degenerated triangle
  64261. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64262. if (polygon.plane)
  64263. polygons.push(polygon);
  64264. }
  64265. }
  64266. var csg = CSG.FromPolygons(polygons);
  64267. csg.matrix = matrix;
  64268. csg.position = meshPosition;
  64269. csg.rotation = meshRotation;
  64270. csg.scaling = meshScaling;
  64271. csg.rotationQuaternion = meshRotationQuaternion;
  64272. currentCSGMeshId++;
  64273. return csg;
  64274. };
  64275. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64276. CSG.FromPolygons = function (polygons) {
  64277. var csg = new CSG();
  64278. csg.polygons = polygons;
  64279. return csg;
  64280. };
  64281. CSG.prototype.clone = function () {
  64282. var csg = new CSG();
  64283. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64284. csg.copyTransformAttributes(this);
  64285. return csg;
  64286. };
  64287. CSG.prototype.union = function (csg) {
  64288. var a = new Node(this.clone().polygons);
  64289. var b = new Node(csg.clone().polygons);
  64290. a.clipTo(b);
  64291. b.clipTo(a);
  64292. b.invert();
  64293. b.clipTo(a);
  64294. b.invert();
  64295. a.build(b.allPolygons());
  64296. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64297. };
  64298. CSG.prototype.unionInPlace = function (csg) {
  64299. var a = new Node(this.polygons);
  64300. var b = new Node(csg.polygons);
  64301. a.clipTo(b);
  64302. b.clipTo(a);
  64303. b.invert();
  64304. b.clipTo(a);
  64305. b.invert();
  64306. a.build(b.allPolygons());
  64307. this.polygons = a.allPolygons();
  64308. };
  64309. CSG.prototype.subtract = function (csg) {
  64310. var a = new Node(this.clone().polygons);
  64311. var b = new Node(csg.clone().polygons);
  64312. a.invert();
  64313. a.clipTo(b);
  64314. b.clipTo(a);
  64315. b.invert();
  64316. b.clipTo(a);
  64317. b.invert();
  64318. a.build(b.allPolygons());
  64319. a.invert();
  64320. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64321. };
  64322. CSG.prototype.subtractInPlace = function (csg) {
  64323. var a = new Node(this.polygons);
  64324. var b = new Node(csg.polygons);
  64325. a.invert();
  64326. a.clipTo(b);
  64327. b.clipTo(a);
  64328. b.invert();
  64329. b.clipTo(a);
  64330. b.invert();
  64331. a.build(b.allPolygons());
  64332. a.invert();
  64333. this.polygons = a.allPolygons();
  64334. };
  64335. CSG.prototype.intersect = function (csg) {
  64336. var a = new Node(this.clone().polygons);
  64337. var b = new Node(csg.clone().polygons);
  64338. a.invert();
  64339. b.clipTo(a);
  64340. b.invert();
  64341. a.clipTo(b);
  64342. b.clipTo(a);
  64343. a.build(b.allPolygons());
  64344. a.invert();
  64345. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64346. };
  64347. CSG.prototype.intersectInPlace = function (csg) {
  64348. var a = new Node(this.polygons);
  64349. var b = new Node(csg.polygons);
  64350. a.invert();
  64351. b.clipTo(a);
  64352. b.invert();
  64353. a.clipTo(b);
  64354. b.clipTo(a);
  64355. a.build(b.allPolygons());
  64356. a.invert();
  64357. this.polygons = a.allPolygons();
  64358. };
  64359. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64360. // not modified.
  64361. CSG.prototype.inverse = function () {
  64362. var csg = this.clone();
  64363. csg.inverseInPlace();
  64364. return csg;
  64365. };
  64366. CSG.prototype.inverseInPlace = function () {
  64367. this.polygons.map(function (p) { p.flip(); });
  64368. };
  64369. // This is used to keep meshes transformations so they can be restored
  64370. // when we build back a Babylon Mesh
  64371. // NB : All CSG operations are performed in world coordinates
  64372. CSG.prototype.copyTransformAttributes = function (csg) {
  64373. this.matrix = csg.matrix;
  64374. this.position = csg.position;
  64375. this.rotation = csg.rotation;
  64376. this.scaling = csg.scaling;
  64377. this.rotationQuaternion = csg.rotationQuaternion;
  64378. return this;
  64379. };
  64380. // Build Raw mesh from CSG
  64381. // Coordinates here are in world space
  64382. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64383. var matrix = this.matrix.clone();
  64384. matrix.invert();
  64385. 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;
  64386. if (keepSubMeshes) {
  64387. // Sort Polygons, since subMeshes are indices range
  64388. polygons.sort(function (a, b) {
  64389. if (a.shared.meshId === b.shared.meshId) {
  64390. return a.shared.subMeshId - b.shared.subMeshId;
  64391. }
  64392. else {
  64393. return a.shared.meshId - b.shared.meshId;
  64394. }
  64395. });
  64396. }
  64397. for (var i = 0, il = polygons.length; i < il; i++) {
  64398. polygon = polygons[i];
  64399. // Building SubMeshes
  64400. if (!subMesh_dict[polygon.shared.meshId]) {
  64401. subMesh_dict[polygon.shared.meshId] = {};
  64402. }
  64403. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64404. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64405. indexStart: +Infinity,
  64406. indexEnd: -Infinity,
  64407. materialIndex: polygon.shared.materialIndex
  64408. };
  64409. }
  64410. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64411. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64412. polygonIndices[0] = 0;
  64413. polygonIndices[1] = j - 1;
  64414. polygonIndices[2] = j;
  64415. for (var k = 0; k < 3; k++) {
  64416. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64417. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64418. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64419. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64420. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64421. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64422. // Check if 2 points can be merged
  64423. if (!(typeof vertex_idx !== 'undefined' &&
  64424. normals[vertex_idx * 3] === localNormal.x &&
  64425. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64426. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64427. uvs[vertex_idx * 2] === uv.x &&
  64428. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64429. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64430. uvs.push(uv.x, uv.y);
  64431. normals.push(normal.x, normal.y, normal.z);
  64432. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64433. }
  64434. indices.push(vertex_idx);
  64435. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64436. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64437. currentIndex++;
  64438. }
  64439. }
  64440. }
  64441. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64442. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64443. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64444. mesh.setIndices(indices, null);
  64445. if (keepSubMeshes) {
  64446. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64447. var materialIndexOffset = 0, materialMaxIndex;
  64448. mesh.subMeshes = new Array();
  64449. for (var m in subMesh_dict) {
  64450. materialMaxIndex = -1;
  64451. for (var sm in subMesh_dict[m]) {
  64452. subMesh_obj = subMesh_dict[m][sm];
  64453. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64454. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64455. }
  64456. materialIndexOffset += ++materialMaxIndex;
  64457. }
  64458. }
  64459. return mesh;
  64460. };
  64461. // Build Mesh from CSG taking material and transforms into account
  64462. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64463. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64464. mesh.material = material;
  64465. mesh.position.copyFrom(this.position);
  64466. mesh.rotation.copyFrom(this.rotation);
  64467. if (this.rotationQuaternion) {
  64468. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64469. }
  64470. mesh.scaling.copyFrom(this.scaling);
  64471. mesh.computeWorldMatrix(true);
  64472. return mesh;
  64473. };
  64474. return CSG;
  64475. }());
  64476. BABYLON.CSG = CSG;
  64477. })(BABYLON || (BABYLON = {}));
  64478. //# sourceMappingURL=babylon.csg.js.map
  64479. var BABYLON;
  64480. (function (BABYLON) {
  64481. var LensFlare = /** @class */ (function () {
  64482. function LensFlare(size, position, color, imgUrl, system) {
  64483. this.size = size;
  64484. this.position = position;
  64485. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64486. this.color = color || new BABYLON.Color3(1, 1, 1);
  64487. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64488. this._system = system;
  64489. system.lensFlares.push(this);
  64490. }
  64491. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64492. return new LensFlare(size, position, color, imgUrl, system);
  64493. };
  64494. LensFlare.prototype.dispose = function () {
  64495. if (this.texture) {
  64496. this.texture.dispose();
  64497. }
  64498. // Remove from scene
  64499. var index = this._system.lensFlares.indexOf(this);
  64500. this._system.lensFlares.splice(index, 1);
  64501. };
  64502. ;
  64503. return LensFlare;
  64504. }());
  64505. BABYLON.LensFlare = LensFlare;
  64506. })(BABYLON || (BABYLON = {}));
  64507. //# sourceMappingURL=babylon.lensFlare.js.map
  64508. var BABYLON;
  64509. (function (BABYLON) {
  64510. var LensFlareSystem = /** @class */ (function () {
  64511. function LensFlareSystem(name, emitter, scene) {
  64512. this.name = name;
  64513. this.lensFlares = new Array();
  64514. this.borderLimit = 300;
  64515. this.viewportBorder = 0;
  64516. this.layerMask = 0x0FFFFFFF;
  64517. this._vertexBuffers = {};
  64518. this._isEnabled = true;
  64519. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64520. this._emitter = emitter;
  64521. this.id = name;
  64522. scene.lensFlareSystems.push(this);
  64523. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64524. var engine = scene.getEngine();
  64525. // VBO
  64526. var vertices = [];
  64527. vertices.push(1, 1);
  64528. vertices.push(-1, 1);
  64529. vertices.push(-1, -1);
  64530. vertices.push(1, -1);
  64531. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64532. // Indices
  64533. var indices = [];
  64534. indices.push(0);
  64535. indices.push(1);
  64536. indices.push(2);
  64537. indices.push(0);
  64538. indices.push(2);
  64539. indices.push(3);
  64540. this._indexBuffer = engine.createIndexBuffer(indices);
  64541. // Effects
  64542. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64543. }
  64544. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64545. get: function () {
  64546. return this._isEnabled;
  64547. },
  64548. set: function (value) {
  64549. this._isEnabled = value;
  64550. },
  64551. enumerable: true,
  64552. configurable: true
  64553. });
  64554. LensFlareSystem.prototype.getScene = function () {
  64555. return this._scene;
  64556. };
  64557. LensFlareSystem.prototype.getEmitter = function () {
  64558. return this._emitter;
  64559. };
  64560. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64561. this._emitter = newEmitter;
  64562. };
  64563. LensFlareSystem.prototype.getEmitterPosition = function () {
  64564. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  64565. };
  64566. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  64567. var position = this.getEmitterPosition();
  64568. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  64569. this._positionX = position.x;
  64570. this._positionY = position.y;
  64571. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  64572. if (this.viewportBorder > 0) {
  64573. globalViewport.x -= this.viewportBorder;
  64574. globalViewport.y -= this.viewportBorder;
  64575. globalViewport.width += this.viewportBorder * 2;
  64576. globalViewport.height += this.viewportBorder * 2;
  64577. position.x += this.viewportBorder;
  64578. position.y += this.viewportBorder;
  64579. this._positionX += this.viewportBorder;
  64580. this._positionY += this.viewportBorder;
  64581. }
  64582. if (position.z > 0) {
  64583. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  64584. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  64585. return true;
  64586. }
  64587. return true;
  64588. }
  64589. return false;
  64590. };
  64591. LensFlareSystem.prototype._isVisible = function () {
  64592. if (!this._isEnabled || !this._scene.activeCamera) {
  64593. return false;
  64594. }
  64595. var emitterPosition = this.getEmitterPosition();
  64596. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  64597. var distance = direction.length();
  64598. direction.normalize();
  64599. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  64600. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  64601. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  64602. };
  64603. LensFlareSystem.prototype.render = function () {
  64604. if (!this._effect.isReady() || !this._scene.activeCamera)
  64605. return false;
  64606. var engine = this._scene.getEngine();
  64607. var viewport = this._scene.activeCamera.viewport;
  64608. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  64609. // Position
  64610. if (!this.computeEffectivePosition(globalViewport)) {
  64611. return false;
  64612. }
  64613. // Visibility
  64614. if (!this._isVisible()) {
  64615. return false;
  64616. }
  64617. // Intensity
  64618. var awayX;
  64619. var awayY;
  64620. if (this._positionX < this.borderLimit + globalViewport.x) {
  64621. awayX = this.borderLimit + globalViewport.x - this._positionX;
  64622. }
  64623. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  64624. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  64625. }
  64626. else {
  64627. awayX = 0;
  64628. }
  64629. if (this._positionY < this.borderLimit + globalViewport.y) {
  64630. awayY = this.borderLimit + globalViewport.y - this._positionY;
  64631. }
  64632. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  64633. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  64634. }
  64635. else {
  64636. awayY = 0;
  64637. }
  64638. var away = (awayX > awayY) ? awayX : awayY;
  64639. away -= this.viewportBorder;
  64640. if (away > this.borderLimit) {
  64641. away = this.borderLimit;
  64642. }
  64643. var intensity = 1.0 - (away / this.borderLimit);
  64644. if (intensity < 0) {
  64645. return false;
  64646. }
  64647. if (intensity > 1.0) {
  64648. intensity = 1.0;
  64649. }
  64650. if (this.viewportBorder > 0) {
  64651. globalViewport.x += this.viewportBorder;
  64652. globalViewport.y += this.viewportBorder;
  64653. globalViewport.width -= this.viewportBorder * 2;
  64654. globalViewport.height -= this.viewportBorder * 2;
  64655. this._positionX -= this.viewportBorder;
  64656. this._positionY -= this.viewportBorder;
  64657. }
  64658. // Position
  64659. var centerX = globalViewport.x + globalViewport.width / 2;
  64660. var centerY = globalViewport.y + globalViewport.height / 2;
  64661. var distX = centerX - this._positionX;
  64662. var distY = centerY - this._positionY;
  64663. // Effects
  64664. engine.enableEffect(this._effect);
  64665. engine.setState(false);
  64666. engine.setDepthBuffer(false);
  64667. // VBOs
  64668. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64669. // Flares
  64670. for (var index = 0; index < this.lensFlares.length; index++) {
  64671. var flare = this.lensFlares[index];
  64672. engine.setAlphaMode(flare.alphaMode);
  64673. var x = centerX - (distX * flare.position);
  64674. var y = centerY - (distY * flare.position);
  64675. var cw = flare.size;
  64676. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  64677. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  64678. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  64679. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  64680. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  64681. // Texture
  64682. this._effect.setTexture("textureSampler", flare.texture);
  64683. // Color
  64684. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  64685. // Draw order
  64686. engine.draw(true, 0, 6);
  64687. }
  64688. engine.setDepthBuffer(true);
  64689. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64690. return true;
  64691. };
  64692. LensFlareSystem.prototype.dispose = function () {
  64693. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64694. if (vertexBuffer) {
  64695. vertexBuffer.dispose();
  64696. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64697. }
  64698. if (this._indexBuffer) {
  64699. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64700. this._indexBuffer = null;
  64701. }
  64702. while (this.lensFlares.length) {
  64703. this.lensFlares[0].dispose();
  64704. }
  64705. // Remove from scene
  64706. var index = this._scene.lensFlareSystems.indexOf(this);
  64707. this._scene.lensFlareSystems.splice(index, 1);
  64708. };
  64709. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  64710. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  64711. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  64712. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  64713. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  64714. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  64715. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  64716. var parsedFlare = parsedLensFlareSystem.flares[index];
  64717. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  64718. }
  64719. return lensFlareSystem;
  64720. };
  64721. LensFlareSystem.prototype.serialize = function () {
  64722. var serializationObject = {};
  64723. serializationObject.id = this.id;
  64724. serializationObject.name = this.name;
  64725. serializationObject.emitterId = this.getEmitter().id;
  64726. serializationObject.borderLimit = this.borderLimit;
  64727. serializationObject.flares = [];
  64728. for (var index = 0; index < this.lensFlares.length; index++) {
  64729. var flare = this.lensFlares[index];
  64730. serializationObject.flares.push({
  64731. size: flare.size,
  64732. position: flare.position,
  64733. color: flare.color.asArray(),
  64734. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  64735. });
  64736. }
  64737. return serializationObject;
  64738. };
  64739. return LensFlareSystem;
  64740. }());
  64741. BABYLON.LensFlareSystem = LensFlareSystem;
  64742. })(BABYLON || (BABYLON = {}));
  64743. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  64744. var BABYLON;
  64745. (function (BABYLON) {
  64746. /**
  64747. * This is a holder class for the physics joint created by the physics plugin.
  64748. * It holds a set of functions to control the underlying joint.
  64749. */
  64750. var PhysicsJoint = /** @class */ (function () {
  64751. function PhysicsJoint(type, jointData) {
  64752. this.type = type;
  64753. this.jointData = jointData;
  64754. jointData.nativeParams = jointData.nativeParams || {};
  64755. }
  64756. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  64757. get: function () {
  64758. return this._physicsJoint;
  64759. },
  64760. set: function (newJoint) {
  64761. if (this._physicsJoint) {
  64762. //remove from the wolrd
  64763. }
  64764. this._physicsJoint = newJoint;
  64765. },
  64766. enumerable: true,
  64767. configurable: true
  64768. });
  64769. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  64770. set: function (physicsPlugin) {
  64771. this._physicsPlugin = physicsPlugin;
  64772. },
  64773. enumerable: true,
  64774. configurable: true
  64775. });
  64776. /**
  64777. * Execute a function that is physics-plugin specific.
  64778. * @param {Function} func the function that will be executed.
  64779. * It accepts two parameters: the physics world and the physics joint.
  64780. */
  64781. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  64782. func(this._physicsPlugin.world, this._physicsJoint);
  64783. };
  64784. //TODO check if the native joints are the same
  64785. //Joint Types
  64786. PhysicsJoint.DistanceJoint = 0;
  64787. PhysicsJoint.HingeJoint = 1;
  64788. PhysicsJoint.BallAndSocketJoint = 2;
  64789. PhysicsJoint.WheelJoint = 3;
  64790. PhysicsJoint.SliderJoint = 4;
  64791. //OIMO
  64792. PhysicsJoint.PrismaticJoint = 5;
  64793. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  64794. PhysicsJoint.UniversalJoint = 6;
  64795. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  64796. //Cannon
  64797. //Similar to a Ball-Joint. Different in params
  64798. PhysicsJoint.PointToPointJoint = 8;
  64799. //Cannon only at the moment
  64800. PhysicsJoint.SpringJoint = 9;
  64801. PhysicsJoint.LockJoint = 10;
  64802. return PhysicsJoint;
  64803. }());
  64804. BABYLON.PhysicsJoint = PhysicsJoint;
  64805. /**
  64806. * A class representing a physics distance joint.
  64807. */
  64808. var DistanceJoint = /** @class */ (function (_super) {
  64809. __extends(DistanceJoint, _super);
  64810. function DistanceJoint(jointData) {
  64811. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  64812. }
  64813. /**
  64814. * Update the predefined distance.
  64815. */
  64816. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  64817. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  64818. };
  64819. return DistanceJoint;
  64820. }(PhysicsJoint));
  64821. BABYLON.DistanceJoint = DistanceJoint;
  64822. var MotorEnabledJoint = /** @class */ (function (_super) {
  64823. __extends(MotorEnabledJoint, _super);
  64824. function MotorEnabledJoint(type, jointData) {
  64825. return _super.call(this, type, jointData) || this;
  64826. }
  64827. /**
  64828. * Set the motor values.
  64829. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64830. * @param {number} force the force to apply
  64831. * @param {number} maxForce max force for this motor.
  64832. */
  64833. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  64834. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64835. };
  64836. /**
  64837. * Set the motor's limits.
  64838. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64839. */
  64840. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64841. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64842. };
  64843. return MotorEnabledJoint;
  64844. }(PhysicsJoint));
  64845. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  64846. /**
  64847. * This class represents a single hinge physics joint
  64848. */
  64849. var HingeJoint = /** @class */ (function (_super) {
  64850. __extends(HingeJoint, _super);
  64851. function HingeJoint(jointData) {
  64852. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  64853. }
  64854. /**
  64855. * Set the motor values.
  64856. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64857. * @param {number} force the force to apply
  64858. * @param {number} maxForce max force for this motor.
  64859. */
  64860. HingeJoint.prototype.setMotor = function (force, maxForce) {
  64861. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  64862. };
  64863. /**
  64864. * Set the motor's limits.
  64865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64866. */
  64867. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  64868. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  64869. };
  64870. return HingeJoint;
  64871. }(MotorEnabledJoint));
  64872. BABYLON.HingeJoint = HingeJoint;
  64873. /**
  64874. * This class represents a dual hinge physics joint (same as wheel joint)
  64875. */
  64876. var Hinge2Joint = /** @class */ (function (_super) {
  64877. __extends(Hinge2Joint, _super);
  64878. function Hinge2Joint(jointData) {
  64879. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  64880. }
  64881. /**
  64882. * Set the motor values.
  64883. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64884. * @param {number} force the force to apply
  64885. * @param {number} maxForce max force for this motor.
  64886. * @param {motorIndex} the motor's index, 0 or 1.
  64887. */
  64888. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  64889. if (motorIndex === void 0) { motorIndex = 0; }
  64890. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  64891. };
  64892. /**
  64893. * Set the motor limits.
  64894. * Attention, this function is plugin specific. Engines won't react 100% the same.
  64895. * @param {number} upperLimit the upper limit
  64896. * @param {number} lowerLimit lower limit
  64897. * @param {motorIndex} the motor's index, 0 or 1.
  64898. */
  64899. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  64900. if (motorIndex === void 0) { motorIndex = 0; }
  64901. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  64902. };
  64903. return Hinge2Joint;
  64904. }(MotorEnabledJoint));
  64905. BABYLON.Hinge2Joint = Hinge2Joint;
  64906. })(BABYLON || (BABYLON = {}));
  64907. //# sourceMappingURL=babylon.physicsJoint.js.map
  64908. var BABYLON;
  64909. (function (BABYLON) {
  64910. var PhysicsImpostor = /** @class */ (function () {
  64911. function PhysicsImpostor(object, type, _options, _scene) {
  64912. if (_options === void 0) { _options = { mass: 0 }; }
  64913. var _this = this;
  64914. this.object = object;
  64915. this.type = type;
  64916. this._options = _options;
  64917. this._scene = _scene;
  64918. this._bodyUpdateRequired = false;
  64919. this._onBeforePhysicsStepCallbacks = new Array();
  64920. this._onAfterPhysicsStepCallbacks = new Array();
  64921. this._onPhysicsCollideCallbacks = [];
  64922. this._deltaPosition = BABYLON.Vector3.Zero();
  64923. this._isDisposed = false;
  64924. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  64925. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  64926. /**
  64927. * this function is executed by the physics engine.
  64928. */
  64929. this.beforeStep = function () {
  64930. if (!_this._physicsEngine) {
  64931. return;
  64932. }
  64933. if (_this._options.ignoreParent && _this.object.parent) {
  64934. _this._tmpPositionWithDelta.copyFrom(_this.object.getAbsolutePosition());
  64935. //this.object.getAbsolutePosition().subtractToRef(this._deltaPosition, this._tmpPositionWithDelta);
  64936. }
  64937. else {
  64938. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  64939. }
  64940. //conjugate deltaRotation
  64941. if (_this.object.rotationQuaternion) {
  64942. if (_this._deltaRotationConjugated) {
  64943. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  64944. }
  64945. else {
  64946. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  64947. }
  64948. }
  64949. // Only if not disabled
  64950. if (!_this._options.disableBidirectionalTransformation) {
  64951. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  64952. }
  64953. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  64954. func(_this);
  64955. });
  64956. };
  64957. /**
  64958. * this function is executed by the physics engine.
  64959. */
  64960. this.afterStep = function () {
  64961. if (!_this._physicsEngine) {
  64962. return;
  64963. }
  64964. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  64965. func(_this);
  64966. });
  64967. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  64968. if (_this._options.ignoreParent && _this.object.parent) {
  64969. _this.object.position.subtractInPlace(_this.object.parent.getAbsolutePosition());
  64970. }
  64971. else {
  64972. _this.object.position.addInPlace(_this._deltaPosition);
  64973. }
  64974. if (_this._deltaRotation && _this.object.rotationQuaternion) {
  64975. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  64976. }
  64977. };
  64978. /**
  64979. * Legacy collision detection event support
  64980. */
  64981. this.onCollideEvent = null;
  64982. //event and body object due to cannon's event-based architecture.
  64983. this.onCollide = function (e) {
  64984. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  64985. return;
  64986. }
  64987. if (!_this._physicsEngine) {
  64988. return;
  64989. }
  64990. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  64991. if (otherImpostor) {
  64992. // Legacy collision detection event support
  64993. if (_this.onCollideEvent) {
  64994. _this.onCollideEvent(_this, otherImpostor);
  64995. }
  64996. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  64997. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  64998. }).forEach(function (obj) {
  64999. obj.callback(_this, otherImpostor);
  65000. });
  65001. }
  65002. };
  65003. //sanity check!
  65004. if (!this.object) {
  65005. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65006. return;
  65007. }
  65008. //legacy support for old syntax.
  65009. if (!this._scene && object.getScene) {
  65010. this._scene = object.getScene();
  65011. }
  65012. if (!this._scene) {
  65013. return;
  65014. }
  65015. this._physicsEngine = this._scene.getPhysicsEngine();
  65016. if (!this._physicsEngine) {
  65017. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65018. }
  65019. else {
  65020. //set the object's quaternion, if not set
  65021. if (!this.object.rotationQuaternion) {
  65022. if (this.object.rotation) {
  65023. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65024. }
  65025. else {
  65026. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65027. }
  65028. }
  65029. //default options params
  65030. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65031. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65032. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65033. this._joints = [];
  65034. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65035. if (!this.object.parent || this._options.ignoreParent) {
  65036. this._init();
  65037. }
  65038. else if (this.object.parent.physicsImpostor) {
  65039. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65040. }
  65041. }
  65042. }
  65043. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65044. get: function () {
  65045. return this._isDisposed;
  65046. },
  65047. enumerable: true,
  65048. configurable: true
  65049. });
  65050. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65051. get: function () {
  65052. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65053. },
  65054. set: function (value) {
  65055. this.setMass(value);
  65056. },
  65057. enumerable: true,
  65058. configurable: true
  65059. });
  65060. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65061. get: function () {
  65062. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65063. },
  65064. set: function (value) {
  65065. if (!this._physicsEngine) {
  65066. return;
  65067. }
  65068. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65074. get: function () {
  65075. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65076. },
  65077. set: function (value) {
  65078. if (!this._physicsEngine) {
  65079. return;
  65080. }
  65081. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65082. },
  65083. enumerable: true,
  65084. configurable: true
  65085. });
  65086. /**
  65087. * This function will completly initialize this impostor.
  65088. * It will create a new body - but only if this mesh has no parent.
  65089. * If it has, this impostor will not be used other than to define the impostor
  65090. * of the child mesh.
  65091. */
  65092. PhysicsImpostor.prototype._init = function () {
  65093. if (!this._physicsEngine) {
  65094. return;
  65095. }
  65096. this._physicsEngine.removeImpostor(this);
  65097. this.physicsBody = null;
  65098. this._parent = this._parent || this._getPhysicsParent();
  65099. if (!this.parent || this._options.ignoreParent) {
  65100. this._physicsEngine.addImpostor(this);
  65101. }
  65102. };
  65103. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65104. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65105. var parentMesh = this.object.parent;
  65106. return parentMesh.physicsImpostor;
  65107. }
  65108. return null;
  65109. };
  65110. /**
  65111. * Should a new body be generated.
  65112. */
  65113. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65114. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65115. };
  65116. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65117. this.forceUpdate();
  65118. };
  65119. /**
  65120. * Force a regeneration of this or the parent's impostor's body.
  65121. * Use under cautious - This will remove all joints already implemented.
  65122. */
  65123. PhysicsImpostor.prototype.forceUpdate = function () {
  65124. this._init();
  65125. if (this.parent && !this._options.ignoreParent) {
  65126. this.parent.forceUpdate();
  65127. }
  65128. };
  65129. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65130. /*public get mesh(): AbstractMesh {
  65131. return this._mesh;
  65132. }*/
  65133. /**
  65134. * Gets the body that holds this impostor. Either its own, or its parent.
  65135. */
  65136. get: function () {
  65137. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65138. },
  65139. /**
  65140. * Set the physics body. Used mainly by the physics engine/plugin
  65141. */
  65142. set: function (physicsBody) {
  65143. if (this._physicsBody && this._physicsEngine) {
  65144. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65145. }
  65146. this._physicsBody = physicsBody;
  65147. this.resetUpdateFlags();
  65148. },
  65149. enumerable: true,
  65150. configurable: true
  65151. });
  65152. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65153. get: function () {
  65154. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65155. },
  65156. set: function (value) {
  65157. this._parent = value;
  65158. },
  65159. enumerable: true,
  65160. configurable: true
  65161. });
  65162. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65163. this._bodyUpdateRequired = false;
  65164. };
  65165. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65166. if (this.object.getBoundingInfo) {
  65167. var q = this.object.rotationQuaternion;
  65168. //reset rotation
  65169. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65170. //calculate the world matrix with no rotation
  65171. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65172. var boundingInfo = this.object.getBoundingInfo();
  65173. var size = void 0;
  65174. if (boundingInfo) {
  65175. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65176. }
  65177. else {
  65178. size = BABYLON.Vector3.Zero();
  65179. }
  65180. //bring back the rotation
  65181. this.object.rotationQuaternion = q;
  65182. //calculate the world matrix with the new rotation
  65183. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65184. return size;
  65185. }
  65186. else {
  65187. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65188. }
  65189. };
  65190. PhysicsImpostor.prototype.getObjectCenter = function () {
  65191. if (this.object.getBoundingInfo) {
  65192. var boundingInfo = this.object.getBoundingInfo();
  65193. if (!boundingInfo) {
  65194. return this.object.position;
  65195. }
  65196. return boundingInfo.boundingBox.centerWorld;
  65197. }
  65198. else {
  65199. return this.object.position;
  65200. }
  65201. };
  65202. /**
  65203. * Get a specific parametes from the options parameter.
  65204. */
  65205. PhysicsImpostor.prototype.getParam = function (paramName) {
  65206. return this._options[paramName];
  65207. };
  65208. /**
  65209. * Sets a specific parameter in the options given to the physics plugin
  65210. */
  65211. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65212. this._options[paramName] = value;
  65213. this._bodyUpdateRequired = true;
  65214. };
  65215. /**
  65216. * Specifically change the body's mass option. Won't recreate the physics body object
  65217. */
  65218. PhysicsImpostor.prototype.setMass = function (mass) {
  65219. if (this.getParam("mass") !== mass) {
  65220. this.setParam("mass", mass);
  65221. }
  65222. if (this._physicsEngine) {
  65223. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65224. }
  65225. };
  65226. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65227. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65228. };
  65229. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65230. if (this._physicsEngine) {
  65231. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65232. }
  65233. };
  65234. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65236. };
  65237. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65238. if (this._physicsEngine) {
  65239. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65240. }
  65241. };
  65242. /**
  65243. * Execute a function with the physics plugin native code.
  65244. * Provide a function the will have two variables - the world object and the physics body object.
  65245. */
  65246. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65247. if (this._physicsEngine) {
  65248. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65249. }
  65250. };
  65251. /**
  65252. * Register a function that will be executed before the physics world is stepping forward.
  65253. */
  65254. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65255. this._onBeforePhysicsStepCallbacks.push(func);
  65256. };
  65257. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65258. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65259. if (index > -1) {
  65260. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65261. }
  65262. else {
  65263. BABYLON.Tools.Warn("Function to remove was not found");
  65264. }
  65265. };
  65266. /**
  65267. * Register a function that will be executed after the physics step
  65268. */
  65269. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65270. this._onAfterPhysicsStepCallbacks.push(func);
  65271. };
  65272. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65273. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65274. if (index > -1) {
  65275. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65276. }
  65277. else {
  65278. BABYLON.Tools.Warn("Function to remove was not found");
  65279. }
  65280. };
  65281. /**
  65282. * register a function that will be executed when this impostor collides against a different body.
  65283. */
  65284. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65285. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65286. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65287. };
  65288. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65289. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65290. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65291. if (index > -1) {
  65292. this._onPhysicsCollideCallbacks.splice(index, 1);
  65293. }
  65294. else {
  65295. BABYLON.Tools.Warn("Function to remove was not found");
  65296. }
  65297. };
  65298. /**
  65299. * Apply a force
  65300. */
  65301. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65302. if (this._physicsEngine) {
  65303. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65304. }
  65305. return this;
  65306. };
  65307. /**
  65308. * Apply an impulse
  65309. */
  65310. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65311. if (this._physicsEngine) {
  65312. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65313. }
  65314. return this;
  65315. };
  65316. /**
  65317. * A help function to create a joint.
  65318. */
  65319. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65320. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65321. this.addJoint(otherImpostor, joint);
  65322. return this;
  65323. };
  65324. /**
  65325. * Add a joint to this impostor with a different impostor.
  65326. */
  65327. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65328. this._joints.push({
  65329. otherImpostor: otherImpostor,
  65330. joint: joint
  65331. });
  65332. if (this._physicsEngine) {
  65333. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65334. }
  65335. return this;
  65336. };
  65337. /**
  65338. * Will keep this body still, in a sleep mode.
  65339. */
  65340. PhysicsImpostor.prototype.sleep = function () {
  65341. if (this._physicsEngine) {
  65342. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65343. }
  65344. return this;
  65345. };
  65346. /**
  65347. * Wake the body up.
  65348. */
  65349. PhysicsImpostor.prototype.wakeUp = function () {
  65350. if (this._physicsEngine) {
  65351. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65352. }
  65353. return this;
  65354. };
  65355. PhysicsImpostor.prototype.clone = function (newObject) {
  65356. if (!newObject)
  65357. return null;
  65358. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65359. };
  65360. PhysicsImpostor.prototype.dispose = function () {
  65361. var _this = this;
  65362. //no dispose if no physics engine is available.
  65363. if (!this._physicsEngine) {
  65364. return;
  65365. }
  65366. this._joints.forEach(function (j) {
  65367. if (_this._physicsEngine) {
  65368. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65369. }
  65370. });
  65371. //dispose the physics body
  65372. this._physicsEngine.removeImpostor(this);
  65373. if (this.parent) {
  65374. this.parent.forceUpdate();
  65375. }
  65376. else {
  65377. /*this._object.getChildMeshes().forEach(function(mesh) {
  65378. if (mesh.physicsImpostor) {
  65379. if (disposeChildren) {
  65380. mesh.physicsImpostor.dispose();
  65381. mesh.physicsImpostor = null;
  65382. }
  65383. }
  65384. })*/
  65385. }
  65386. this._isDisposed = true;
  65387. };
  65388. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65389. this._deltaPosition.copyFrom(position);
  65390. };
  65391. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65392. if (!this._deltaRotation) {
  65393. this._deltaRotation = new BABYLON.Quaternion();
  65394. }
  65395. this._deltaRotation.copyFrom(rotation);
  65396. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65397. };
  65398. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65399. if (this._physicsEngine) {
  65400. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65401. }
  65402. return this;
  65403. };
  65404. PhysicsImpostor.prototype.getRadius = function () {
  65405. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65406. };
  65407. /**
  65408. * Sync a bone with this impostor
  65409. * @param bone The bone to sync to the impostor.
  65410. * @param boneMesh The mesh that the bone is influencing.
  65411. * @param jointPivot The pivot of the joint / bone in local space.
  65412. * @param distToJoint Optional distance from the impostor to the joint.
  65413. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65414. */
  65415. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65416. var tempVec = PhysicsImpostor._tmpVecs[0];
  65417. var mesh = this.object;
  65418. if (mesh.rotationQuaternion) {
  65419. if (adjustRotation) {
  65420. var tempQuat = PhysicsImpostor._tmpQuat;
  65421. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65422. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65423. }
  65424. else {
  65425. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65426. }
  65427. }
  65428. tempVec.x = 0;
  65429. tempVec.y = 0;
  65430. tempVec.z = 0;
  65431. if (jointPivot) {
  65432. tempVec.x = jointPivot.x;
  65433. tempVec.y = jointPivot.y;
  65434. tempVec.z = jointPivot.z;
  65435. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65436. if (distToJoint === undefined || distToJoint === null) {
  65437. distToJoint = jointPivot.length();
  65438. }
  65439. tempVec.x *= distToJoint;
  65440. tempVec.y *= distToJoint;
  65441. tempVec.z *= distToJoint;
  65442. }
  65443. if (bone.getParent()) {
  65444. tempVec.addInPlace(mesh.getAbsolutePosition());
  65445. bone.setAbsolutePosition(tempVec, boneMesh);
  65446. }
  65447. else {
  65448. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65449. boneMesh.position.x -= tempVec.x;
  65450. boneMesh.position.y -= tempVec.y;
  65451. boneMesh.position.z -= tempVec.z;
  65452. }
  65453. };
  65454. /**
  65455. * Sync impostor to a bone
  65456. * @param bone The bone that the impostor will be synced to.
  65457. * @param boneMesh The mesh that the bone is influencing.
  65458. * @param jointPivot The pivot of the joint / bone in local space.
  65459. * @param distToJoint Optional distance from the impostor to the joint.
  65460. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65461. * @param boneAxis Optional vector3 axis the bone is aligned with
  65462. */
  65463. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65464. var mesh = this.object;
  65465. if (mesh.rotationQuaternion) {
  65466. if (adjustRotation) {
  65467. var tempQuat = PhysicsImpostor._tmpQuat;
  65468. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65469. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65470. }
  65471. else {
  65472. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65473. }
  65474. }
  65475. var pos = PhysicsImpostor._tmpVecs[0];
  65476. var boneDir = PhysicsImpostor._tmpVecs[1];
  65477. if (!boneAxis) {
  65478. boneAxis = PhysicsImpostor._tmpVecs[2];
  65479. boneAxis.x = 0;
  65480. boneAxis.y = 1;
  65481. boneAxis.z = 0;
  65482. }
  65483. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65484. bone.getAbsolutePositionToRef(boneMesh, pos);
  65485. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65486. distToJoint = jointPivot.length();
  65487. }
  65488. if (distToJoint !== undefined && distToJoint !== null) {
  65489. pos.x += boneDir.x * distToJoint;
  65490. pos.y += boneDir.y * distToJoint;
  65491. pos.z += boneDir.z * distToJoint;
  65492. }
  65493. mesh.setAbsolutePosition(pos);
  65494. };
  65495. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65496. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65497. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65498. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65499. //Impostor types
  65500. PhysicsImpostor.NoImpostor = 0;
  65501. PhysicsImpostor.SphereImpostor = 1;
  65502. PhysicsImpostor.BoxImpostor = 2;
  65503. PhysicsImpostor.PlaneImpostor = 3;
  65504. PhysicsImpostor.MeshImpostor = 4;
  65505. PhysicsImpostor.CylinderImpostor = 7;
  65506. PhysicsImpostor.ParticleImpostor = 8;
  65507. PhysicsImpostor.HeightmapImpostor = 9;
  65508. return PhysicsImpostor;
  65509. }());
  65510. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65511. })(BABYLON || (BABYLON = {}));
  65512. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65513. var BABYLON;
  65514. (function (BABYLON) {
  65515. var PhysicsEngine = /** @class */ (function () {
  65516. function PhysicsEngine(gravity, _physicsPlugin) {
  65517. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65518. this._physicsPlugin = _physicsPlugin;
  65519. //new methods and parameters
  65520. this._impostors = [];
  65521. this._joints = [];
  65522. if (!this._physicsPlugin.isSupported()) {
  65523. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65524. + "Please make sure it is included.");
  65525. }
  65526. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65527. this.setGravity(gravity);
  65528. this.setTimeStep();
  65529. }
  65530. PhysicsEngine.prototype.setGravity = function (gravity) {
  65531. this.gravity = gravity;
  65532. this._physicsPlugin.setGravity(this.gravity);
  65533. };
  65534. /**
  65535. * Set the time step of the physics engine.
  65536. * default is 1/60.
  65537. * To slow it down, enter 1/600 for example.
  65538. * To speed it up, 1/30
  65539. * @param {number} newTimeStep the new timestep to apply to this world.
  65540. */
  65541. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65542. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65543. this._physicsPlugin.setTimeStep(newTimeStep);
  65544. };
  65545. /**
  65546. * Get the time step of the physics engine.
  65547. */
  65548. PhysicsEngine.prototype.getTimeStep = function () {
  65549. return this._physicsPlugin.getTimeStep();
  65550. };
  65551. PhysicsEngine.prototype.dispose = function () {
  65552. this._impostors.forEach(function (impostor) {
  65553. impostor.dispose();
  65554. });
  65555. this._physicsPlugin.dispose();
  65556. };
  65557. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  65558. return this._physicsPlugin.name;
  65559. };
  65560. /**
  65561. * Adding a new impostor for the impostor tracking.
  65562. * This will be done by the impostor itself.
  65563. * @param {PhysicsImpostor} impostor the impostor to add
  65564. */
  65565. PhysicsEngine.prototype.addImpostor = function (impostor) {
  65566. impostor.uniqueId = this._impostors.push(impostor);
  65567. //if no parent, generate the body
  65568. if (!impostor.parent) {
  65569. this._physicsPlugin.generatePhysicsBody(impostor);
  65570. }
  65571. };
  65572. /**
  65573. * Remove an impostor from the engine.
  65574. * This impostor and its mesh will not longer be updated by the physics engine.
  65575. * @param {PhysicsImpostor} impostor the impostor to remove
  65576. */
  65577. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  65578. var index = this._impostors.indexOf(impostor);
  65579. if (index > -1) {
  65580. var removed = this._impostors.splice(index, 1);
  65581. //Is it needed?
  65582. if (removed.length) {
  65583. //this will also remove it from the world.
  65584. removed[0].physicsBody = null;
  65585. }
  65586. }
  65587. };
  65588. /**
  65589. * Add a joint to the physics engine
  65590. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  65591. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  65592. * @param {PhysicsJoint} the joint that will connect both impostors.
  65593. */
  65594. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  65595. var impostorJoint = {
  65596. mainImpostor: mainImpostor,
  65597. connectedImpostor: connectedImpostor,
  65598. joint: joint
  65599. };
  65600. joint.physicsPlugin = this._physicsPlugin;
  65601. this._joints.push(impostorJoint);
  65602. this._physicsPlugin.generateJoint(impostorJoint);
  65603. };
  65604. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  65605. var matchingJoints = this._joints.filter(function (impostorJoint) {
  65606. return (impostorJoint.connectedImpostor === connectedImpostor
  65607. && impostorJoint.joint === joint
  65608. && impostorJoint.mainImpostor === mainImpostor);
  65609. });
  65610. if (matchingJoints.length) {
  65611. this._physicsPlugin.removeJoint(matchingJoints[0]);
  65612. //TODO remove it from the list as well
  65613. }
  65614. };
  65615. /**
  65616. * Called by the scene. no need to call it.
  65617. */
  65618. PhysicsEngine.prototype._step = function (delta) {
  65619. var _this = this;
  65620. //check if any mesh has no body / requires an update
  65621. this._impostors.forEach(function (impostor) {
  65622. if (impostor.isBodyInitRequired()) {
  65623. _this._physicsPlugin.generatePhysicsBody(impostor);
  65624. }
  65625. });
  65626. if (delta > 0.1) {
  65627. delta = 0.1;
  65628. }
  65629. else if (delta <= 0) {
  65630. delta = 1.0 / 60.0;
  65631. }
  65632. this._physicsPlugin.executeStep(delta, this._impostors);
  65633. };
  65634. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  65635. return this._physicsPlugin;
  65636. };
  65637. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  65638. for (var i = 0; i < this._impostors.length; ++i) {
  65639. if (this._impostors[i].object === object) {
  65640. return this._impostors[i];
  65641. }
  65642. }
  65643. return null;
  65644. };
  65645. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  65646. for (var i = 0; i < this._impostors.length; ++i) {
  65647. if (this._impostors[i].physicsBody === body) {
  65648. return this._impostors[i];
  65649. }
  65650. }
  65651. return null;
  65652. };
  65653. // Statics
  65654. PhysicsEngine.Epsilon = 0.001;
  65655. return PhysicsEngine;
  65656. }());
  65657. BABYLON.PhysicsEngine = PhysicsEngine;
  65658. })(BABYLON || (BABYLON = {}));
  65659. //# sourceMappingURL=babylon.physicsEngine.js.map
  65660. var BABYLON;
  65661. (function (BABYLON) {
  65662. var CannonJSPlugin = /** @class */ (function () {
  65663. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  65664. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  65665. if (iterations === void 0) { iterations = 10; }
  65666. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  65667. this.name = "CannonJSPlugin";
  65668. this._physicsMaterials = new Array();
  65669. this._fixedTimeStep = 1 / 60;
  65670. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  65671. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  65672. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  65673. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  65674. this._tmpPosition = BABYLON.Vector3.Zero();
  65675. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  65676. this._tmpUnityRotation = new BABYLON.Quaternion();
  65677. if (!this.isSupported()) {
  65678. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  65679. return;
  65680. }
  65681. this.world = new this.BJSCANNON.World();
  65682. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  65683. this.world.solver.iterations = iterations;
  65684. }
  65685. CannonJSPlugin.prototype.setGravity = function (gravity) {
  65686. this.world.gravity.copy(gravity);
  65687. };
  65688. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  65689. this._fixedTimeStep = timeStep;
  65690. };
  65691. CannonJSPlugin.prototype.getTimeStep = function () {
  65692. return this._fixedTimeStep;
  65693. };
  65694. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  65695. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  65696. };
  65697. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  65698. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65699. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65700. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  65701. };
  65702. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  65703. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65704. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  65705. impostor.physicsBody.applyForce(impulse, worldPoint);
  65706. };
  65707. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  65708. //parent-child relationship. Does this impostor has a parent impostor?
  65709. if (impostor.parent) {
  65710. if (impostor.physicsBody) {
  65711. this.removePhysicsBody(impostor);
  65712. //TODO is that needed?
  65713. impostor.forceUpdate();
  65714. }
  65715. return;
  65716. }
  65717. //should a new body be created for this impostor?
  65718. if (impostor.isBodyInitRequired()) {
  65719. var shape = this._createShape(impostor);
  65720. //unregister events, if body is being changed
  65721. var oldBody = impostor.physicsBody;
  65722. if (oldBody) {
  65723. this.removePhysicsBody(impostor);
  65724. }
  65725. //create the body and material
  65726. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  65727. var bodyCreationObject = {
  65728. mass: impostor.getParam("mass"),
  65729. material: material
  65730. };
  65731. // A simple extend, in case native options were used.
  65732. var nativeOptions = impostor.getParam("nativeOptions");
  65733. for (var key in nativeOptions) {
  65734. if (nativeOptions.hasOwnProperty(key)) {
  65735. bodyCreationObject[key] = nativeOptions[key];
  65736. }
  65737. }
  65738. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  65739. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  65740. this.world.addEventListener("preStep", impostor.beforeStep);
  65741. this.world.addEventListener("postStep", impostor.afterStep);
  65742. impostor.physicsBody.addShape(shape);
  65743. this.world.add(impostor.physicsBody);
  65744. //try to keep the body moving in the right direction by taking old properties.
  65745. //Should be tested!
  65746. if (oldBody) {
  65747. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  65748. impostor.physicsBody[param].copy(oldBody[param]);
  65749. });
  65750. }
  65751. this._processChildMeshes(impostor);
  65752. }
  65753. //now update the body's transformation
  65754. this._updatePhysicsBodyTransformation(impostor);
  65755. };
  65756. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  65757. var _this = this;
  65758. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  65759. var currentRotation = mainImpostor.object.rotationQuaternion;
  65760. if (meshChildren.length) {
  65761. var processMesh = function (localPosition, mesh) {
  65762. if (!currentRotation || !mesh.rotationQuaternion) {
  65763. return;
  65764. }
  65765. var childImpostor = mesh.getPhysicsImpostor();
  65766. if (childImpostor) {
  65767. var parent = childImpostor.parent;
  65768. if (parent !== mainImpostor) {
  65769. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  65770. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  65771. if (childImpostor.physicsBody) {
  65772. _this.removePhysicsBody(childImpostor);
  65773. childImpostor.physicsBody = null;
  65774. }
  65775. childImpostor.parent = mainImpostor;
  65776. childImpostor.resetUpdateFlags();
  65777. 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));
  65778. //Add the mass of the children.
  65779. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  65780. }
  65781. }
  65782. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  65783. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  65784. };
  65785. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  65786. }
  65787. };
  65788. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  65789. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  65790. this.world.removeEventListener("preStep", impostor.beforeStep);
  65791. this.world.removeEventListener("postStep", impostor.afterStep);
  65792. this.world.remove(impostor.physicsBody);
  65793. };
  65794. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  65795. var mainBody = impostorJoint.mainImpostor.physicsBody;
  65796. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  65797. if (!mainBody || !connectedBody) {
  65798. return;
  65799. }
  65800. var constraint;
  65801. var jointData = impostorJoint.joint.jointData;
  65802. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  65803. var constraintData = {
  65804. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  65805. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  65806. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  65807. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  65808. maxForce: jointData.nativeParams.maxForce,
  65809. collideConnected: !!jointData.collision
  65810. };
  65811. switch (impostorJoint.joint.type) {
  65812. case BABYLON.PhysicsJoint.HingeJoint:
  65813. case BABYLON.PhysicsJoint.Hinge2Joint:
  65814. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  65815. break;
  65816. case BABYLON.PhysicsJoint.DistanceJoint:
  65817. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  65818. break;
  65819. case BABYLON.PhysicsJoint.SpringJoint:
  65820. var springData = jointData;
  65821. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  65822. restLength: springData.length,
  65823. stiffness: springData.stiffness,
  65824. damping: springData.damping,
  65825. localAnchorA: constraintData.pivotA,
  65826. localAnchorB: constraintData.pivotB
  65827. });
  65828. break;
  65829. case BABYLON.PhysicsJoint.LockJoint:
  65830. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  65831. break;
  65832. case BABYLON.PhysicsJoint.PointToPointJoint:
  65833. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  65834. default:
  65835. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  65836. break;
  65837. }
  65838. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  65839. constraint.collideConnected = !!jointData.collision;
  65840. impostorJoint.joint.physicsJoint = constraint;
  65841. //don't add spring as constraint, as it is not one.
  65842. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  65843. this.world.addConstraint(constraint);
  65844. }
  65845. else {
  65846. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  65847. constraint.applyForce();
  65848. });
  65849. }
  65850. };
  65851. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  65852. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  65853. };
  65854. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  65855. var index;
  65856. var mat;
  65857. for (index = 0; index < this._physicsMaterials.length; index++) {
  65858. mat = this._physicsMaterials[index];
  65859. if (mat.friction === friction && mat.restitution === restitution) {
  65860. return mat;
  65861. }
  65862. }
  65863. var currentMat = new this.BJSCANNON.Material(name);
  65864. currentMat.friction = friction;
  65865. currentMat.restitution = restitution;
  65866. this._physicsMaterials.push(currentMat);
  65867. return currentMat;
  65868. };
  65869. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  65870. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65871. };
  65872. CannonJSPlugin.prototype._createShape = function (impostor) {
  65873. var object = impostor.object;
  65874. var returnValue;
  65875. var extendSize = impostor.getObjectExtendSize();
  65876. switch (impostor.type) {
  65877. case BABYLON.PhysicsImpostor.SphereImpostor:
  65878. var radiusX = extendSize.x;
  65879. var radiusY = extendSize.y;
  65880. var radiusZ = extendSize.z;
  65881. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  65882. break;
  65883. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  65884. case BABYLON.PhysicsImpostor.CylinderImpostor:
  65885. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  65886. break;
  65887. case BABYLON.PhysicsImpostor.BoxImpostor:
  65888. var box = extendSize.scale(0.5);
  65889. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  65890. break;
  65891. case BABYLON.PhysicsImpostor.PlaneImpostor:
  65892. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  65893. returnValue = new this.BJSCANNON.Plane();
  65894. break;
  65895. case BABYLON.PhysicsImpostor.MeshImpostor:
  65896. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  65897. var rawFaces = object.getIndices ? object.getIndices() : [];
  65898. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  65899. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  65900. break;
  65901. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  65902. returnValue = this._createHeightmap(object);
  65903. break;
  65904. case BABYLON.PhysicsImpostor.ParticleImpostor:
  65905. returnValue = new this.BJSCANNON.Particle();
  65906. break;
  65907. }
  65908. return returnValue;
  65909. };
  65910. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  65911. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  65912. var matrix = new Array();
  65913. //For now pointDepth will not be used and will be automatically calculated.
  65914. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  65915. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  65916. var boundingInfo = (object.getBoundingInfo());
  65917. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.z);
  65918. var minY = boundingInfo.boundingBox.extendSizeWorld.y;
  65919. var elementSize = dim * 2 / arraySize;
  65920. for (var i = 0; i < pos.length; i = i + 3) {
  65921. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  65922. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  65923. var y = pos[i + 1] + minY;
  65924. if (!matrix[x]) {
  65925. matrix[x] = [];
  65926. }
  65927. if (!matrix[x][z]) {
  65928. matrix[x][z] = y;
  65929. }
  65930. matrix[x][z] = Math.max(y, matrix[x][z]);
  65931. }
  65932. for (var x = 0; x <= arraySize; ++x) {
  65933. if (!matrix[x]) {
  65934. var loc = 1;
  65935. while (!matrix[(x + loc) % arraySize]) {
  65936. loc++;
  65937. }
  65938. matrix[x] = matrix[(x + loc) % arraySize].slice();
  65939. //console.log("missing x", x);
  65940. }
  65941. for (var z = 0; z <= arraySize; ++z) {
  65942. if (!matrix[x][z]) {
  65943. var loc = 1;
  65944. var newValue;
  65945. while (newValue === undefined) {
  65946. newValue = matrix[x][(z + loc++) % arraySize];
  65947. }
  65948. matrix[x][z] = newValue;
  65949. }
  65950. }
  65951. }
  65952. var shape = new this.BJSCANNON.Heightfield(matrix, {
  65953. elementSize: elementSize
  65954. });
  65955. //For future reference, needed for body transformation
  65956. shape.minY = minY;
  65957. return shape;
  65958. };
  65959. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  65960. var object = impostor.object;
  65961. //make sure it is updated...
  65962. object.computeWorldMatrix && object.computeWorldMatrix(true);
  65963. // The delta between the mesh position and the mesh bounding box center
  65964. var center = impostor.getObjectCenter();
  65965. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  65966. this._tmpPosition.copyFrom(center);
  65967. var quaternion = object.rotationQuaternion;
  65968. if (!quaternion) {
  65969. return;
  65970. }
  65971. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  65972. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  65973. //-90 DEG in X, precalculated
  65974. quaternion = quaternion.multiply(this._minus90X);
  65975. //Invert! (Precalculated, 90 deg in X)
  65976. //No need to clone. this will never change.
  65977. impostor.setDeltaRotation(this._plus90X);
  65978. }
  65979. //If it is a heightfield, if should be centered.
  65980. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  65981. var mesh = object;
  65982. var boundingInfo = mesh.getBoundingInfo();
  65983. //calculate the correct body position:
  65984. var rotationQuaternion = mesh.rotationQuaternion;
  65985. mesh.rotationQuaternion = this._tmpUnityRotation;
  65986. mesh.computeWorldMatrix(true);
  65987. //get original center with no rotation
  65988. var c = center.clone();
  65989. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  65990. //rotation is back
  65991. mesh.rotationQuaternion = rotationQuaternion;
  65992. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  65993. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  65994. mesh.setPivotMatrix(p);
  65995. mesh.computeWorldMatrix(true);
  65996. //calculate the translation
  65997. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  65998. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  65999. //add it inverted to the delta
  66000. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66001. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66002. mesh.setPivotMatrix(oldPivot);
  66003. mesh.computeWorldMatrix(true);
  66004. }
  66005. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66006. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66007. this._tmpPosition.copyFrom(object.position);
  66008. }
  66009. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66010. //Now update the impostor object
  66011. impostor.physicsBody.position.copy(this._tmpPosition);
  66012. impostor.physicsBody.quaternion.copy(quaternion);
  66013. };
  66014. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66015. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66016. if (impostor.object.rotationQuaternion) {
  66017. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66018. }
  66019. };
  66020. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66021. impostor.physicsBody.position.copy(newPosition);
  66022. impostor.physicsBody.quaternion.copy(newRotation);
  66023. };
  66024. CannonJSPlugin.prototype.isSupported = function () {
  66025. return this.BJSCANNON !== undefined;
  66026. };
  66027. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66028. impostor.physicsBody.velocity.copy(velocity);
  66029. };
  66030. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66031. impostor.physicsBody.angularVelocity.copy(velocity);
  66032. };
  66033. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66034. var v = impostor.physicsBody.velocity;
  66035. if (!v) {
  66036. return null;
  66037. }
  66038. return new BABYLON.Vector3(v.x, v.y, v.z);
  66039. };
  66040. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66041. var v = impostor.physicsBody.angularVelocity;
  66042. if (!v) {
  66043. return null;
  66044. }
  66045. return new BABYLON.Vector3(v.x, v.y, v.z);
  66046. };
  66047. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66048. impostor.physicsBody.mass = mass;
  66049. impostor.physicsBody.updateMassProperties();
  66050. };
  66051. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66052. return impostor.physicsBody.mass;
  66053. };
  66054. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66055. return impostor.physicsBody.material.friction;
  66056. };
  66057. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66058. impostor.physicsBody.material.friction = friction;
  66059. };
  66060. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66061. return impostor.physicsBody.material.restitution;
  66062. };
  66063. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66064. impostor.physicsBody.material.restitution = restitution;
  66065. };
  66066. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66067. impostor.physicsBody.sleep();
  66068. };
  66069. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66070. impostor.physicsBody.wakeUp();
  66071. };
  66072. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66073. joint.physicsJoint.distance = maxDistance;
  66074. };
  66075. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66076. // if (!motorIndex) {
  66077. // joint.physicsJoint.enableMotor();
  66078. // }
  66079. // }
  66080. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66081. // if (!motorIndex) {
  66082. // joint.physicsJoint.disableMotor();
  66083. // }
  66084. // }
  66085. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66086. if (!motorIndex) {
  66087. joint.physicsJoint.enableMotor();
  66088. joint.physicsJoint.setMotorSpeed(speed);
  66089. if (maxForce) {
  66090. this.setLimit(joint, maxForce);
  66091. }
  66092. }
  66093. };
  66094. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66095. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66096. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66097. };
  66098. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66099. var body = impostor.physicsBody;
  66100. mesh.position.x = body.position.x;
  66101. mesh.position.y = body.position.y;
  66102. mesh.position.z = body.position.z;
  66103. if (mesh.rotationQuaternion) {
  66104. mesh.rotationQuaternion.x = body.quaternion.x;
  66105. mesh.rotationQuaternion.y = body.quaternion.y;
  66106. mesh.rotationQuaternion.z = body.quaternion.z;
  66107. mesh.rotationQuaternion.w = body.quaternion.w;
  66108. }
  66109. };
  66110. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66111. var shape = impostor.physicsBody.shapes[0];
  66112. return shape.boundingSphereRadius;
  66113. };
  66114. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66115. var shape = impostor.physicsBody.shapes[0];
  66116. result.x = shape.halfExtents.x * 2;
  66117. result.y = shape.halfExtents.y * 2;
  66118. result.z = shape.halfExtents.z * 2;
  66119. };
  66120. CannonJSPlugin.prototype.dispose = function () {
  66121. };
  66122. return CannonJSPlugin;
  66123. }());
  66124. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66125. })(BABYLON || (BABYLON = {}));
  66126. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66127. var BABYLON;
  66128. (function (BABYLON) {
  66129. var OimoJSPlugin = /** @class */ (function () {
  66130. function OimoJSPlugin(iterations) {
  66131. this.name = "OimoJSPlugin";
  66132. this._tmpImpostorsArray = [];
  66133. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66134. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66135. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66136. this.world.worldscale(1);
  66137. this.world.clear();
  66138. //making sure no stats are calculated
  66139. this.world.isNoStat = true;
  66140. }
  66141. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66142. this.world.gravity.copy(gravity);
  66143. };
  66144. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66145. this.world.timeStep = timeStep;
  66146. };
  66147. OimoJSPlugin.prototype.getTimeStep = function () {
  66148. return this.world.timeStep;
  66149. };
  66150. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66151. var _this = this;
  66152. impostors.forEach(function (impostor) {
  66153. impostor.beforeStep();
  66154. });
  66155. this.world.step();
  66156. impostors.forEach(function (impostor) {
  66157. impostor.afterStep();
  66158. //update the ordered impostors array
  66159. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66160. });
  66161. //check for collisions
  66162. var contact = this.world.contacts;
  66163. while (contact !== null) {
  66164. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66165. contact = contact.next;
  66166. continue;
  66167. }
  66168. //is this body colliding with any other? get the impostor
  66169. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66170. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66171. if (!mainImpostor || !collidingImpostor) {
  66172. contact = contact.next;
  66173. continue;
  66174. }
  66175. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66176. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66177. contact = contact.next;
  66178. }
  66179. };
  66180. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66181. var mass = impostor.physicsBody.massInfo.mass;
  66182. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66183. };
  66184. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66185. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66186. this.applyImpulse(impostor, force, contactPoint);
  66187. };
  66188. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66189. var _this = this;
  66190. //parent-child relationship. Does this impostor has a parent impostor?
  66191. if (impostor.parent) {
  66192. if (impostor.physicsBody) {
  66193. this.removePhysicsBody(impostor);
  66194. //TODO is that needed?
  66195. impostor.forceUpdate();
  66196. }
  66197. return;
  66198. }
  66199. if (impostor.isBodyInitRequired()) {
  66200. var bodyConfig = {
  66201. name: impostor.uniqueId,
  66202. //Oimo must have mass, also for static objects.
  66203. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66204. size: [],
  66205. type: [],
  66206. pos: [],
  66207. rot: [],
  66208. move: impostor.getParam("mass") !== 0,
  66209. //Supporting older versions of Oimo
  66210. world: this.world
  66211. };
  66212. var impostors = [impostor];
  66213. var addToArray = function (parent) {
  66214. if (!parent.getChildMeshes)
  66215. return;
  66216. parent.getChildMeshes().forEach(function (m) {
  66217. if (m.physicsImpostor) {
  66218. impostors.push(m.physicsImpostor);
  66219. //m.physicsImpostor._init();
  66220. }
  66221. });
  66222. };
  66223. addToArray(impostor.object);
  66224. var checkWithEpsilon_1 = function (value) {
  66225. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66226. };
  66227. impostors.forEach(function (i) {
  66228. if (!impostor.object.rotationQuaternion) {
  66229. return;
  66230. }
  66231. //get the correct bounding box
  66232. var oldQuaternion = i.object.rotationQuaternion;
  66233. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66234. x: impostor.object.rotationQuaternion.x,
  66235. y: impostor.object.rotationQuaternion.y,
  66236. z: impostor.object.rotationQuaternion.z,
  66237. s: impostor.object.rotationQuaternion.w
  66238. });
  66239. var extendSize = i.getObjectExtendSize();
  66240. if (i === impostor) {
  66241. var center = impostor.getObjectCenter();
  66242. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66243. //Can also use Array.prototype.push.apply
  66244. bodyConfig.pos.push(center.x);
  66245. bodyConfig.pos.push(center.y);
  66246. bodyConfig.pos.push(center.z);
  66247. //tmp solution
  66248. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66249. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66250. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66251. }
  66252. else {
  66253. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66254. bodyConfig.pos.push(localPosition.x);
  66255. bodyConfig.pos.push(localPosition.y);
  66256. bodyConfig.pos.push(localPosition.z);
  66257. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66258. bodyConfig.rot.push(0);
  66259. bodyConfig.rot.push(0);
  66260. bodyConfig.rot.push(0);
  66261. }
  66262. // register mesh
  66263. switch (i.type) {
  66264. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66265. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66266. case BABYLON.PhysicsImpostor.SphereImpostor:
  66267. var radiusX = extendSize.x;
  66268. var radiusY = extendSize.y;
  66269. var radiusZ = extendSize.z;
  66270. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66271. bodyConfig.type.push('sphere');
  66272. //due to the way oimo works with compounds, add 3 times
  66273. bodyConfig.size.push(size);
  66274. bodyConfig.size.push(size);
  66275. bodyConfig.size.push(size);
  66276. break;
  66277. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66278. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66279. var sizeY = checkWithEpsilon_1(extendSize.y);
  66280. bodyConfig.type.push('cylinder');
  66281. bodyConfig.size.push(sizeX);
  66282. bodyConfig.size.push(sizeY);
  66283. //due to the way oimo works with compounds, add one more value.
  66284. bodyConfig.size.push(sizeY);
  66285. break;
  66286. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66287. case BABYLON.PhysicsImpostor.BoxImpostor:
  66288. default:
  66289. var sizeX = checkWithEpsilon_1(extendSize.x);
  66290. var sizeY = checkWithEpsilon_1(extendSize.y);
  66291. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66292. bodyConfig.type.push('box');
  66293. bodyConfig.size.push(sizeX);
  66294. bodyConfig.size.push(sizeY);
  66295. bodyConfig.size.push(sizeZ);
  66296. break;
  66297. }
  66298. //actually not needed, but hey...
  66299. i.object.rotationQuaternion = oldQuaternion;
  66300. });
  66301. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66302. }
  66303. else {
  66304. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66305. }
  66306. impostor.setDeltaPosition(this._tmpPositionVector);
  66307. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66308. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66309. };
  66310. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66311. //impostor.physicsBody.dispose();
  66312. //Same as : (older oimo versions)
  66313. this.world.removeRigidBody(impostor.physicsBody);
  66314. };
  66315. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66316. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66317. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66318. if (!mainBody || !connectedBody) {
  66319. return;
  66320. }
  66321. var jointData = impostorJoint.joint.jointData;
  66322. var options = jointData.nativeParams || {};
  66323. var type;
  66324. var nativeJointData = {
  66325. body1: mainBody,
  66326. body2: connectedBody,
  66327. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66328. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66329. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66330. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66331. min: options.min,
  66332. max: options.max,
  66333. collision: options.collision || jointData.collision,
  66334. spring: options.spring,
  66335. //supporting older version of Oimo
  66336. world: this.world
  66337. };
  66338. switch (impostorJoint.joint.type) {
  66339. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66340. type = "jointBall";
  66341. break;
  66342. case BABYLON.PhysicsJoint.SpringJoint:
  66343. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66344. var springData = jointData;
  66345. nativeJointData.min = springData.length || nativeJointData.min;
  66346. //Max should also be set, just make sure it is at least min
  66347. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66348. case BABYLON.PhysicsJoint.DistanceJoint:
  66349. type = "jointDistance";
  66350. nativeJointData.max = jointData.maxDistance;
  66351. break;
  66352. case BABYLON.PhysicsJoint.PrismaticJoint:
  66353. type = "jointPrisme";
  66354. break;
  66355. case BABYLON.PhysicsJoint.SliderJoint:
  66356. type = "jointSlide";
  66357. break;
  66358. case BABYLON.PhysicsJoint.WheelJoint:
  66359. type = "jointWheel";
  66360. break;
  66361. case BABYLON.PhysicsJoint.HingeJoint:
  66362. default:
  66363. type = "jointHinge";
  66364. break;
  66365. }
  66366. nativeJointData.type = type;
  66367. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66368. };
  66369. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66370. //Bug in Oimo prevents us from disposing a joint in the playground
  66371. //joint.joint.physicsJoint.dispose();
  66372. //So we will bruteforce it!
  66373. try {
  66374. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66375. }
  66376. catch (e) {
  66377. BABYLON.Tools.Warn(e);
  66378. }
  66379. };
  66380. OimoJSPlugin.prototype.isSupported = function () {
  66381. return this.BJSOIMO !== undefined;
  66382. };
  66383. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66384. if (!impostor.physicsBody.sleeping) {
  66385. //TODO check that
  66386. if (impostor.physicsBody.shapes.next) {
  66387. var parentShape = this._getLastShape(impostor.physicsBody);
  66388. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66389. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66390. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66391. }
  66392. else {
  66393. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66394. }
  66395. if (impostor.object.rotationQuaternion) {
  66396. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66397. impostor.object.rotationQuaternion.normalize();
  66398. }
  66399. }
  66400. };
  66401. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66402. var body = impostor.physicsBody;
  66403. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66404. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66405. body.syncShapes();
  66406. body.awake();
  66407. };
  66408. OimoJSPlugin.prototype._getLastShape = function (body) {
  66409. var lastShape = body.shapes;
  66410. while (lastShape.next) {
  66411. lastShape = lastShape.next;
  66412. }
  66413. return lastShape;
  66414. };
  66415. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66416. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66417. };
  66418. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66419. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66420. };
  66421. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66422. var v = impostor.physicsBody.linearVelocity;
  66423. if (!v) {
  66424. return null;
  66425. }
  66426. return new BABYLON.Vector3(v.x, v.y, v.z);
  66427. };
  66428. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66429. var v = impostor.physicsBody.angularVelocity;
  66430. if (!v) {
  66431. return null;
  66432. }
  66433. return new BABYLON.Vector3(v.x, v.y, v.z);
  66434. };
  66435. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66436. var staticBody = mass === 0;
  66437. //this will actually set the body's density and not its mass.
  66438. //But this is how oimo treats the mass variable.
  66439. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66440. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66441. };
  66442. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66443. return impostor.physicsBody.shapes.density;
  66444. };
  66445. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66446. return impostor.physicsBody.shapes.friction;
  66447. };
  66448. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66449. impostor.physicsBody.shapes.friction = friction;
  66450. };
  66451. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66452. return impostor.physicsBody.shapes.restitution;
  66453. };
  66454. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66455. impostor.physicsBody.shapes.restitution = restitution;
  66456. };
  66457. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66458. impostor.physicsBody.sleep();
  66459. };
  66460. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66461. impostor.physicsBody.awake();
  66462. };
  66463. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66464. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66465. if (minDistance !== void 0) {
  66466. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66467. }
  66468. };
  66469. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66470. //TODO separate rotational and transational motors.
  66471. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66472. if (motor) {
  66473. motor.setMotor(speed, maxForce);
  66474. }
  66475. };
  66476. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66477. //TODO separate rotational and transational motors.
  66478. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66479. if (motor) {
  66480. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66481. }
  66482. };
  66483. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66484. var body = impostor.physicsBody;
  66485. mesh.position.x = body.position.x;
  66486. mesh.position.y = body.position.y;
  66487. mesh.position.z = body.position.z;
  66488. if (mesh.rotationQuaternion) {
  66489. mesh.rotationQuaternion.x = body.orientation.x;
  66490. mesh.rotationQuaternion.y = body.orientation.y;
  66491. mesh.rotationQuaternion.z = body.orientation.z;
  66492. mesh.rotationQuaternion.w = body.orientation.s;
  66493. }
  66494. };
  66495. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66496. return impostor.physicsBody.shapes.radius;
  66497. };
  66498. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66499. var shape = impostor.physicsBody.shapes;
  66500. result.x = shape.halfWidth * 2;
  66501. result.y = shape.halfHeight * 2;
  66502. result.z = shape.halfDepth * 2;
  66503. };
  66504. OimoJSPlugin.prototype.dispose = function () {
  66505. this.world.clear();
  66506. };
  66507. return OimoJSPlugin;
  66508. }());
  66509. BABYLON.OimoJSPlugin = OimoJSPlugin;
  66510. })(BABYLON || (BABYLON = {}));
  66511. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  66512. var BABYLON;
  66513. (function (BABYLON) {
  66514. var Internals;
  66515. (function (Internals) {
  66516. /*
  66517. * Based on jsTGALoader - Javascript loader for TGA file
  66518. * By Vincent Thibault
  66519. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  66520. */
  66521. var TGATools = /** @class */ (function () {
  66522. function TGATools() {
  66523. }
  66524. TGATools.GetTGAHeader = function (data) {
  66525. var offset = 0;
  66526. var header = {
  66527. id_length: data[offset++],
  66528. colormap_type: data[offset++],
  66529. image_type: data[offset++],
  66530. colormap_index: data[offset++] | data[offset++] << 8,
  66531. colormap_length: data[offset++] | data[offset++] << 8,
  66532. colormap_size: data[offset++],
  66533. origin: [
  66534. data[offset++] | data[offset++] << 8,
  66535. data[offset++] | data[offset++] << 8
  66536. ],
  66537. width: data[offset++] | data[offset++] << 8,
  66538. height: data[offset++] | data[offset++] << 8,
  66539. pixel_size: data[offset++],
  66540. flags: data[offset++]
  66541. };
  66542. return header;
  66543. };
  66544. TGATools.UploadContent = function (gl, data) {
  66545. // Not enough data to contain header ?
  66546. if (data.length < 19) {
  66547. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  66548. return;
  66549. }
  66550. // Read Header
  66551. var offset = 18;
  66552. var header = TGATools.GetTGAHeader(data);
  66553. // Assume it's a valid Targa file.
  66554. if (header.id_length + offset > data.length) {
  66555. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  66556. return;
  66557. }
  66558. // Skip not needed data
  66559. offset += header.id_length;
  66560. var use_rle = false;
  66561. var use_pal = false;
  66562. var use_rgb = false;
  66563. var use_grey = false;
  66564. // Get some informations.
  66565. switch (header.image_type) {
  66566. case TGATools._TYPE_RLE_INDEXED:
  66567. use_rle = true;
  66568. case TGATools._TYPE_INDEXED:
  66569. use_pal = true;
  66570. break;
  66571. case TGATools._TYPE_RLE_RGB:
  66572. use_rle = true;
  66573. case TGATools._TYPE_RGB:
  66574. use_rgb = true;
  66575. break;
  66576. case TGATools._TYPE_RLE_GREY:
  66577. use_rle = true;
  66578. case TGATools._TYPE_GREY:
  66579. use_grey = true;
  66580. break;
  66581. }
  66582. var pixel_data;
  66583. // var numAlphaBits = header.flags & 0xf;
  66584. var pixel_size = header.pixel_size >> 3;
  66585. var pixel_total = header.width * header.height * pixel_size;
  66586. // Read palettes
  66587. var palettes;
  66588. if (use_pal) {
  66589. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  66590. }
  66591. // Read LRE
  66592. if (use_rle) {
  66593. pixel_data = new Uint8Array(pixel_total);
  66594. var c, count, i;
  66595. var localOffset = 0;
  66596. var pixels = new Uint8Array(pixel_size);
  66597. while (offset < pixel_total && localOffset < pixel_total) {
  66598. c = data[offset++];
  66599. count = (c & 0x7f) + 1;
  66600. // RLE pixels
  66601. if (c & 0x80) {
  66602. // Bind pixel tmp array
  66603. for (i = 0; i < pixel_size; ++i) {
  66604. pixels[i] = data[offset++];
  66605. }
  66606. // Copy pixel array
  66607. for (i = 0; i < count; ++i) {
  66608. pixel_data.set(pixels, localOffset + i * pixel_size);
  66609. }
  66610. localOffset += pixel_size * count;
  66611. }
  66612. else {
  66613. count *= pixel_size;
  66614. for (i = 0; i < count; ++i) {
  66615. pixel_data[localOffset + i] = data[offset++];
  66616. }
  66617. localOffset += count;
  66618. }
  66619. }
  66620. }
  66621. else {
  66622. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  66623. }
  66624. // Load to texture
  66625. var x_start, y_start, x_step, y_step, y_end, x_end;
  66626. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  66627. default:
  66628. case TGATools._ORIGIN_UL:
  66629. x_start = 0;
  66630. x_step = 1;
  66631. x_end = header.width;
  66632. y_start = 0;
  66633. y_step = 1;
  66634. y_end = header.height;
  66635. break;
  66636. case TGATools._ORIGIN_BL:
  66637. x_start = 0;
  66638. x_step = 1;
  66639. x_end = header.width;
  66640. y_start = header.height - 1;
  66641. y_step = -1;
  66642. y_end = -1;
  66643. break;
  66644. case TGATools._ORIGIN_UR:
  66645. x_start = header.width - 1;
  66646. x_step = -1;
  66647. x_end = -1;
  66648. y_start = 0;
  66649. y_step = 1;
  66650. y_end = header.height;
  66651. break;
  66652. case TGATools._ORIGIN_BR:
  66653. x_start = header.width - 1;
  66654. x_step = -1;
  66655. x_end = -1;
  66656. y_start = header.height - 1;
  66657. y_step = -1;
  66658. y_end = -1;
  66659. break;
  66660. }
  66661. // Load the specify method
  66662. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  66663. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  66664. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  66665. };
  66666. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66667. var image = pixel_data, colormap = palettes;
  66668. var width = header.width, height = header.height;
  66669. var color, i = 0, x, y;
  66670. var imageData = new Uint8Array(width * height * 4);
  66671. for (y = y_start; y !== y_end; y += y_step) {
  66672. for (x = x_start; x !== x_end; x += x_step, i++) {
  66673. color = image[i];
  66674. imageData[(x + width * y) * 4 + 3] = 255;
  66675. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  66676. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  66677. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  66678. }
  66679. }
  66680. return imageData;
  66681. };
  66682. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66683. var image = pixel_data;
  66684. var width = header.width, height = header.height;
  66685. var color, i = 0, x, y;
  66686. var imageData = new Uint8Array(width * height * 4);
  66687. for (y = y_start; y !== y_end; y += y_step) {
  66688. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66689. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  66690. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  66691. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  66692. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  66693. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  66694. }
  66695. }
  66696. return imageData;
  66697. };
  66698. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66699. var image = pixel_data;
  66700. var width = header.width, height = header.height;
  66701. var i = 0, x, y;
  66702. var imageData = new Uint8Array(width * height * 4);
  66703. for (y = y_start; y !== y_end; y += y_step) {
  66704. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  66705. imageData[(x + width * y) * 4 + 3] = 255;
  66706. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66707. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66708. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66709. }
  66710. }
  66711. return imageData;
  66712. };
  66713. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66714. var image = pixel_data;
  66715. var width = header.width, height = header.height;
  66716. var i = 0, x, y;
  66717. var imageData = new Uint8Array(width * height * 4);
  66718. for (y = y_start; y !== y_end; y += y_step) {
  66719. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  66720. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66721. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  66722. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  66723. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  66724. }
  66725. }
  66726. return imageData;
  66727. };
  66728. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66729. var image = pixel_data;
  66730. var width = header.width, height = header.height;
  66731. var color, i = 0, x, y;
  66732. var imageData = new Uint8Array(width * height * 4);
  66733. for (y = y_start; y !== y_end; y += y_step) {
  66734. for (x = x_start; x !== x_end; x += x_step, i++) {
  66735. color = image[i];
  66736. imageData[(x + width * y) * 4 + 0] = color;
  66737. imageData[(x + width * y) * 4 + 1] = color;
  66738. imageData[(x + width * y) * 4 + 2] = color;
  66739. imageData[(x + width * y) * 4 + 3] = 255;
  66740. }
  66741. }
  66742. return imageData;
  66743. };
  66744. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  66745. var image = pixel_data;
  66746. var width = header.width, height = header.height;
  66747. var i = 0, x, y;
  66748. var imageData = new Uint8Array(width * height * 4);
  66749. for (y = y_start; y !== y_end; y += y_step) {
  66750. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  66751. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  66752. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  66753. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  66754. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  66755. }
  66756. }
  66757. return imageData;
  66758. };
  66759. //private static _TYPE_NO_DATA = 0;
  66760. TGATools._TYPE_INDEXED = 1;
  66761. TGATools._TYPE_RGB = 2;
  66762. TGATools._TYPE_GREY = 3;
  66763. TGATools._TYPE_RLE_INDEXED = 9;
  66764. TGATools._TYPE_RLE_RGB = 10;
  66765. TGATools._TYPE_RLE_GREY = 11;
  66766. TGATools._ORIGIN_MASK = 0x30;
  66767. TGATools._ORIGIN_SHIFT = 0x04;
  66768. TGATools._ORIGIN_BL = 0x00;
  66769. TGATools._ORIGIN_BR = 0x01;
  66770. TGATools._ORIGIN_UL = 0x02;
  66771. TGATools._ORIGIN_UR = 0x03;
  66772. return TGATools;
  66773. }());
  66774. Internals.TGATools = TGATools;
  66775. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66776. })(BABYLON || (BABYLON = {}));
  66777. //# sourceMappingURL=babylon.tga.js.map
  66778. var BABYLON;
  66779. (function (BABYLON) {
  66780. var Internals;
  66781. (function (Internals) {
  66782. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  66783. // All values and structures referenced from:
  66784. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  66785. var DDS_MAGIC = 0x20534444;
  66786. var
  66787. //DDSD_CAPS = 0x1,
  66788. //DDSD_HEIGHT = 0x2,
  66789. //DDSD_WIDTH = 0x4,
  66790. //DDSD_PITCH = 0x8,
  66791. //DDSD_PIXELFORMAT = 0x1000,
  66792. DDSD_MIPMAPCOUNT = 0x20000;
  66793. //DDSD_LINEARSIZE = 0x80000,
  66794. //DDSD_DEPTH = 0x800000;
  66795. // var DDSCAPS_COMPLEX = 0x8,
  66796. // DDSCAPS_MIPMAP = 0x400000,
  66797. // DDSCAPS_TEXTURE = 0x1000;
  66798. var DDSCAPS2_CUBEMAP = 0x200;
  66799. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  66800. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  66801. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  66802. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  66803. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  66804. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  66805. // DDSCAPS2_VOLUME = 0x200000;
  66806. var
  66807. //DDPF_ALPHAPIXELS = 0x1,
  66808. //DDPF_ALPHA = 0x2,
  66809. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  66810. //DDPF_YUV = 0x200,
  66811. DDPF_LUMINANCE = 0x20000;
  66812. function FourCCToInt32(value) {
  66813. return value.charCodeAt(0) +
  66814. (value.charCodeAt(1) << 8) +
  66815. (value.charCodeAt(2) << 16) +
  66816. (value.charCodeAt(3) << 24);
  66817. }
  66818. function Int32ToFourCC(value) {
  66819. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  66820. }
  66821. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  66822. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  66823. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  66824. var FOURCC_DX10 = FourCCToInt32("DX10");
  66825. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  66826. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  66827. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  66828. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  66829. var headerLengthInt = 31; // The header length in 32 bit ints
  66830. // Offsets into the header array
  66831. var off_magic = 0;
  66832. var off_size = 1;
  66833. var off_flags = 2;
  66834. var off_height = 3;
  66835. var off_width = 4;
  66836. var off_mipmapCount = 7;
  66837. var off_pfFlags = 20;
  66838. var off_pfFourCC = 21;
  66839. var off_RGBbpp = 22;
  66840. // var off_RMask = 23;
  66841. // var off_GMask = 24;
  66842. // var off_BMask = 25;
  66843. // var off_AMask = 26;
  66844. // var off_caps1 = 27;
  66845. var off_caps2 = 28;
  66846. // var off_caps3 = 29;
  66847. // var off_caps4 = 30;
  66848. var off_dxgiFormat = 32;
  66849. ;
  66850. var DDSTools = /** @class */ (function () {
  66851. function DDSTools() {
  66852. }
  66853. DDSTools.GetDDSInfo = function (arrayBuffer) {
  66854. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  66855. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  66856. var mipmapCount = 1;
  66857. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  66858. mipmapCount = Math.max(1, header[off_mipmapCount]);
  66859. }
  66860. var fourCC = header[off_pfFourCC];
  66861. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  66862. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66863. switch (fourCC) {
  66864. case FOURCC_D3DFMT_R16G16B16A16F:
  66865. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66866. break;
  66867. case FOURCC_D3DFMT_R32G32B32A32F:
  66868. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66869. break;
  66870. case FOURCC_DX10:
  66871. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  66872. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66873. break;
  66874. }
  66875. }
  66876. return {
  66877. width: header[off_width],
  66878. height: header[off_height],
  66879. mipmapCount: mipmapCount,
  66880. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  66881. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  66882. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  66883. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  66884. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  66885. dxgiFormat: dxgiFormat,
  66886. textureType: textureType
  66887. };
  66888. };
  66889. DDSTools._ToHalfFloat = function (value) {
  66890. if (!DDSTools._FloatView) {
  66891. DDSTools._FloatView = new Float32Array(1);
  66892. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  66893. }
  66894. DDSTools._FloatView[0] = value;
  66895. var x = DDSTools._Int32View[0];
  66896. var bits = (x >> 16) & 0x8000; /* Get the sign */
  66897. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  66898. var e = (x >> 23) & 0xff; /* Using int is faster here */
  66899. /* If zero, or denormal, or exponent underflows too much for a denormal
  66900. * half, return signed zero. */
  66901. if (e < 103) {
  66902. return bits;
  66903. }
  66904. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  66905. if (e > 142) {
  66906. bits |= 0x7c00;
  66907. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  66908. * not Inf, so make sure we set one mantissa bit too. */
  66909. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  66910. return bits;
  66911. }
  66912. /* If exponent underflows but not too much, return a denormal */
  66913. if (e < 113) {
  66914. m |= 0x0800;
  66915. /* Extra rounding may overflow and set mantissa to 0 and exponent
  66916. * to 1, which is OK. */
  66917. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  66918. return bits;
  66919. }
  66920. bits |= ((e - 112) << 10) | (m >> 1);
  66921. bits += m & 1;
  66922. return bits;
  66923. };
  66924. DDSTools._FromHalfFloat = function (value) {
  66925. var s = (value & 0x8000) >> 15;
  66926. var e = (value & 0x7C00) >> 10;
  66927. var f = value & 0x03FF;
  66928. if (e === 0) {
  66929. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  66930. }
  66931. else if (e == 0x1F) {
  66932. return f ? NaN : ((s ? -1 : 1) * Infinity);
  66933. }
  66934. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  66935. };
  66936. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66937. var destArray = new Float32Array(dataLength);
  66938. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66939. var index = 0;
  66940. for (var y = 0; y < height; y++) {
  66941. for (var x = 0; x < width; x++) {
  66942. var srcPos = (x + y * width) * 4;
  66943. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  66944. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  66945. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  66946. if (DDSTools.StoreLODInAlphaChannel) {
  66947. destArray[index + 3] = lod;
  66948. }
  66949. else {
  66950. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  66951. }
  66952. index += 4;
  66953. }
  66954. }
  66955. return destArray;
  66956. };
  66957. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66958. if (DDSTools.StoreLODInAlphaChannel) {
  66959. var destArray = new Uint16Array(dataLength);
  66960. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  66961. var index = 0;
  66962. for (var y = 0; y < height; y++) {
  66963. for (var x = 0; x < width; x++) {
  66964. var srcPos = (x + y * width) * 4;
  66965. destArray[index] = srcData[srcPos];
  66966. destArray[index + 1] = srcData[srcPos + 1];
  66967. destArray[index + 2] = srcData[srcPos + 2];
  66968. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  66969. index += 4;
  66970. }
  66971. }
  66972. return destArray;
  66973. }
  66974. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  66975. };
  66976. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66977. if (DDSTools.StoreLODInAlphaChannel) {
  66978. var destArray = new Float32Array(dataLength);
  66979. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66980. var index = 0;
  66981. for (var y = 0; y < height; y++) {
  66982. for (var x = 0; x < width; x++) {
  66983. var srcPos = (x + y * width) * 4;
  66984. destArray[index] = srcData[srcPos];
  66985. destArray[index + 1] = srcData[srcPos + 1];
  66986. destArray[index + 2] = srcData[srcPos + 2];
  66987. destArray[index + 3] = lod;
  66988. index += 4;
  66989. }
  66990. }
  66991. return destArray;
  66992. }
  66993. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  66994. };
  66995. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  66996. var destArray = new Uint8Array(dataLength);
  66997. var srcData = new Float32Array(arrayBuffer, dataOffset);
  66998. var index = 0;
  66999. for (var y = 0; y < height; y++) {
  67000. for (var x = 0; x < width; x++) {
  67001. var srcPos = (x + y * width) * 4;
  67002. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67003. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67004. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67005. if (DDSTools.StoreLODInAlphaChannel) {
  67006. destArray[index + 3] = lod;
  67007. }
  67008. else {
  67009. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67010. }
  67011. index += 4;
  67012. }
  67013. }
  67014. return destArray;
  67015. };
  67016. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67017. var destArray = new Uint8Array(dataLength);
  67018. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67019. var index = 0;
  67020. for (var y = 0; y < height; y++) {
  67021. for (var x = 0; x < width; x++) {
  67022. var srcPos = (x + y * width) * 4;
  67023. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67024. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67025. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67026. if (DDSTools.StoreLODInAlphaChannel) {
  67027. destArray[index + 3] = lod;
  67028. }
  67029. else {
  67030. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67031. }
  67032. index += 4;
  67033. }
  67034. }
  67035. return destArray;
  67036. };
  67037. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67038. var byteArray = new Uint8Array(dataLength);
  67039. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67040. var index = 0;
  67041. for (var y = 0; y < height; y++) {
  67042. for (var x = 0; x < width; x++) {
  67043. var srcPos = (x + y * width) * 4;
  67044. byteArray[index] = srcData[srcPos + 2];
  67045. byteArray[index + 1] = srcData[srcPos + 1];
  67046. byteArray[index + 2] = srcData[srcPos];
  67047. byteArray[index + 3] = srcData[srcPos + 3];
  67048. index += 4;
  67049. }
  67050. }
  67051. return byteArray;
  67052. };
  67053. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67054. var byteArray = new Uint8Array(dataLength);
  67055. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67056. var index = 0;
  67057. for (var y = 0; y < height; y++) {
  67058. for (var x = 0; x < width; x++) {
  67059. var srcPos = (x + y * width) * 3;
  67060. byteArray[index] = srcData[srcPos + 2];
  67061. byteArray[index + 1] = srcData[srcPos + 1];
  67062. byteArray[index + 2] = srcData[srcPos];
  67063. index += 3;
  67064. }
  67065. }
  67066. return byteArray;
  67067. };
  67068. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67069. var byteArray = new Uint8Array(dataLength);
  67070. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67071. var index = 0;
  67072. for (var y = 0; y < height; y++) {
  67073. for (var x = 0; x < width; x++) {
  67074. var srcPos = (x + y * width);
  67075. byteArray[index] = srcData[srcPos];
  67076. index++;
  67077. }
  67078. }
  67079. return byteArray;
  67080. };
  67081. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67082. if (lodIndex === void 0) { lodIndex = -1; }
  67083. var ext = engine.getCaps().s3tc;
  67084. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67085. var internalFormat = 0;
  67086. var format = 0;
  67087. var blockBytes = 1;
  67088. if (header[off_magic] != DDS_MAGIC) {
  67089. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67090. return;
  67091. }
  67092. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67093. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67094. return;
  67095. }
  67096. if (info.isCompressed && !ext) {
  67097. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67098. return;
  67099. }
  67100. var bpp = header[off_RGBbpp];
  67101. dataOffset = header[off_size] + 4;
  67102. var computeFormats = false;
  67103. if (info.isFourCC) {
  67104. fourCC = header[off_pfFourCC];
  67105. switch (fourCC) {
  67106. case FOURCC_DXT1:
  67107. blockBytes = 8;
  67108. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67109. break;
  67110. case FOURCC_DXT3:
  67111. blockBytes = 16;
  67112. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67113. break;
  67114. case FOURCC_DXT5:
  67115. blockBytes = 16;
  67116. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67117. break;
  67118. case FOURCC_D3DFMT_R16G16B16A16F:
  67119. computeFormats = true;
  67120. break;
  67121. case FOURCC_D3DFMT_R32G32B32A32F:
  67122. computeFormats = true;
  67123. break;
  67124. case FOURCC_DX10:
  67125. // There is an additionnal header so dataOffset need to be changed
  67126. dataOffset += 5 * 4; // 5 uints
  67127. var supported = false;
  67128. switch (info.dxgiFormat) {
  67129. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67130. computeFormats = true;
  67131. supported = true;
  67132. break;
  67133. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67134. info.isRGB = true;
  67135. info.isFourCC = false;
  67136. bpp = 32;
  67137. supported = true;
  67138. break;
  67139. }
  67140. if (supported) {
  67141. break;
  67142. }
  67143. default:
  67144. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67145. return;
  67146. }
  67147. }
  67148. if (computeFormats) {
  67149. format = engine._getWebGLTextureType(info.textureType);
  67150. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67151. }
  67152. mipmapCount = 1;
  67153. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67154. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67155. }
  67156. for (var face = 0; face < faces; face++) {
  67157. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67158. width = header[off_width];
  67159. height = header[off_height];
  67160. for (mip = 0; mip < mipmapCount; ++mip) {
  67161. if (lodIndex === -1 || lodIndex === mip) {
  67162. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67163. var i = (lodIndex === -1) ? mip : 0;
  67164. if (!info.isCompressed && info.isFourCC) {
  67165. dataLength = width * height * 4;
  67166. var FloatArray = null;
  67167. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67168. if (bpp === 128) {
  67169. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67170. }
  67171. else if (bpp === 64) {
  67172. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67173. }
  67174. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67175. format = engine._getWebGLTextureType(info.textureType);
  67176. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67177. }
  67178. else {
  67179. if (bpp === 128) {
  67180. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67181. }
  67182. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67183. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67184. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67185. format = engine._getWebGLTextureType(info.textureType);
  67186. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67187. }
  67188. else {
  67189. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67190. }
  67191. }
  67192. if (FloatArray) {
  67193. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67194. }
  67195. }
  67196. else if (info.isRGB) {
  67197. if (bpp === 24) {
  67198. dataLength = width * height * 3;
  67199. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67200. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67201. }
  67202. else {
  67203. dataLength = width * height * 4;
  67204. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67205. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67206. }
  67207. }
  67208. else if (info.isLuminance) {
  67209. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67210. var unpaddedRowSize = width;
  67211. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67212. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67213. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67214. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67215. }
  67216. else {
  67217. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67218. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67219. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67220. }
  67221. }
  67222. dataOffset += width * height * (bpp / 8);
  67223. width *= 0.5;
  67224. height *= 0.5;
  67225. width = Math.max(1.0, width);
  67226. height = Math.max(1.0, height);
  67227. }
  67228. }
  67229. };
  67230. DDSTools.StoreLODInAlphaChannel = false;
  67231. return DDSTools;
  67232. }());
  67233. Internals.DDSTools = DDSTools;
  67234. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67235. })(BABYLON || (BABYLON = {}));
  67236. //# sourceMappingURL=babylon.dds.js.map
  67237. var BABYLON;
  67238. (function (BABYLON) {
  67239. var Internals;
  67240. (function (Internals) {
  67241. /**
  67242. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67243. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67244. */
  67245. var KhronosTextureContainer = /** @class */ (function () {
  67246. /**
  67247. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67248. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67249. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67250. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67251. */
  67252. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67253. this.arrayBuffer = arrayBuffer;
  67254. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67255. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67256. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67257. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67258. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67259. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67260. BABYLON.Tools.Error("texture missing KTX identifier");
  67261. return;
  67262. }
  67263. // load the reset of the header in native 32 bit int
  67264. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67265. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67266. var oppositeEndianess = header[0] === 0x01020304;
  67267. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67268. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67269. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67270. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67271. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67272. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67273. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67274. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67275. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67276. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67277. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67278. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67279. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67280. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67281. if (this.glType !== 0) {
  67282. BABYLON.Tools.Error("only compressed formats currently supported");
  67283. return;
  67284. }
  67285. else {
  67286. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67287. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67288. }
  67289. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67290. BABYLON.Tools.Error("only 2D textures currently supported");
  67291. return;
  67292. }
  67293. if (this.numberOfArrayElements !== 0) {
  67294. BABYLON.Tools.Error("texture arrays not currently supported");
  67295. return;
  67296. }
  67297. if (this.numberOfFaces !== facesExpected) {
  67298. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67299. return;
  67300. }
  67301. // we now have a completely validated file, so could use existence of loadType as success
  67302. // would need to make this more elaborate & adjust checks above to support more than one load type
  67303. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67304. }
  67305. // not as fast hardware based, but will probably never need to use
  67306. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67307. return ((val & 0xFF) << 24)
  67308. | ((val & 0xFF00) << 8)
  67309. | ((val >> 8) & 0xFF00)
  67310. | ((val >> 24) & 0xFF);
  67311. };
  67312. /**
  67313. * It is assumed that the texture has already been created & is currently bound
  67314. */
  67315. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67316. switch (this.loadType) {
  67317. case KhronosTextureContainer.COMPRESSED_2D:
  67318. this._upload2DCompressedLevels(gl, loadMipmaps);
  67319. break;
  67320. case KhronosTextureContainer.TEX_2D:
  67321. case KhronosTextureContainer.COMPRESSED_3D:
  67322. case KhronosTextureContainer.TEX_3D:
  67323. }
  67324. };
  67325. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67326. // initialize width & height for level 1
  67327. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67328. var width = this.pixelWidth;
  67329. var height = this.pixelHeight;
  67330. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67331. for (var level = 0; level < mipmapCount; level++) {
  67332. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67333. for (var face = 0; face < this.numberOfFaces; face++) {
  67334. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67335. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67336. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67337. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67338. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67339. }
  67340. width = Math.max(1.0, width * 0.5);
  67341. height = Math.max(1.0, height * 0.5);
  67342. }
  67343. };
  67344. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67345. // load types
  67346. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67347. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67348. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67349. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67350. return KhronosTextureContainer;
  67351. }());
  67352. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67353. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67354. })(BABYLON || (BABYLON = {}));
  67355. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67356. var BABYLON;
  67357. (function (BABYLON) {
  67358. var Debug;
  67359. (function (Debug) {
  67360. /**
  67361. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67362. */
  67363. var SkeletonViewer = /** @class */ (function () {
  67364. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67365. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67366. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67367. this.skeleton = skeleton;
  67368. this.mesh = mesh;
  67369. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67370. this.renderingGroupId = renderingGroupId;
  67371. this.color = BABYLON.Color3.White();
  67372. this._debugLines = new Array();
  67373. this._isEnabled = false;
  67374. this._scene = scene;
  67375. this.update();
  67376. this._renderFunction = this.update.bind(this);
  67377. }
  67378. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67379. get: function () {
  67380. return this._isEnabled;
  67381. },
  67382. set: function (value) {
  67383. if (this._isEnabled === value) {
  67384. return;
  67385. }
  67386. this._isEnabled = value;
  67387. if (value) {
  67388. this._scene.registerBeforeRender(this._renderFunction);
  67389. }
  67390. else {
  67391. this._scene.unregisterBeforeRender(this._renderFunction);
  67392. }
  67393. },
  67394. enumerable: true,
  67395. configurable: true
  67396. });
  67397. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67398. if (x === void 0) { x = 0; }
  67399. if (y === void 0) { y = 0; }
  67400. if (z === void 0) { z = 0; }
  67401. var tmat = BABYLON.Tmp.Matrix[0];
  67402. var parentBone = bone.getParent();
  67403. tmat.copyFrom(bone.getLocalMatrix());
  67404. if (x !== 0 || y !== 0 || z !== 0) {
  67405. var tmat2 = BABYLON.Tmp.Matrix[1];
  67406. BABYLON.Matrix.IdentityToRef(tmat2);
  67407. tmat2.m[12] = x;
  67408. tmat2.m[13] = y;
  67409. tmat2.m[14] = z;
  67410. tmat2.multiplyToRef(tmat, tmat);
  67411. }
  67412. if (parentBone) {
  67413. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67414. }
  67415. tmat.multiplyToRef(meshMat, tmat);
  67416. position.x = tmat.m[12];
  67417. position.y = tmat.m[13];
  67418. position.z = tmat.m[14];
  67419. };
  67420. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67421. var len = bones.length;
  67422. var meshPos = this.mesh.position;
  67423. for (var i = 0; i < len; i++) {
  67424. var bone = bones[i];
  67425. var points = this._debugLines[i];
  67426. if (!points) {
  67427. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67428. this._debugLines[i] = points;
  67429. }
  67430. this._getBonePosition(points[0], bone, meshMat);
  67431. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67432. points[0].subtractInPlace(meshPos);
  67433. points[1].subtractInPlace(meshPos);
  67434. }
  67435. };
  67436. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67437. var len = bones.length;
  67438. var boneNum = 0;
  67439. var meshPos = this.mesh.position;
  67440. for (var i = len - 1; i >= 0; i--) {
  67441. var childBone = bones[i];
  67442. var parentBone = childBone.getParent();
  67443. if (!parentBone) {
  67444. continue;
  67445. }
  67446. var points = this._debugLines[boneNum];
  67447. if (!points) {
  67448. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67449. this._debugLines[boneNum] = points;
  67450. }
  67451. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67452. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67453. points[0].subtractInPlace(meshPos);
  67454. points[1].subtractInPlace(meshPos);
  67455. boneNum++;
  67456. }
  67457. };
  67458. SkeletonViewer.prototype.update = function () {
  67459. if (this.autoUpdateBonesMatrices) {
  67460. this.skeleton.computeAbsoluteTransforms();
  67461. }
  67462. if (this.skeleton.bones[0].length === undefined) {
  67463. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67464. }
  67465. else {
  67466. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67467. }
  67468. if (!this._debugMesh) {
  67469. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67470. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67471. }
  67472. else {
  67473. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67474. }
  67475. this._debugMesh.position.copyFrom(this.mesh.position);
  67476. this._debugMesh.color = this.color;
  67477. };
  67478. SkeletonViewer.prototype.dispose = function () {
  67479. if (this._debugMesh) {
  67480. this.isEnabled = false;
  67481. this._debugMesh.dispose();
  67482. this._debugMesh = null;
  67483. }
  67484. };
  67485. return SkeletonViewer;
  67486. }());
  67487. Debug.SkeletonViewer = SkeletonViewer;
  67488. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67489. })(BABYLON || (BABYLON = {}));
  67490. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67491. var BABYLON;
  67492. (function (BABYLON) {
  67493. var Debug;
  67494. (function (Debug) {
  67495. var AxesViewer = /** @class */ (function () {
  67496. function AxesViewer(scene, scaleLines) {
  67497. if (scaleLines === void 0) { scaleLines = 1; }
  67498. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67499. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67500. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67501. this.scaleLines = 1;
  67502. this.scaleLines = scaleLines;
  67503. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67504. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67505. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  67506. this._xmesh.renderingGroupId = 2;
  67507. this._ymesh.renderingGroupId = 2;
  67508. this._zmesh.renderingGroupId = 2;
  67509. this._xmesh.material.checkReadyOnlyOnce = true;
  67510. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  67511. this._ymesh.material.checkReadyOnlyOnce = true;
  67512. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  67513. this._zmesh.material.checkReadyOnlyOnce = true;
  67514. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  67515. this.scene = scene;
  67516. }
  67517. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  67518. var scaleLines = this.scaleLines;
  67519. if (this._xmesh) {
  67520. this._xmesh.position.copyFrom(position);
  67521. }
  67522. if (this._ymesh) {
  67523. this._ymesh.position.copyFrom(position);
  67524. }
  67525. if (this._zmesh) {
  67526. this._zmesh.position.copyFrom(position);
  67527. }
  67528. var point2 = this._xline[1];
  67529. point2.x = xaxis.x * scaleLines;
  67530. point2.y = xaxis.y * scaleLines;
  67531. point2.z = xaxis.z * scaleLines;
  67532. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  67533. point2 = this._yline[1];
  67534. point2.x = yaxis.x * scaleLines;
  67535. point2.y = yaxis.y * scaleLines;
  67536. point2.z = yaxis.z * scaleLines;
  67537. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  67538. point2 = this._zline[1];
  67539. point2.x = zaxis.x * scaleLines;
  67540. point2.y = zaxis.y * scaleLines;
  67541. point2.z = zaxis.z * scaleLines;
  67542. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  67543. };
  67544. AxesViewer.prototype.dispose = function () {
  67545. if (this._xmesh) {
  67546. this._xmesh.dispose();
  67547. }
  67548. if (this._ymesh) {
  67549. this._ymesh.dispose();
  67550. }
  67551. if (this._zmesh) {
  67552. this._zmesh.dispose();
  67553. }
  67554. this._xmesh = null;
  67555. this._ymesh = null;
  67556. this._zmesh = null;
  67557. this.scene = null;
  67558. };
  67559. return AxesViewer;
  67560. }());
  67561. Debug.AxesViewer = AxesViewer;
  67562. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67563. })(BABYLON || (BABYLON = {}));
  67564. //# sourceMappingURL=babylon.axesViewer.js.map
  67565. var BABYLON;
  67566. (function (BABYLON) {
  67567. var Debug;
  67568. (function (Debug) {
  67569. var BoneAxesViewer = /** @class */ (function (_super) {
  67570. __extends(BoneAxesViewer, _super);
  67571. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  67572. if (scaleLines === void 0) { scaleLines = 1; }
  67573. var _this = _super.call(this, scene, scaleLines) || this;
  67574. _this.pos = BABYLON.Vector3.Zero();
  67575. _this.xaxis = BABYLON.Vector3.Zero();
  67576. _this.yaxis = BABYLON.Vector3.Zero();
  67577. _this.zaxis = BABYLON.Vector3.Zero();
  67578. _this.mesh = mesh;
  67579. _this.bone = bone;
  67580. return _this;
  67581. }
  67582. BoneAxesViewer.prototype.update = function () {
  67583. if (!this.mesh || !this.bone) {
  67584. return;
  67585. }
  67586. var bone = this.bone;
  67587. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  67588. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  67589. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  67590. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  67591. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  67592. };
  67593. BoneAxesViewer.prototype.dispose = function () {
  67594. if (this.mesh) {
  67595. this.mesh = null;
  67596. this.bone = null;
  67597. _super.prototype.dispose.call(this);
  67598. }
  67599. };
  67600. return BoneAxesViewer;
  67601. }(Debug.AxesViewer));
  67602. Debug.BoneAxesViewer = BoneAxesViewer;
  67603. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67604. })(BABYLON || (BABYLON = {}));
  67605. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  67606. var BABYLON;
  67607. (function (BABYLON) {
  67608. var RayHelper = /** @class */ (function () {
  67609. function RayHelper(ray) {
  67610. this.ray = ray;
  67611. }
  67612. RayHelper.CreateAndShow = function (ray, scene, color) {
  67613. var helper = new RayHelper(ray);
  67614. helper.show(scene, color);
  67615. return helper;
  67616. };
  67617. RayHelper.prototype.show = function (scene, color) {
  67618. if (!this._renderFunction && this.ray) {
  67619. var ray = this.ray;
  67620. this._renderFunction = this._render.bind(this);
  67621. this._scene = scene;
  67622. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  67623. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  67624. if (this._renderFunction) {
  67625. this._scene.registerBeforeRender(this._renderFunction);
  67626. }
  67627. }
  67628. if (color && this._renderLine) {
  67629. this._renderLine.color.copyFrom(color);
  67630. }
  67631. };
  67632. RayHelper.prototype.hide = function () {
  67633. if (this._renderFunction && this._scene) {
  67634. this._scene.unregisterBeforeRender(this._renderFunction);
  67635. this._scene = null;
  67636. this._renderFunction = null;
  67637. if (this._renderLine) {
  67638. this._renderLine.dispose();
  67639. this._renderLine = null;
  67640. }
  67641. this._renderPoints = [];
  67642. }
  67643. };
  67644. RayHelper.prototype._render = function () {
  67645. var ray = this.ray;
  67646. if (!ray) {
  67647. return;
  67648. }
  67649. var point = this._renderPoints[1];
  67650. var len = Math.min(ray.length, 1000000);
  67651. point.copyFrom(ray.direction);
  67652. point.scaleInPlace(len);
  67653. point.addInPlace(ray.origin);
  67654. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  67655. };
  67656. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  67657. this._attachedToMesh = mesh;
  67658. var ray = this.ray;
  67659. if (!ray) {
  67660. return;
  67661. }
  67662. if (!ray.direction) {
  67663. ray.direction = BABYLON.Vector3.Zero();
  67664. }
  67665. if (!ray.origin) {
  67666. ray.origin = BABYLON.Vector3.Zero();
  67667. }
  67668. if (length) {
  67669. ray.length = length;
  67670. }
  67671. if (!meshSpaceOrigin) {
  67672. meshSpaceOrigin = BABYLON.Vector3.Zero();
  67673. }
  67674. if (!meshSpaceDirection) {
  67675. // -1 so that this will work with Mesh.lookAt
  67676. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  67677. }
  67678. if (!this._meshSpaceDirection) {
  67679. this._meshSpaceDirection = meshSpaceDirection.clone();
  67680. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  67681. }
  67682. else {
  67683. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  67684. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  67685. }
  67686. if (!this._updateToMeshFunction) {
  67687. this._updateToMeshFunction = this._updateToMesh.bind(this);
  67688. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  67689. }
  67690. this._updateToMesh();
  67691. };
  67692. RayHelper.prototype.detachFromMesh = function () {
  67693. if (this._attachedToMesh) {
  67694. if (this._updateToMeshFunction) {
  67695. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  67696. }
  67697. this._attachedToMesh = null;
  67698. this._updateToMeshFunction = null;
  67699. }
  67700. };
  67701. RayHelper.prototype._updateToMesh = function () {
  67702. var ray = this.ray;
  67703. if (!this._attachedToMesh || !ray) {
  67704. return;
  67705. }
  67706. if (this._attachedToMesh._isDisposed) {
  67707. this.detachFromMesh();
  67708. return;
  67709. }
  67710. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  67711. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  67712. };
  67713. RayHelper.prototype.dispose = function () {
  67714. this.hide();
  67715. this.detachFromMesh();
  67716. this.ray = null;
  67717. };
  67718. return RayHelper;
  67719. }());
  67720. BABYLON.RayHelper = RayHelper;
  67721. })(BABYLON || (BABYLON = {}));
  67722. //# sourceMappingURL=babylon.rayHelper.js.map
  67723. var BABYLON;
  67724. (function (BABYLON) {
  67725. var DebugLayer = /** @class */ (function () {
  67726. function DebugLayer(scene) {
  67727. this._scene = scene;
  67728. }
  67729. /** Creates the inspector window. */
  67730. DebugLayer.prototype._createInspector = function (config) {
  67731. if (config === void 0) { config = {}; }
  67732. var popup = config.popup || false;
  67733. var initialTab = config.initialTab || 0;
  67734. var parentElement = config.parentElement || null;
  67735. if (!this._inspector) {
  67736. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  67737. } // else nothing to do,; instance is already existing
  67738. };
  67739. DebugLayer.prototype.isVisible = function () {
  67740. if (!this._inspector) {
  67741. return false;
  67742. }
  67743. return true;
  67744. };
  67745. DebugLayer.prototype.hide = function () {
  67746. if (this._inspector) {
  67747. try {
  67748. this._inspector.dispose();
  67749. }
  67750. catch (e) {
  67751. // If the inspector has been removed directly from the inspector tool
  67752. }
  67753. this._inspector = null;
  67754. }
  67755. };
  67756. DebugLayer.prototype.show = function (config) {
  67757. if (config === void 0) { config = {}; }
  67758. if (typeof INSPECTOR == 'undefined') {
  67759. // Load inspector and add it to the DOM
  67760. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  67761. }
  67762. else {
  67763. // Otherwise creates the inspector
  67764. this._createInspector(config);
  67765. }
  67766. };
  67767. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  67768. return DebugLayer;
  67769. }());
  67770. BABYLON.DebugLayer = DebugLayer;
  67771. })(BABYLON || (BABYLON = {}));
  67772. //# sourceMappingURL=babylon.debugLayer.js.map
  67773. var BABYLON;
  67774. (function (BABYLON) {
  67775. var Debug;
  67776. (function (Debug) {
  67777. var PhysicsViewer = /** @class */ (function () {
  67778. function PhysicsViewer(scene) {
  67779. this._impostors = [];
  67780. this._meshes = [];
  67781. this._numMeshes = 0;
  67782. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67783. var physicEngine = this._scene.getPhysicsEngine();
  67784. if (physicEngine) {
  67785. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  67786. }
  67787. }
  67788. PhysicsViewer.prototype._updateDebugMeshes = function () {
  67789. var plugin = this._physicsEnginePlugin;
  67790. for (var i = 0; i < this._numMeshes; i++) {
  67791. var impostor = this._impostors[i];
  67792. if (!impostor) {
  67793. continue;
  67794. }
  67795. if (impostor.isDisposed) {
  67796. this.hideImpostor(this._impostors[i--]);
  67797. }
  67798. else {
  67799. var mesh = this._meshes[i];
  67800. if (mesh && plugin) {
  67801. plugin.syncMeshWithImpostor(mesh, impostor);
  67802. }
  67803. }
  67804. }
  67805. };
  67806. PhysicsViewer.prototype.showImpostor = function (impostor) {
  67807. if (!this._scene) {
  67808. return;
  67809. }
  67810. for (var i = 0; i < this._numMeshes; i++) {
  67811. if (this._impostors[i] == impostor) {
  67812. return;
  67813. }
  67814. }
  67815. var debugMesh = this._getDebugMesh(impostor, this._scene);
  67816. if (debugMesh) {
  67817. this._impostors[this._numMeshes] = impostor;
  67818. this._meshes[this._numMeshes] = debugMesh;
  67819. if (this._numMeshes === 0) {
  67820. this._renderFunction = this._updateDebugMeshes.bind(this);
  67821. this._scene.registerBeforeRender(this._renderFunction);
  67822. }
  67823. this._numMeshes++;
  67824. }
  67825. };
  67826. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  67827. if (!impostor || !this._scene) {
  67828. return;
  67829. }
  67830. var removed = false;
  67831. for (var i = 0; i < this._numMeshes; i++) {
  67832. if (this._impostors[i] == impostor) {
  67833. var mesh = this._meshes[i];
  67834. if (!mesh) {
  67835. continue;
  67836. }
  67837. this._scene.removeMesh(mesh);
  67838. mesh.dispose();
  67839. this._numMeshes--;
  67840. if (this._numMeshes > 0) {
  67841. this._meshes[i] = this._meshes[this._numMeshes];
  67842. this._impostors[i] = this._impostors[this._numMeshes];
  67843. this._meshes[this._numMeshes] = null;
  67844. this._impostors[this._numMeshes] = null;
  67845. }
  67846. else {
  67847. this._meshes[0] = null;
  67848. this._impostors[0] = null;
  67849. }
  67850. removed = true;
  67851. break;
  67852. }
  67853. }
  67854. if (removed && this._numMeshes === 0) {
  67855. this._scene.unregisterBeforeRender(this._renderFunction);
  67856. }
  67857. };
  67858. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  67859. if (!this._debugMaterial) {
  67860. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  67861. this._debugMaterial.wireframe = true;
  67862. }
  67863. return this._debugMaterial;
  67864. };
  67865. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  67866. if (!this._debugBoxMesh) {
  67867. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  67868. this._debugBoxMesh.renderingGroupId = 1;
  67869. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67870. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  67871. scene.removeMesh(this._debugBoxMesh);
  67872. }
  67873. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  67874. };
  67875. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  67876. if (!this._debugSphereMesh) {
  67877. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  67878. this._debugSphereMesh.renderingGroupId = 1;
  67879. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  67880. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  67881. scene.removeMesh(this._debugSphereMesh);
  67882. }
  67883. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  67884. };
  67885. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  67886. var mesh = null;
  67887. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  67888. mesh = this._getDebugBoxMesh(scene);
  67889. impostor.getBoxSizeToRef(mesh.scaling);
  67890. }
  67891. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  67892. mesh = this._getDebugSphereMesh(scene);
  67893. var radius = impostor.getRadius();
  67894. mesh.scaling.x = radius * 2;
  67895. mesh.scaling.y = radius * 2;
  67896. mesh.scaling.z = radius * 2;
  67897. }
  67898. return mesh;
  67899. };
  67900. PhysicsViewer.prototype.dispose = function () {
  67901. for (var i = 0; i < this._numMeshes; i++) {
  67902. this.hideImpostor(this._impostors[i]);
  67903. }
  67904. if (this._debugBoxMesh) {
  67905. this._debugBoxMesh.dispose();
  67906. }
  67907. if (this._debugSphereMesh) {
  67908. this._debugSphereMesh.dispose();
  67909. }
  67910. if (this._debugMaterial) {
  67911. this._debugMaterial.dispose();
  67912. }
  67913. this._impostors.length = 0;
  67914. this._scene = null;
  67915. this._physicsEnginePlugin = null;
  67916. };
  67917. return PhysicsViewer;
  67918. }());
  67919. Debug.PhysicsViewer = PhysicsViewer;
  67920. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67921. })(BABYLON || (BABYLON = {}));
  67922. //# sourceMappingURL=babylon.physicsViewer.js.map
  67923. var BABYLON;
  67924. (function (BABYLON) {
  67925. var BoundingBoxRenderer = /** @class */ (function () {
  67926. function BoundingBoxRenderer(scene) {
  67927. this.frontColor = new BABYLON.Color3(1, 1, 1);
  67928. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  67929. this.showBackLines = true;
  67930. this.renderList = new BABYLON.SmartArray(32);
  67931. this._vertexBuffers = {};
  67932. this._scene = scene;
  67933. }
  67934. BoundingBoxRenderer.prototype._prepareRessources = function () {
  67935. if (this._colorShader) {
  67936. return;
  67937. }
  67938. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  67939. attributes: [BABYLON.VertexBuffer.PositionKind],
  67940. uniforms: ["world", "viewProjection", "color"]
  67941. });
  67942. var engine = this._scene.getEngine();
  67943. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  67944. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  67945. this._createIndexBuffer();
  67946. };
  67947. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  67948. var engine = this._scene.getEngine();
  67949. 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]);
  67950. };
  67951. BoundingBoxRenderer.prototype._rebuild = function () {
  67952. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67953. if (vb) {
  67954. vb._rebuild();
  67955. }
  67956. this._createIndexBuffer();
  67957. };
  67958. BoundingBoxRenderer.prototype.reset = function () {
  67959. this.renderList.reset();
  67960. };
  67961. BoundingBoxRenderer.prototype.render = function () {
  67962. if (this.renderList.length === 0) {
  67963. return;
  67964. }
  67965. this._prepareRessources();
  67966. if (!this._colorShader.isReady()) {
  67967. return;
  67968. }
  67969. var engine = this._scene.getEngine();
  67970. engine.setDepthWrite(false);
  67971. this._colorShader._preBind();
  67972. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  67973. var boundingBox = this.renderList.data[boundingBoxIndex];
  67974. var min = boundingBox.minimum;
  67975. var max = boundingBox.maximum;
  67976. var diff = max.subtract(min);
  67977. var median = min.add(diff.scale(0.5));
  67978. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  67979. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  67980. .multiply(boundingBox.getWorldMatrix());
  67981. // VBOs
  67982. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  67983. if (this.showBackLines) {
  67984. // Back
  67985. engine.setDepthFunctionToGreaterOrEqual();
  67986. this._scene.resetCachedMaterial();
  67987. this._colorShader.setColor4("color", this.backColor.toColor4());
  67988. this._colorShader.bind(worldMatrix);
  67989. // Draw order
  67990. engine.draw(false, 0, 24);
  67991. }
  67992. // Front
  67993. engine.setDepthFunctionToLess();
  67994. this._scene.resetCachedMaterial();
  67995. this._colorShader.setColor4("color", this.frontColor.toColor4());
  67996. this._colorShader.bind(worldMatrix);
  67997. // Draw order
  67998. engine.draw(false, 0, 24);
  67999. }
  68000. this._colorShader.unbind();
  68001. engine.setDepthFunctionToLessOrEqual();
  68002. engine.setDepthWrite(true);
  68003. };
  68004. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68005. this._prepareRessources();
  68006. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68007. return;
  68008. }
  68009. var engine = this._scene.getEngine();
  68010. engine.setDepthWrite(false);
  68011. engine.setColorWrite(false);
  68012. this._colorShader._preBind();
  68013. var boundingBox = mesh._boundingInfo.boundingBox;
  68014. var min = boundingBox.minimum;
  68015. var max = boundingBox.maximum;
  68016. var diff = max.subtract(min);
  68017. var median = min.add(diff.scale(0.5));
  68018. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68019. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68020. .multiply(boundingBox.getWorldMatrix());
  68021. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68022. engine.setDepthFunctionToLess();
  68023. this._scene.resetCachedMaterial();
  68024. this._colorShader.bind(worldMatrix);
  68025. engine.draw(false, 0, 24);
  68026. this._colorShader.unbind();
  68027. engine.setDepthFunctionToLessOrEqual();
  68028. engine.setDepthWrite(true);
  68029. engine.setColorWrite(true);
  68030. };
  68031. BoundingBoxRenderer.prototype.dispose = function () {
  68032. if (!this._colorShader) {
  68033. return;
  68034. }
  68035. this.renderList.dispose();
  68036. this._colorShader.dispose();
  68037. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68038. if (buffer) {
  68039. buffer.dispose();
  68040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68041. }
  68042. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68043. };
  68044. return BoundingBoxRenderer;
  68045. }());
  68046. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68047. })(BABYLON || (BABYLON = {}));
  68048. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68049. var BABYLON;
  68050. (function (BABYLON) {
  68051. var MorphTarget = /** @class */ (function () {
  68052. function MorphTarget(name, influence) {
  68053. if (influence === void 0) { influence = 0; }
  68054. this.name = name;
  68055. this.animations = new Array();
  68056. this.onInfluenceChanged = new BABYLON.Observable();
  68057. this.influence = influence;
  68058. }
  68059. Object.defineProperty(MorphTarget.prototype, "influence", {
  68060. get: function () {
  68061. return this._influence;
  68062. },
  68063. set: function (influence) {
  68064. if (this._influence === influence) {
  68065. return;
  68066. }
  68067. var previous = this._influence;
  68068. this._influence = influence;
  68069. if (this.onInfluenceChanged.hasObservers) {
  68070. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68071. }
  68072. },
  68073. enumerable: true,
  68074. configurable: true
  68075. });
  68076. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68077. get: function () {
  68078. return this._normals !== undefined;
  68079. },
  68080. enumerable: true,
  68081. configurable: true
  68082. });
  68083. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68084. get: function () {
  68085. return this._tangents !== undefined;
  68086. },
  68087. enumerable: true,
  68088. configurable: true
  68089. });
  68090. MorphTarget.prototype.setPositions = function (data) {
  68091. this._positions = new Float32Array(data);
  68092. };
  68093. MorphTarget.prototype.getPositions = function () {
  68094. return this._positions;
  68095. };
  68096. MorphTarget.prototype.setNormals = function (data) {
  68097. this._normals = new Float32Array(data);
  68098. };
  68099. MorphTarget.prototype.getNormals = function () {
  68100. return this._normals;
  68101. };
  68102. MorphTarget.prototype.setTangents = function (data) {
  68103. this._tangents = new Float32Array(data);
  68104. };
  68105. MorphTarget.prototype.getTangents = function () {
  68106. return this._tangents;
  68107. };
  68108. /**
  68109. * Serializes the current target into a Serialization object.
  68110. * Returns the serialized object.
  68111. */
  68112. MorphTarget.prototype.serialize = function () {
  68113. var serializationObject = {};
  68114. serializationObject.name = this.name;
  68115. serializationObject.influence = this.influence;
  68116. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68117. if (this.hasNormals) {
  68118. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68119. }
  68120. if (this.hasTangents) {
  68121. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68122. }
  68123. // Animations
  68124. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68125. return serializationObject;
  68126. };
  68127. // Statics
  68128. MorphTarget.Parse = function (serializationObject) {
  68129. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68130. result.setPositions(serializationObject.positions);
  68131. if (serializationObject.normals) {
  68132. result.setNormals(serializationObject.normals);
  68133. }
  68134. if (serializationObject.tangents) {
  68135. result.setTangents(serializationObject.tangents);
  68136. }
  68137. // Animations
  68138. if (serializationObject.animations) {
  68139. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68140. var parsedAnimation = serializationObject.animations[animationIndex];
  68141. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68142. }
  68143. }
  68144. return result;
  68145. };
  68146. MorphTarget.FromMesh = function (mesh, name, influence) {
  68147. if (!name) {
  68148. name = mesh.name;
  68149. }
  68150. var result = new MorphTarget(name, influence);
  68151. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68153. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68154. }
  68155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68156. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68157. }
  68158. return result;
  68159. };
  68160. return MorphTarget;
  68161. }());
  68162. BABYLON.MorphTarget = MorphTarget;
  68163. })(BABYLON || (BABYLON = {}));
  68164. //# sourceMappingURL=babylon.morphTarget.js.map
  68165. var BABYLON;
  68166. (function (BABYLON) {
  68167. var MorphTargetManager = /** @class */ (function () {
  68168. function MorphTargetManager(scene) {
  68169. if (scene === void 0) { scene = null; }
  68170. this._targets = new Array();
  68171. this._targetObservable = new Array();
  68172. this._activeTargets = new BABYLON.SmartArray(16);
  68173. this._supportsNormals = false;
  68174. this._supportsTangents = false;
  68175. this._vertexCount = 0;
  68176. this._uniqueId = 0;
  68177. this._tempInfluences = new Array();
  68178. if (!scene) {
  68179. scene = BABYLON.Engine.LastCreatedScene;
  68180. }
  68181. this._scene = scene;
  68182. if (this._scene) {
  68183. this._scene.morphTargetManagers.push(this);
  68184. this._uniqueId = this._scene.getUniqueId();
  68185. }
  68186. }
  68187. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68188. get: function () {
  68189. return this._uniqueId;
  68190. },
  68191. enumerable: true,
  68192. configurable: true
  68193. });
  68194. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68195. get: function () {
  68196. return this._vertexCount;
  68197. },
  68198. enumerable: true,
  68199. configurable: true
  68200. });
  68201. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68202. get: function () {
  68203. return this._supportsNormals;
  68204. },
  68205. enumerable: true,
  68206. configurable: true
  68207. });
  68208. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68209. get: function () {
  68210. return this._supportsTangents;
  68211. },
  68212. enumerable: true,
  68213. configurable: true
  68214. });
  68215. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68216. get: function () {
  68217. return this._targets.length;
  68218. },
  68219. enumerable: true,
  68220. configurable: true
  68221. });
  68222. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68223. get: function () {
  68224. return this._activeTargets.length;
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68230. get: function () {
  68231. return this._influences;
  68232. },
  68233. enumerable: true,
  68234. configurable: true
  68235. });
  68236. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68237. return this._activeTargets.data[index];
  68238. };
  68239. MorphTargetManager.prototype.getTarget = function (index) {
  68240. return this._targets[index];
  68241. };
  68242. MorphTargetManager.prototype.addTarget = function (target) {
  68243. var _this = this;
  68244. if (this._vertexCount) {
  68245. if (this._vertexCount !== target.getPositions().length / 3) {
  68246. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68247. return;
  68248. }
  68249. }
  68250. this._targets.push(target);
  68251. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68252. _this._syncActiveTargets(needUpdate);
  68253. }));
  68254. this._syncActiveTargets(true);
  68255. };
  68256. MorphTargetManager.prototype.removeTarget = function (target) {
  68257. var index = this._targets.indexOf(target);
  68258. if (index >= 0) {
  68259. this._targets.splice(index, 1);
  68260. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68261. this._vertexCount = 0;
  68262. this._syncActiveTargets(true);
  68263. }
  68264. };
  68265. /**
  68266. * Serializes the current manager into a Serialization object.
  68267. * Returns the serialized object.
  68268. */
  68269. MorphTargetManager.prototype.serialize = function () {
  68270. var serializationObject = {};
  68271. serializationObject.id = this.uniqueId;
  68272. serializationObject.targets = [];
  68273. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68274. var target = _a[_i];
  68275. serializationObject.targets.push(target.serialize());
  68276. }
  68277. return serializationObject;
  68278. };
  68279. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68280. var influenceCount = 0;
  68281. this._activeTargets.reset();
  68282. this._supportsNormals = true;
  68283. this._supportsTangents = true;
  68284. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68285. var target = _a[_i];
  68286. if (target.influence > 0) {
  68287. this._activeTargets.push(target);
  68288. this._tempInfluences[influenceCount++] = target.influence;
  68289. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68290. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68291. if (this._vertexCount === 0) {
  68292. this._vertexCount = target.getPositions().length / 3;
  68293. }
  68294. }
  68295. }
  68296. if (!this._influences || this._influences.length !== influenceCount) {
  68297. this._influences = new Float32Array(influenceCount);
  68298. }
  68299. for (var index = 0; index < influenceCount; index++) {
  68300. this._influences[index] = this._tempInfluences[index];
  68301. }
  68302. if (needUpdate && this._scene) {
  68303. // Flag meshes as dirty to resync with the active targets
  68304. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68305. var mesh = _c[_b];
  68306. if (mesh.morphTargetManager === this) {
  68307. mesh._syncGeometryWithMorphTargetManager();
  68308. }
  68309. }
  68310. }
  68311. };
  68312. // Statics
  68313. MorphTargetManager.Parse = function (serializationObject, scene) {
  68314. var result = new MorphTargetManager(scene);
  68315. result._uniqueId = serializationObject.id;
  68316. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68317. var targetData = _a[_i];
  68318. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68319. }
  68320. return result;
  68321. };
  68322. return MorphTargetManager;
  68323. }());
  68324. BABYLON.MorphTargetManager = MorphTargetManager;
  68325. })(BABYLON || (BABYLON = {}));
  68326. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68327. var BABYLON;
  68328. (function (BABYLON) {
  68329. var Octree = /** @class */ (function () {
  68330. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68331. if (maxDepth === void 0) { maxDepth = 2; }
  68332. this.maxDepth = maxDepth;
  68333. this.dynamicContent = new Array();
  68334. this._maxBlockCapacity = maxBlockCapacity || 64;
  68335. this._selectionContent = new BABYLON.SmartArray(1024);
  68336. this._creationFunc = creationFunc;
  68337. }
  68338. // Methods
  68339. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68340. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68341. };
  68342. Octree.prototype.addMesh = function (entry) {
  68343. for (var index = 0; index < this.blocks.length; index++) {
  68344. var block = this.blocks[index];
  68345. block.addEntry(entry);
  68346. }
  68347. };
  68348. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68349. this._selectionContent.reset();
  68350. for (var index = 0; index < this.blocks.length; index++) {
  68351. var block = this.blocks[index];
  68352. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68353. }
  68354. if (allowDuplicate) {
  68355. this._selectionContent.concat(this.dynamicContent);
  68356. }
  68357. else {
  68358. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68359. }
  68360. return this._selectionContent;
  68361. };
  68362. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68363. this._selectionContent.reset();
  68364. for (var index = 0; index < this.blocks.length; index++) {
  68365. var block = this.blocks[index];
  68366. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68367. }
  68368. if (allowDuplicate) {
  68369. this._selectionContent.concat(this.dynamicContent);
  68370. }
  68371. else {
  68372. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68373. }
  68374. return this._selectionContent;
  68375. };
  68376. Octree.prototype.intersectsRay = function (ray) {
  68377. this._selectionContent.reset();
  68378. for (var index = 0; index < this.blocks.length; index++) {
  68379. var block = this.blocks[index];
  68380. block.intersectsRay(ray, this._selectionContent);
  68381. }
  68382. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68383. return this._selectionContent;
  68384. };
  68385. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68386. target.blocks = new Array();
  68387. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68388. // Segmenting space
  68389. for (var x = 0; x < 2; x++) {
  68390. for (var y = 0; y < 2; y++) {
  68391. for (var z = 0; z < 2; z++) {
  68392. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68393. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68394. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68395. block.addEntries(entries);
  68396. target.blocks.push(block);
  68397. }
  68398. }
  68399. }
  68400. };
  68401. Octree.CreationFuncForMeshes = function (entry, block) {
  68402. var boundingInfo = entry.getBoundingInfo();
  68403. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68404. block.entries.push(entry);
  68405. }
  68406. };
  68407. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68408. var boundingInfo = entry.getBoundingInfo();
  68409. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68410. block.entries.push(entry);
  68411. }
  68412. };
  68413. return Octree;
  68414. }());
  68415. BABYLON.Octree = Octree;
  68416. })(BABYLON || (BABYLON = {}));
  68417. //# sourceMappingURL=babylon.octree.js.map
  68418. var BABYLON;
  68419. (function (BABYLON) {
  68420. var OctreeBlock = /** @class */ (function () {
  68421. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68422. this.entries = new Array();
  68423. this._boundingVectors = new Array();
  68424. this._capacity = capacity;
  68425. this._depth = depth;
  68426. this._maxDepth = maxDepth;
  68427. this._creationFunc = creationFunc;
  68428. this._minPoint = minPoint;
  68429. this._maxPoint = maxPoint;
  68430. this._boundingVectors.push(minPoint.clone());
  68431. this._boundingVectors.push(maxPoint.clone());
  68432. this._boundingVectors.push(minPoint.clone());
  68433. this._boundingVectors[2].x = maxPoint.x;
  68434. this._boundingVectors.push(minPoint.clone());
  68435. this._boundingVectors[3].y = maxPoint.y;
  68436. this._boundingVectors.push(minPoint.clone());
  68437. this._boundingVectors[4].z = maxPoint.z;
  68438. this._boundingVectors.push(maxPoint.clone());
  68439. this._boundingVectors[5].z = minPoint.z;
  68440. this._boundingVectors.push(maxPoint.clone());
  68441. this._boundingVectors[6].x = minPoint.x;
  68442. this._boundingVectors.push(maxPoint.clone());
  68443. this._boundingVectors[7].y = minPoint.y;
  68444. }
  68445. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68446. // Property
  68447. get: function () {
  68448. return this._capacity;
  68449. },
  68450. enumerable: true,
  68451. configurable: true
  68452. });
  68453. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68454. get: function () {
  68455. return this._minPoint;
  68456. },
  68457. enumerable: true,
  68458. configurable: true
  68459. });
  68460. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68461. get: function () {
  68462. return this._maxPoint;
  68463. },
  68464. enumerable: true,
  68465. configurable: true
  68466. });
  68467. // Methods
  68468. OctreeBlock.prototype.addEntry = function (entry) {
  68469. if (this.blocks) {
  68470. for (var index = 0; index < this.blocks.length; index++) {
  68471. var block = this.blocks[index];
  68472. block.addEntry(entry);
  68473. }
  68474. return;
  68475. }
  68476. this._creationFunc(entry, this);
  68477. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68478. this.createInnerBlocks();
  68479. }
  68480. };
  68481. OctreeBlock.prototype.addEntries = function (entries) {
  68482. for (var index = 0; index < entries.length; index++) {
  68483. var mesh = entries[index];
  68484. this.addEntry(mesh);
  68485. }
  68486. };
  68487. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68488. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68489. if (this.blocks) {
  68490. for (var index = 0; index < this.blocks.length; index++) {
  68491. var block = this.blocks[index];
  68492. block.select(frustumPlanes, selection, allowDuplicate);
  68493. }
  68494. return;
  68495. }
  68496. if (allowDuplicate) {
  68497. selection.concat(this.entries);
  68498. }
  68499. else {
  68500. selection.concatWithNoDuplicate(this.entries);
  68501. }
  68502. }
  68503. };
  68504. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  68505. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  68506. if (this.blocks) {
  68507. for (var index = 0; index < this.blocks.length; index++) {
  68508. var block = this.blocks[index];
  68509. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  68510. }
  68511. return;
  68512. }
  68513. if (allowDuplicate) {
  68514. selection.concat(this.entries);
  68515. }
  68516. else {
  68517. selection.concatWithNoDuplicate(this.entries);
  68518. }
  68519. }
  68520. };
  68521. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  68522. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  68523. if (this.blocks) {
  68524. for (var index = 0; index < this.blocks.length; index++) {
  68525. var block = this.blocks[index];
  68526. block.intersectsRay(ray, selection);
  68527. }
  68528. return;
  68529. }
  68530. selection.concatWithNoDuplicate(this.entries);
  68531. }
  68532. };
  68533. OctreeBlock.prototype.createInnerBlocks = function () {
  68534. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  68535. };
  68536. return OctreeBlock;
  68537. }());
  68538. BABYLON.OctreeBlock = OctreeBlock;
  68539. })(BABYLON || (BABYLON = {}));
  68540. //# sourceMappingURL=babylon.octreeBlock.js.map
  68541. var BABYLON;
  68542. (function (BABYLON) {
  68543. var SIMDVector3 = /** @class */ (function () {
  68544. function SIMDVector3() {
  68545. }
  68546. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  68547. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  68548. };
  68549. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  68550. var m = transformation.m;
  68551. var m0 = SIMD.Float32x4.load(m, 0);
  68552. var m1 = SIMD.Float32x4.load(m, 4);
  68553. var m2 = SIMD.Float32x4.load(m, 8);
  68554. var m3 = SIMD.Float32x4.load(m, 12);
  68555. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  68556. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  68557. result.x = SIMD.Float32x4.extractLane(r, 0);
  68558. result.y = SIMD.Float32x4.extractLane(r, 1);
  68559. result.z = SIMD.Float32x4.extractLane(r, 2);
  68560. };
  68561. return SIMDVector3;
  68562. }());
  68563. var SIMDMatrix = /** @class */ (function () {
  68564. function SIMDMatrix() {
  68565. }
  68566. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  68567. var tm = this.m;
  68568. var om = other.m;
  68569. var m0 = SIMD.Float32x4.load(om, 0);
  68570. var m1 = SIMD.Float32x4.load(om, 4);
  68571. var m2 = SIMD.Float32x4.load(om, 8);
  68572. var m3 = SIMD.Float32x4.load(om, 12);
  68573. for (var i = 0; i < 16; i += 4) {
  68574. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  68575. }
  68576. return this;
  68577. };
  68578. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  68579. var src = this.m;
  68580. var dest = other.m;
  68581. // Load the 4 rows
  68582. var src0 = SIMD.Float32x4.load(src, 0);
  68583. var src1 = SIMD.Float32x4.load(src, 4);
  68584. var src2 = SIMD.Float32x4.load(src, 8);
  68585. var src3 = SIMD.Float32x4.load(src, 12);
  68586. // Transpose the source matrix. Sort of. Not a true transpose operation
  68587. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  68588. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  68589. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  68590. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  68591. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  68592. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  68593. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  68594. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  68595. // This is a true transposition, but it will lead to an incorrect result
  68596. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  68597. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  68598. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68599. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68600. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  68601. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  68602. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  68603. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  68604. // ----
  68605. tmp1 = SIMD.Float32x4.mul(row2, row3);
  68606. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68607. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  68608. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  68609. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68610. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  68611. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  68612. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  68613. // ----
  68614. tmp1 = SIMD.Float32x4.mul(row1, row2);
  68615. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68616. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  68617. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  68618. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68619. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  68620. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  68621. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  68622. // ----
  68623. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  68624. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68625. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  68626. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  68627. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  68628. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68629. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  68630. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  68631. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  68632. // ----
  68633. tmp1 = SIMD.Float32x4.mul(row0, row1);
  68634. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68635. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68636. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  68637. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68638. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  68639. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  68640. // ----
  68641. tmp1 = SIMD.Float32x4.mul(row0, row3);
  68642. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68643. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  68644. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  68645. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68646. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  68647. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  68648. // ----
  68649. tmp1 = SIMD.Float32x4.mul(row0, row2);
  68650. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  68651. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  68652. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  68653. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  68654. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  68655. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  68656. // Compute determinant
  68657. var det = SIMD.Float32x4.mul(row0, minor0);
  68658. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  68659. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  68660. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  68661. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  68662. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  68663. // These shuffles aren't necessary if the faulty transposition is done
  68664. // up at the top of this function.
  68665. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  68666. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  68667. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  68668. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  68669. // Compute final values by multiplying with 1/det
  68670. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  68671. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  68672. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  68673. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  68674. return this;
  68675. };
  68676. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  68677. var out = result.m;
  68678. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  68679. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  68680. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  68681. // cc.kmVec3Subtract(f, pCenter, pEye);
  68682. var f = SIMD.Float32x4.sub(center, eye);
  68683. // cc.kmVec3Normalize(f, f);
  68684. var tmp = SIMD.Float32x4.mul(f, f);
  68685. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68686. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68687. // cc.kmVec3Assign(up, pUp);
  68688. // cc.kmVec3Normalize(up, up);
  68689. tmp = SIMD.Float32x4.mul(up, up);
  68690. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68691. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68692. // cc.kmVec3Cross(s, f, up);
  68693. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  68694. // cc.kmVec3Normalize(s, s);
  68695. tmp = SIMD.Float32x4.mul(s, s);
  68696. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68697. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68698. // cc.kmVec3Cross(u, s, f);
  68699. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  68700. // cc.kmVec3Normalize(s, s);
  68701. tmp = SIMD.Float32x4.mul(s, s);
  68702. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  68703. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  68704. var zero = SIMD.Float32x4.splat(0.0);
  68705. s = SIMD.Float32x4.neg(s);
  68706. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  68707. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  68708. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  68709. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  68710. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  68711. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  68712. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  68713. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68714. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  68715. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68716. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  68717. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68718. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  68719. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  68720. };
  68721. return SIMDMatrix;
  68722. }());
  68723. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  68724. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  68725. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  68726. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  68727. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  68728. var SIMDHelper = /** @class */ (function () {
  68729. function SIMDHelper() {
  68730. }
  68731. Object.defineProperty(SIMDHelper, "IsEnabled", {
  68732. get: function () {
  68733. return SIMDHelper._isEnabled;
  68734. },
  68735. enumerable: true,
  68736. configurable: true
  68737. });
  68738. SIMDHelper.DisableSIMD = function () {
  68739. // Replace functions
  68740. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  68741. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  68742. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  68743. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  68744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  68745. SIMDHelper._isEnabled = false;
  68746. };
  68747. SIMDHelper.EnableSIMD = function () {
  68748. if (self.SIMD === undefined) {
  68749. return;
  68750. }
  68751. // check if polyfills needed
  68752. if (!self.Math.fround) {
  68753. self.Math.fround = (function (array) { return function (x) {
  68754. return array[0] = x, array[0];
  68755. }; })(new Float32Array(1));
  68756. }
  68757. if (!self.Math.imul) {
  68758. self.Math.imul = function (a, b) {
  68759. var ah = (a >>> 16) & 0xffff;
  68760. var al = a & 0xffff;
  68761. var bh = (b >>> 16) & 0xffff;
  68762. var bl = b & 0xffff;
  68763. // the shift by 0 fixes the sign on the high part
  68764. // the final |0 converts the unsigned value into a signed value
  68765. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  68766. };
  68767. }
  68768. // Replace functions
  68769. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  68770. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  68771. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  68772. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  68773. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  68774. SIMDHelper._isEnabled = true;
  68775. };
  68776. SIMDHelper._isEnabled = false;
  68777. return SIMDHelper;
  68778. }());
  68779. BABYLON.SIMDHelper = SIMDHelper;
  68780. })(BABYLON || (BABYLON = {}));
  68781. //# sourceMappingURL=babylon.math.SIMD.js.map
  68782. var BABYLON;
  68783. (function (BABYLON) {
  68784. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  68785. __extends(VRDistortionCorrectionPostProcess, _super);
  68786. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  68787. var _this = _super.call(this, name, "vrDistortionCorrection", [
  68788. 'LensCenter',
  68789. 'Scale',
  68790. 'ScaleIn',
  68791. 'HmdWarpParam'
  68792. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  68793. _this._isRightEye = isRightEye;
  68794. _this._distortionFactors = vrMetrics.distortionK;
  68795. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  68796. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  68797. _this.adaptScaleToCurrentViewport = true;
  68798. _this.onSizeChangedObservable.add(function () {
  68799. _this.aspectRatio = _this.width * .5 / _this.height;
  68800. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  68801. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  68802. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  68803. });
  68804. _this.onApplyObservable.add(function (effect) {
  68805. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  68806. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  68807. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  68808. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  68809. });
  68810. return _this;
  68811. }
  68812. return VRDistortionCorrectionPostProcess;
  68813. }(BABYLON.PostProcess));
  68814. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  68815. })(BABYLON || (BABYLON = {}));
  68816. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  68817. var BABYLON;
  68818. (function (BABYLON) {
  68819. var AnaglyphPostProcess = /** @class */ (function (_super) {
  68820. __extends(AnaglyphPostProcess, _super);
  68821. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  68822. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  68823. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68824. _this.onApplyObservable.add(function (effect) {
  68825. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  68826. });
  68827. return _this;
  68828. }
  68829. return AnaglyphPostProcess;
  68830. }(BABYLON.PostProcess));
  68831. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  68832. })(BABYLON || (BABYLON = {}));
  68833. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  68834. var BABYLON;
  68835. (function (BABYLON) {
  68836. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  68837. __extends(StereoscopicInterlacePostProcess, _super);
  68838. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  68839. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  68840. _this._passedProcess = rigCameras[0]._rigPostProcess;
  68841. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68842. _this.onSizeChangedObservable.add(function () {
  68843. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  68844. });
  68845. _this.onApplyObservable.add(function (effect) {
  68846. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  68847. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  68848. });
  68849. return _this;
  68850. }
  68851. return StereoscopicInterlacePostProcess;
  68852. }(BABYLON.PostProcess));
  68853. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  68854. })(BABYLON || (BABYLON = {}));
  68855. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  68856. var BABYLON;
  68857. (function (BABYLON) {
  68858. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  68859. function FreeCameraDeviceOrientationInput() {
  68860. var _this = this;
  68861. this._screenOrientationAngle = 0;
  68862. this._screenQuaternion = new BABYLON.Quaternion();
  68863. this._alpha = 0;
  68864. this._beta = 0;
  68865. this._gamma = 0;
  68866. this._orientationChanged = function () {
  68867. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  68868. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  68869. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  68870. };
  68871. this._deviceOrientation = function (evt) {
  68872. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  68873. _this._beta = evt.beta !== null ? evt.beta : 0;
  68874. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  68875. };
  68876. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  68877. this._orientationChanged();
  68878. }
  68879. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  68880. get: function () {
  68881. return this._camera;
  68882. },
  68883. set: function (camera) {
  68884. this._camera = camera;
  68885. if (this._camera != null && !this._camera.rotationQuaternion) {
  68886. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  68887. }
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68893. window.addEventListener("orientationchange", this._orientationChanged);
  68894. window.addEventListener("deviceorientation", this._deviceOrientation);
  68895. //In certain cases, the attach control is called AFTER orientation was changed,
  68896. //So this is needed.
  68897. this._orientationChanged();
  68898. };
  68899. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  68900. window.removeEventListener("orientationchange", this._orientationChanged);
  68901. window.removeEventListener("deviceorientation", this._deviceOrientation);
  68902. };
  68903. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  68904. //if no device orientation provided, don't update the rotation.
  68905. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  68906. if (!this._alpha)
  68907. return;
  68908. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  68909. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  68910. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  68911. //Mirror on XY Plane
  68912. this._camera.rotationQuaternion.z *= -1;
  68913. this._camera.rotationQuaternion.w *= -1;
  68914. };
  68915. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  68916. return "FreeCameraDeviceOrientationInput";
  68917. };
  68918. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  68919. return "deviceOrientation";
  68920. };
  68921. return FreeCameraDeviceOrientationInput;
  68922. }());
  68923. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  68924. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  68925. })(BABYLON || (BABYLON = {}));
  68926. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  68927. var BABYLON;
  68928. (function (BABYLON) {
  68929. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  68930. function ArcRotateCameraVRDeviceOrientationInput() {
  68931. this.alphaCorrection = 1;
  68932. this.betaCorrection = 1;
  68933. this.gammaCorrection = 1;
  68934. this._alpha = 0;
  68935. this._beta = 0;
  68936. this._gamma = 0;
  68937. this._dirty = false;
  68938. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  68939. }
  68940. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  68941. this.camera.attachControl(element, noPreventDefault);
  68942. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  68943. };
  68944. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  68945. if (evt.alpha !== null) {
  68946. this._alpha = +evt.alpha | 0;
  68947. }
  68948. if (evt.beta !== null) {
  68949. this._beta = +evt.beta | 0;
  68950. }
  68951. if (evt.gamma !== null) {
  68952. this._gamma = +evt.gamma | 0;
  68953. }
  68954. this._dirty = true;
  68955. };
  68956. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  68957. if (this._dirty) {
  68958. this._dirty = false;
  68959. if (this._gamma < 0) {
  68960. this._gamma = 180 + this._gamma;
  68961. }
  68962. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  68963. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  68964. }
  68965. };
  68966. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  68967. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  68968. };
  68969. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  68970. return "ArcRotateCameraVRDeviceOrientationInput";
  68971. };
  68972. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  68973. return "VRDeviceOrientation";
  68974. };
  68975. return ArcRotateCameraVRDeviceOrientationInput;
  68976. }());
  68977. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  68978. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  68979. })(BABYLON || (BABYLON = {}));
  68980. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  68981. var BABYLON;
  68982. (function (BABYLON) {
  68983. var VRCameraMetrics = /** @class */ (function () {
  68984. function VRCameraMetrics() {
  68985. this.compensateDistortion = true;
  68986. }
  68987. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  68988. get: function () {
  68989. return this.hResolution / (2 * this.vResolution);
  68990. },
  68991. enumerable: true,
  68992. configurable: true
  68993. });
  68994. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  68995. get: function () {
  68996. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  68997. },
  68998. enumerable: true,
  68999. configurable: true
  69000. });
  69001. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69002. get: function () {
  69003. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69004. var h = (4 * meters) / this.hScreenSize;
  69005. return BABYLON.Matrix.Translation(h, 0, 0);
  69006. },
  69007. enumerable: true,
  69008. configurable: true
  69009. });
  69010. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69011. get: function () {
  69012. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69013. var h = (4 * meters) / this.hScreenSize;
  69014. return BABYLON.Matrix.Translation(-h, 0, 0);
  69015. },
  69016. enumerable: true,
  69017. configurable: true
  69018. });
  69019. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69020. get: function () {
  69021. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69022. },
  69023. enumerable: true,
  69024. configurable: true
  69025. });
  69026. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69027. get: function () {
  69028. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69029. },
  69030. enumerable: true,
  69031. configurable: true
  69032. });
  69033. VRCameraMetrics.GetDefault = function () {
  69034. var result = new VRCameraMetrics();
  69035. result.hResolution = 1280;
  69036. result.vResolution = 800;
  69037. result.hScreenSize = 0.149759993;
  69038. result.vScreenSize = 0.0935999975;
  69039. result.vScreenCenter = 0.0467999987;
  69040. result.eyeToScreenDistance = 0.0410000011;
  69041. result.lensSeparationDistance = 0.0635000020;
  69042. result.interpupillaryDistance = 0.0640000030;
  69043. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69044. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69045. result.postProcessScaleFactor = 1.714605507808412;
  69046. result.lensCenterOffset = 0.151976421;
  69047. return result;
  69048. };
  69049. return VRCameraMetrics;
  69050. }());
  69051. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69052. })(BABYLON || (BABYLON = {}));
  69053. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69054. var BABYLON;
  69055. (function (BABYLON) {
  69056. var WebVRFreeCamera = /** @class */ (function (_super) {
  69057. __extends(WebVRFreeCamera, _super);
  69058. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69059. if (webVROptions === void 0) { webVROptions = {}; }
  69060. var _this = _super.call(this, name, position, scene) || this;
  69061. _this.webVROptions = webVROptions;
  69062. _this._vrDevice = null;
  69063. _this.rawPose = null;
  69064. _this._specsVersion = "1.1";
  69065. _this._attached = false;
  69066. _this._descendants = [];
  69067. _this.devicePosition = BABYLON.Vector3.Zero();
  69068. _this.deviceScaleFactor = 1;
  69069. _this.controllers = [];
  69070. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69071. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69072. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69073. _this.minZ = 0.1;
  69074. //legacy support - the compensation boolean was removed.
  69075. if (arguments.length === 5) {
  69076. _this.webVROptions = arguments[4];
  69077. }
  69078. // default webVR options
  69079. if (_this.webVROptions.trackPosition == undefined) {
  69080. _this.webVROptions.trackPosition = true;
  69081. }
  69082. if (_this.webVROptions.controllerMeshes == undefined) {
  69083. _this.webVROptions.controllerMeshes = true;
  69084. }
  69085. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69086. _this.webVROptions.defaultLightingOnControllers = true;
  69087. }
  69088. _this.rotationQuaternion = new BABYLON.Quaternion();
  69089. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69090. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69091. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69092. }
  69093. //enable VR
  69094. var engine = _this.getEngine();
  69095. _this._onVREnabled = function (success) { if (success) {
  69096. _this.initControllers();
  69097. } };
  69098. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69099. engine.initWebVR().add(function (event) {
  69100. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69101. return;
  69102. }
  69103. _this._vrDevice = event.vrDisplay;
  69104. //reset the rig parameters.
  69105. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69106. if (_this._attached) {
  69107. _this.getEngine().enableVR();
  69108. }
  69109. });
  69110. if (typeof (VRFrameData) !== "undefined")
  69111. _this._frameData = new VRFrameData();
  69112. /**
  69113. * The idea behind the following lines:
  69114. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69115. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69116. * the second will not show it correctly.
  69117. *
  69118. * To solve this - each object that has the camera as parent will be added to a protected array.
  69119. * When the rig camera renders, it will take this array and set all of those to be its children.
  69120. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69121. * Amazing!
  69122. */
  69123. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69124. if (camera.parent === _this && _this.rigParenting) {
  69125. _this._descendants = _this.getDescendants(true, function (n) {
  69126. // don't take the cameras or the controllers!
  69127. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69128. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69129. return !isController && !isRigCamera;
  69130. });
  69131. _this._descendants.forEach(function (node) {
  69132. node.parent = camera;
  69133. });
  69134. }
  69135. });
  69136. scene.onAfterCameraRenderObservable.add(function (camera) {
  69137. if (camera.parent === _this && _this.rigParenting) {
  69138. _this._descendants.forEach(function (node) {
  69139. node.parent = _this;
  69140. });
  69141. }
  69142. });
  69143. return _this;
  69144. }
  69145. WebVRFreeCamera.prototype.dispose = function () {
  69146. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69147. _super.prototype.dispose.call(this);
  69148. };
  69149. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69150. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69151. var gp = _a[_i];
  69152. if (gp.hand === name) {
  69153. return gp;
  69154. }
  69155. }
  69156. return null;
  69157. };
  69158. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69159. get: function () {
  69160. if (!this._leftController) {
  69161. this._leftController = this.getControllerByName("left");
  69162. }
  69163. return this._leftController;
  69164. },
  69165. enumerable: true,
  69166. configurable: true
  69167. });
  69168. ;
  69169. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69170. get: function () {
  69171. if (!this._rightController) {
  69172. this._rightController = this.getControllerByName("right");
  69173. }
  69174. return this._rightController;
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. ;
  69180. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69181. if (length === void 0) { length = 100; }
  69182. if (this.leftCamera) {
  69183. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69184. }
  69185. else {
  69186. return _super.prototype.getForwardRay.call(this, length);
  69187. }
  69188. };
  69189. WebVRFreeCamera.prototype._checkInputs = function () {
  69190. if (this._vrDevice && this._vrDevice.isPresenting) {
  69191. this._vrDevice.getFrameData(this._frameData);
  69192. this.updateFromDevice(this._frameData.pose);
  69193. }
  69194. _super.prototype._checkInputs.call(this);
  69195. };
  69196. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69197. if (poseData && poseData.orientation) {
  69198. this.rawPose = poseData;
  69199. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69200. if (this.getScene().useRightHandedSystem) {
  69201. this.deviceRotationQuaternion.z *= -1;
  69202. this.deviceRotationQuaternion.w *= -1;
  69203. }
  69204. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69205. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69206. if (this.getScene().useRightHandedSystem) {
  69207. this.devicePosition.z *= -1;
  69208. }
  69209. }
  69210. }
  69211. };
  69212. /**
  69213. * WebVR's attach control will start broadcasting frames to the device.
  69214. * Note that in certain browsers (chrome for example) this function must be called
  69215. * within a user-interaction callback. Example:
  69216. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69217. *
  69218. * @param {HTMLElement} element
  69219. * @param {boolean} [noPreventDefault]
  69220. *
  69221. * @memberOf WebVRFreeCamera
  69222. */
  69223. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69224. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69225. this._attached = true;
  69226. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69227. if (this._vrDevice) {
  69228. this.getEngine().enableVR();
  69229. }
  69230. };
  69231. WebVRFreeCamera.prototype.detachControl = function (element) {
  69232. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69233. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69234. _super.prototype.detachControl.call(this, element);
  69235. this._attached = false;
  69236. this.getEngine().disableVR();
  69237. };
  69238. WebVRFreeCamera.prototype.getClassName = function () {
  69239. return "WebVRFreeCamera";
  69240. };
  69241. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69242. //uses the vrDisplay's "resetPose()".
  69243. //pitch and roll won't be affected.
  69244. this._vrDevice.resetPose();
  69245. };
  69246. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69247. var camLeft = this._rigCameras[0];
  69248. var camRight = this._rigCameras[1];
  69249. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69250. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69251. camLeft.position.copyFrom(this.devicePosition);
  69252. camRight.position.copyFrom(this.devicePosition);
  69253. };
  69254. /**
  69255. * This function is called by the two RIG cameras.
  69256. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69257. */
  69258. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69259. var _this = this;
  69260. //WebVR 1.1
  69261. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69262. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69263. if (!this.getScene().useRightHandedSystem) {
  69264. [2, 6, 8, 9, 14].forEach(function (num) {
  69265. _this._webvrViewMatrix.m[num] *= -1;
  69266. });
  69267. }
  69268. // update the camera rotation matrix
  69269. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69270. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69271. // Computing target and final matrix
  69272. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69273. var parentCamera = this._cameraRigParams["parentCamera"];
  69274. // should the view matrix be updated with scale and position offset?
  69275. if (parentCamera.deviceScaleFactor !== 1) {
  69276. this._webvrViewMatrix.invert();
  69277. // scale the position, if set
  69278. if (parentCamera.deviceScaleFactor) {
  69279. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69280. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69281. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69282. }
  69283. this._webvrViewMatrix.invert();
  69284. }
  69285. return this._webvrViewMatrix;
  69286. };
  69287. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69288. var _this = this;
  69289. var parentCamera = this.parent;
  69290. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69291. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69292. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69293. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69294. //babylon compatible matrix
  69295. if (!this.getScene().useRightHandedSystem) {
  69296. [8, 9, 10, 11].forEach(function (num) {
  69297. _this._projectionMatrix.m[num] *= -1;
  69298. });
  69299. }
  69300. return this._projectionMatrix;
  69301. };
  69302. WebVRFreeCamera.prototype.initControllers = function () {
  69303. var _this = this;
  69304. this.controllers = [];
  69305. var manager = this.getScene().gamepadManager;
  69306. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69307. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69308. var webVrController = gamepad;
  69309. if (webVrController.defaultModel) {
  69310. webVrController.defaultModel.setEnabled(false);
  69311. }
  69312. }
  69313. });
  69314. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69315. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69316. var webVrController_1 = gamepad;
  69317. if (_this.webVROptions.controllerMeshes) {
  69318. if (webVrController_1.defaultModel) {
  69319. webVrController_1.defaultModel.setEnabled(true);
  69320. }
  69321. else {
  69322. // Load the meshes
  69323. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69324. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69325. if (_this.webVROptions.defaultLightingOnControllers) {
  69326. if (!_this._lightOnControllers) {
  69327. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69328. }
  69329. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69330. var children = mesh.getChildren();
  69331. if (children.length !== 0) {
  69332. children.forEach(function (mesh) {
  69333. light.includedOnlyMeshes.push(mesh);
  69334. activateLightOnSubMeshes_1(mesh, light);
  69335. });
  69336. }
  69337. };
  69338. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69339. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69340. }
  69341. });
  69342. }
  69343. }
  69344. webVrController_1.attachToPoseControlledCamera(_this);
  69345. // since this is async - sanity check. Is the controller already stored?
  69346. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69347. //add to the controllers array
  69348. _this.controllers.push(webVrController_1);
  69349. //did we find enough controllers? Great! let the developer know.
  69350. if (_this.controllers.length >= 2) {
  69351. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69352. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69353. // So we're overriding setting left & right manually to be sure
  69354. var firstViveWandDetected = false;
  69355. for (var i = 0; i < _this.controllers.length; i++) {
  69356. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69357. if (!firstViveWandDetected) {
  69358. firstViveWandDetected = true;
  69359. _this.controllers[i].hand = "left";
  69360. }
  69361. else {
  69362. _this.controllers[i].hand = "right";
  69363. }
  69364. }
  69365. }
  69366. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69367. }
  69368. }
  69369. }
  69370. });
  69371. };
  69372. return WebVRFreeCamera;
  69373. }(BABYLON.FreeCamera));
  69374. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69375. })(BABYLON || (BABYLON = {}));
  69376. //# sourceMappingURL=babylon.webVRCamera.js.map
  69377. var BABYLON;
  69378. (function (BABYLON) {
  69379. // We're mainly based on the logic defined into the FreeCamera code
  69380. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69381. __extends(DeviceOrientationCamera, _super);
  69382. function DeviceOrientationCamera(name, position, scene) {
  69383. var _this = _super.call(this, name, position, scene) || this;
  69384. _this._quaternionCache = new BABYLON.Quaternion();
  69385. _this.inputs.addDeviceOrientation();
  69386. return _this;
  69387. }
  69388. DeviceOrientationCamera.prototype.getClassName = function () {
  69389. return "DeviceOrientationCamera";
  69390. };
  69391. DeviceOrientationCamera.prototype._checkInputs = function () {
  69392. _super.prototype._checkInputs.call(this);
  69393. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69394. if (this._initialQuaternion) {
  69395. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69396. }
  69397. };
  69398. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69399. var _this = this;
  69400. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69401. //can only work if this camera has a rotation quaternion already.
  69402. if (!this.rotationQuaternion)
  69403. return;
  69404. if (!this._initialQuaternion) {
  69405. this._initialQuaternion = new BABYLON.Quaternion();
  69406. }
  69407. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69408. ['x', 'y', 'z'].forEach(function (axisName) {
  69409. if (!axis[axisName]) {
  69410. _this._initialQuaternion[axisName] = 0;
  69411. }
  69412. else {
  69413. _this._initialQuaternion[axisName] *= -1;
  69414. }
  69415. });
  69416. this._initialQuaternion.normalize();
  69417. //force rotation update
  69418. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69419. };
  69420. return DeviceOrientationCamera;
  69421. }(BABYLON.FreeCamera));
  69422. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69423. })(BABYLON || (BABYLON = {}));
  69424. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69425. var BABYLON;
  69426. (function (BABYLON) {
  69427. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69428. __extends(VRDeviceOrientationFreeCamera, _super);
  69429. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69430. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69431. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69432. var _this = _super.call(this, name, position, scene) || this;
  69433. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69434. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69435. return _this;
  69436. }
  69437. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69438. return "VRDeviceOrientationFreeCamera";
  69439. };
  69440. return VRDeviceOrientationFreeCamera;
  69441. }(BABYLON.DeviceOrientationCamera));
  69442. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69443. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69444. __extends(VRDeviceOrientationGamepadCamera, _super);
  69445. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69446. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69447. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69448. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69449. _this.inputs.addGamepad();
  69450. return _this;
  69451. }
  69452. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69453. return "VRDeviceOrientationGamepadCamera";
  69454. };
  69455. return VRDeviceOrientationGamepadCamera;
  69456. }(VRDeviceOrientationFreeCamera));
  69457. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69458. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69459. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69460. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69461. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69462. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69463. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69464. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69465. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69466. _this.inputs.addVRDeviceOrientation();
  69467. return _this;
  69468. }
  69469. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69470. return "VRDeviceOrientationArcRotateCamera";
  69471. };
  69472. return VRDeviceOrientationArcRotateCamera;
  69473. }(BABYLON.ArcRotateCamera));
  69474. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69475. })(BABYLON || (BABYLON = {}));
  69476. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69477. var BABYLON;
  69478. (function (BABYLON) {
  69479. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69480. __extends(AnaglyphFreeCamera, _super);
  69481. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69482. var _this = _super.call(this, name, position, scene) || this;
  69483. _this.interaxialDistance = interaxialDistance;
  69484. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69485. return _this;
  69486. }
  69487. AnaglyphFreeCamera.prototype.getClassName = function () {
  69488. return "AnaglyphFreeCamera";
  69489. };
  69490. return AnaglyphFreeCamera;
  69491. }(BABYLON.FreeCamera));
  69492. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  69493. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  69494. __extends(AnaglyphArcRotateCamera, _super);
  69495. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  69496. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69497. _this.interaxialDistance = interaxialDistance;
  69498. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69499. return _this;
  69500. }
  69501. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  69502. return "AnaglyphArcRotateCamera";
  69503. };
  69504. return AnaglyphArcRotateCamera;
  69505. }(BABYLON.ArcRotateCamera));
  69506. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  69507. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  69508. __extends(AnaglyphGamepadCamera, _super);
  69509. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  69510. var _this = _super.call(this, name, position, scene) || this;
  69511. _this.interaxialDistance = interaxialDistance;
  69512. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69513. return _this;
  69514. }
  69515. AnaglyphGamepadCamera.prototype.getClassName = function () {
  69516. return "AnaglyphGamepadCamera";
  69517. };
  69518. return AnaglyphGamepadCamera;
  69519. }(BABYLON.GamepadCamera));
  69520. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  69521. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  69522. __extends(AnaglyphUniversalCamera, _super);
  69523. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  69524. var _this = _super.call(this, name, position, scene) || this;
  69525. _this.interaxialDistance = interaxialDistance;
  69526. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69527. return _this;
  69528. }
  69529. AnaglyphUniversalCamera.prototype.getClassName = function () {
  69530. return "AnaglyphUniversalCamera";
  69531. };
  69532. return AnaglyphUniversalCamera;
  69533. }(BABYLON.UniversalCamera));
  69534. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  69535. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  69536. __extends(StereoscopicFreeCamera, _super);
  69537. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69538. var _this = _super.call(this, name, position, scene) || this;
  69539. _this.interaxialDistance = interaxialDistance;
  69540. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69541. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69542. return _this;
  69543. }
  69544. StereoscopicFreeCamera.prototype.getClassName = function () {
  69545. return "StereoscopicFreeCamera";
  69546. };
  69547. return StereoscopicFreeCamera;
  69548. }(BABYLON.FreeCamera));
  69549. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  69550. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  69551. __extends(StereoscopicArcRotateCamera, _super);
  69552. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  69553. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69554. _this.interaxialDistance = interaxialDistance;
  69555. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69556. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69557. return _this;
  69558. }
  69559. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  69560. return "StereoscopicArcRotateCamera";
  69561. };
  69562. return StereoscopicArcRotateCamera;
  69563. }(BABYLON.ArcRotateCamera));
  69564. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  69565. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  69566. __extends(StereoscopicGamepadCamera, _super);
  69567. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69568. var _this = _super.call(this, name, position, scene) || this;
  69569. _this.interaxialDistance = interaxialDistance;
  69570. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69571. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69572. return _this;
  69573. }
  69574. StereoscopicGamepadCamera.prototype.getClassName = function () {
  69575. return "StereoscopicGamepadCamera";
  69576. };
  69577. return StereoscopicGamepadCamera;
  69578. }(BABYLON.GamepadCamera));
  69579. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  69580. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  69581. __extends(StereoscopicUniversalCamera, _super);
  69582. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  69583. var _this = _super.call(this, name, position, scene) || this;
  69584. _this.interaxialDistance = interaxialDistance;
  69585. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  69586. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  69587. return _this;
  69588. }
  69589. StereoscopicUniversalCamera.prototype.getClassName = function () {
  69590. return "StereoscopicUniversalCamera";
  69591. };
  69592. return StereoscopicUniversalCamera;
  69593. }(BABYLON.UniversalCamera));
  69594. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  69595. })(BABYLON || (BABYLON = {}));
  69596. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  69597. var BABYLON;
  69598. (function (BABYLON) {
  69599. var VRExperienceHelper = /** @class */ (function () {
  69600. function VRExperienceHelper(scene, webVROptions) {
  69601. if (webVROptions === void 0) { webVROptions = {}; }
  69602. var _this = this;
  69603. this.webVROptions = webVROptions;
  69604. // Can the system support WebVR, even if a headset isn't plugged in?
  69605. this._webVRsupported = false;
  69606. // If WebVR is supported, is a headset plugged in and are we ready to present?
  69607. this._webVRready = false;
  69608. // Are we waiting for the requestPresent callback to complete?
  69609. this._webVRrequesting = false;
  69610. // Are we presenting to the headset right now?
  69611. this._webVRpresenting = false;
  69612. // Are we presenting in the fullscreen fallback?
  69613. this._fullscreenVRpresenting = false;
  69614. this._scene = scene;
  69615. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  69616. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  69617. }
  69618. else {
  69619. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  69620. if (scene.activeCamera.rotation) {
  69621. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  69622. }
  69623. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  69624. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  69625. }
  69626. this._scene.activeCamera = this._deviceOrientationCamera;
  69627. this._position = this._scene.activeCamera.position;
  69628. this._canvas = scene.getEngine().getRenderingCanvas();
  69629. if (this._canvas) {
  69630. this._scene.activeCamera.attachControl(this._canvas);
  69631. }
  69632. this._btnVR = document.createElement("BUTTON");
  69633. this._btnVR.className = "babylonVRicon";
  69634. this._btnVR.id = "babylonVRiconbtn";
  69635. this._btnVR.title = "Click to switch to VR";
  69636. 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) }";
  69637. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  69638. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  69639. // css += ".babylonVRicon.vrdisplaysupported { }";
  69640. // css += ".babylonVRicon.vrdisplayready { }";
  69641. // css += ".babylonVRicon.vrdisplayrequesting { }";
  69642. var style = document.createElement('style');
  69643. style.appendChild(document.createTextNode(css));
  69644. document.getElementsByTagName('head')[0].appendChild(style);
  69645. if (this._canvas) {
  69646. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69647. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69648. this._btnVR.addEventListener("click", function () {
  69649. _this.enterVR();
  69650. });
  69651. window.addEventListener("resize", function () {
  69652. if (_this._canvas) {
  69653. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  69654. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  69655. }
  69656. if (_this._fullscreenVRpresenting && _this._webVRready) {
  69657. _this.exitVR();
  69658. }
  69659. });
  69660. }
  69661. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69662. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69663. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69664. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  69665. document.body.appendChild(this._btnVR);
  69666. // Exiting VR mode using 'ESC' key on desktop
  69667. this._onKeyDown = function (event) {
  69668. if (event.keyCode === 27 && _this.isInVRMode()) {
  69669. _this.exitVR();
  69670. }
  69671. };
  69672. document.addEventListener("keydown", this._onKeyDown);
  69673. // Exiting VR mode double tapping the touch screen
  69674. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  69675. if (_this.isInVRMode()) {
  69676. _this.exitVR();
  69677. if (_this._fullscreenVRpresenting) {
  69678. _this._scene.getEngine().switchFullscreen(true);
  69679. }
  69680. }
  69681. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  69682. // Listen for WebVR display changes
  69683. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  69684. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  69685. this._onVRRequestPresentStart = function () {
  69686. _this._webVRrequesting = true;
  69687. _this.updateButtonVisibility();
  69688. };
  69689. this._onVRRequestPresentComplete = function (success) {
  69690. _this._webVRrequesting = false;
  69691. _this.updateButtonVisibility();
  69692. };
  69693. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  69694. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  69695. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  69696. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69697. // Create the cameras
  69698. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  69699. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  69700. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  69701. this.updateButtonVisibility();
  69702. }
  69703. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  69704. if (this.onControllerMeshLoaded) {
  69705. this.onControllerMeshLoaded(webVRController);
  69706. }
  69707. };
  69708. VRExperienceHelper.prototype._onFullscreenChange = function () {
  69709. if (document.fullscreen !== undefined) {
  69710. this._fullscreenVRpresenting = document.fullscreen;
  69711. }
  69712. else if (document.mozFullScreen !== undefined) {
  69713. this._fullscreenVRpresenting = document.mozFullScreen;
  69714. }
  69715. else if (document.webkitIsFullScreen !== undefined) {
  69716. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  69717. }
  69718. else if (document.msIsFullScreen !== undefined) {
  69719. this._fullscreenVRpresenting = document.msIsFullScreen;
  69720. }
  69721. if (!this._fullscreenVRpresenting && this._canvas) {
  69722. this.exitVR();
  69723. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  69724. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  69725. }
  69726. };
  69727. VRExperienceHelper.prototype.isInVRMode = function () {
  69728. return this._webVRpresenting || this._fullscreenVRpresenting;
  69729. };
  69730. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  69731. var vrDisplay = this._scene.getEngine().getVRDevice();
  69732. if (vrDisplay) {
  69733. var wasPresenting = this._webVRpresenting;
  69734. // A VR display is connected
  69735. this._webVRpresenting = vrDisplay.isPresenting;
  69736. if (wasPresenting && !this._webVRpresenting)
  69737. this.exitVR();
  69738. }
  69739. else {
  69740. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  69741. }
  69742. this.updateButtonVisibility();
  69743. };
  69744. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  69745. this._webVRsupported = eventArgs.vrSupported;
  69746. this._webVRready = !!eventArgs.vrDisplay;
  69747. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  69748. this.updateButtonVisibility();
  69749. };
  69750. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  69751. if (!this._btnVR) {
  69752. return;
  69753. }
  69754. this._btnVR.className = "babylonVRicon";
  69755. if (this.isInVRMode()) {
  69756. this._btnVR.className += " vrdisplaypresenting";
  69757. }
  69758. else {
  69759. if (this._webVRready)
  69760. this._btnVR.className += " vrdisplayready";
  69761. if (this._webVRsupported)
  69762. this._btnVR.className += " vrdisplaysupported";
  69763. if (this._webVRrequesting)
  69764. this._btnVR.className += " vrdisplayrequesting";
  69765. }
  69766. };
  69767. /**
  69768. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  69769. * Otherwise, will use the fullscreen API.
  69770. */
  69771. VRExperienceHelper.prototype.enterVR = function () {
  69772. if (this.onEnteringVR) {
  69773. this.onEnteringVR();
  69774. }
  69775. if (this._webVRrequesting)
  69776. return;
  69777. // If WebVR is supported and a headset is connected
  69778. if (this._webVRready) {
  69779. if (!this._webVRpresenting) {
  69780. this._webVRCamera.position = this._position;
  69781. this._scene.activeCamera = this._webVRCamera;
  69782. }
  69783. }
  69784. else {
  69785. this._vrDeviceOrientationCamera.position = this._position;
  69786. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  69787. this._scene.getEngine().switchFullscreen(true);
  69788. this.updateButtonVisibility();
  69789. }
  69790. if (this._scene.activeCamera && this._canvas) {
  69791. this._scene.activeCamera.attachControl(this._canvas);
  69792. }
  69793. };
  69794. /**
  69795. * Attempt to exit VR, or fullscreen.
  69796. */
  69797. VRExperienceHelper.prototype.exitVR = function () {
  69798. if (this.onExitingVR) {
  69799. this.onExitingVR();
  69800. }
  69801. if (this._webVRpresenting) {
  69802. this._scene.getEngine().disableVR();
  69803. }
  69804. if (this._scene.activeCamera) {
  69805. this._position = this._scene.activeCamera.position;
  69806. }
  69807. this._deviceOrientationCamera.position = this._position;
  69808. this._scene.activeCamera = this._deviceOrientationCamera;
  69809. if (this._canvas) {
  69810. this._scene.activeCamera.attachControl(this._canvas);
  69811. }
  69812. this.updateButtonVisibility();
  69813. };
  69814. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  69815. get: function () {
  69816. return this._position;
  69817. },
  69818. set: function (value) {
  69819. this._position = value;
  69820. if (this._scene.activeCamera) {
  69821. this._scene.activeCamera.position = value;
  69822. }
  69823. },
  69824. enumerable: true,
  69825. configurable: true
  69826. });
  69827. VRExperienceHelper.prototype.dispose = function () {
  69828. if (this.isInVRMode()) {
  69829. this.exitVR();
  69830. }
  69831. this._deviceOrientationCamera.dispose();
  69832. if (this._webVRCamera) {
  69833. this._webVRCamera.dispose();
  69834. }
  69835. if (this._vrDeviceOrientationCamera) {
  69836. this._vrDeviceOrientationCamera.dispose();
  69837. }
  69838. document.body.removeChild(this._btnVR);
  69839. document.removeEventListener("keydown", this._onKeyDown);
  69840. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  69841. };
  69842. VRExperienceHelper.prototype.getClassName = function () {
  69843. return "VRExperienceHelper";
  69844. };
  69845. return VRExperienceHelper;
  69846. }());
  69847. BABYLON.VRExperienceHelper = VRExperienceHelper;
  69848. })(BABYLON || (BABYLON = {}));
  69849. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  69850. // Mainly based on these 2 articles :
  69851. // 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
  69852. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  69853. var BABYLON;
  69854. (function (BABYLON) {
  69855. var JoystickAxis;
  69856. (function (JoystickAxis) {
  69857. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  69858. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  69859. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  69860. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  69861. var VirtualJoystick = /** @class */ (function () {
  69862. function VirtualJoystick(leftJoystick) {
  69863. var _this = this;
  69864. if (leftJoystick) {
  69865. this._leftJoystick = true;
  69866. }
  69867. else {
  69868. this._leftJoystick = false;
  69869. }
  69870. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  69871. VirtualJoystick._globalJoystickIndex++;
  69872. // By default left & right arrow keys are moving the X
  69873. // and up & down keys are moving the Y
  69874. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  69875. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  69876. this.reverseLeftRight = false;
  69877. this.reverseUpDown = false;
  69878. // collections of pointers
  69879. this._touches = new BABYLON.StringDictionary();
  69880. this.deltaPosition = BABYLON.Vector3.Zero();
  69881. this._joystickSensibility = 25;
  69882. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69883. this._rotationSpeed = 25;
  69884. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  69885. this._rotateOnAxisRelativeToMesh = false;
  69886. this._onResize = function (evt) {
  69887. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69888. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69889. if (VirtualJoystick.vjCanvas) {
  69890. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  69891. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  69892. }
  69893. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  69894. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  69895. };
  69896. // injecting a canvas element on top of the canvas 3D game
  69897. if (!VirtualJoystick.vjCanvas) {
  69898. window.addEventListener("resize", this._onResize, false);
  69899. VirtualJoystick.vjCanvas = document.createElement("canvas");
  69900. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  69901. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  69902. VirtualJoystick.vjCanvas.width = window.innerWidth;
  69903. VirtualJoystick.vjCanvas.height = window.innerHeight;
  69904. VirtualJoystick.vjCanvas.style.width = "100%";
  69905. VirtualJoystick.vjCanvas.style.height = "100%";
  69906. VirtualJoystick.vjCanvas.style.position = "absolute";
  69907. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  69908. VirtualJoystick.vjCanvas.style.top = "0px";
  69909. VirtualJoystick.vjCanvas.style.left = "0px";
  69910. VirtualJoystick.vjCanvas.style.zIndex = "5";
  69911. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  69912. // Support for jQuery PEP polyfill
  69913. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  69914. var context = VirtualJoystick.vjCanvas.getContext('2d');
  69915. if (!context) {
  69916. throw new Error("Unable to create canvas for virtual joystick");
  69917. }
  69918. VirtualJoystick.vjCanvasContext = context;
  69919. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  69920. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  69921. document.body.appendChild(VirtualJoystick.vjCanvas);
  69922. }
  69923. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  69924. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  69925. this.pressed = false;
  69926. // default joystick color
  69927. this._joystickColor = "cyan";
  69928. this._joystickPointerID = -1;
  69929. // current joystick position
  69930. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  69931. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  69932. // origin joystick position
  69933. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  69934. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  69935. this._onPointerDownHandlerRef = function (evt) {
  69936. _this._onPointerDown(evt);
  69937. };
  69938. this._onPointerMoveHandlerRef = function (evt) {
  69939. _this._onPointerMove(evt);
  69940. };
  69941. this._onPointerOutHandlerRef = function (evt) {
  69942. _this._onPointerUp(evt);
  69943. };
  69944. this._onPointerUpHandlerRef = function (evt) {
  69945. _this._onPointerUp(evt);
  69946. };
  69947. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  69948. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  69949. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  69950. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  69951. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  69952. evt.preventDefault(); // Disables system menu
  69953. }, false);
  69954. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  69955. }
  69956. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  69957. this._joystickSensibility = newJoystickSensibility;
  69958. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  69959. };
  69960. VirtualJoystick.prototype._onPointerDown = function (e) {
  69961. var positionOnScreenCondition;
  69962. e.preventDefault();
  69963. if (this._leftJoystick === true) {
  69964. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  69965. }
  69966. else {
  69967. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  69968. }
  69969. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  69970. // First contact will be dedicated to the virtual joystick
  69971. this._joystickPointerID = e.pointerId;
  69972. this._joystickPointerStartPos.x = e.clientX;
  69973. this._joystickPointerStartPos.y = e.clientY;
  69974. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  69975. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  69976. this._deltaJoystickVector.x = 0;
  69977. this._deltaJoystickVector.y = 0;
  69978. this.pressed = true;
  69979. this._touches.add(e.pointerId.toString(), e);
  69980. }
  69981. else {
  69982. // You can only trigger the action buttons with a joystick declared
  69983. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  69984. this._action();
  69985. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  69986. }
  69987. }
  69988. };
  69989. VirtualJoystick.prototype._onPointerMove = function (e) {
  69990. // If the current pointer is the one associated to the joystick (first touch contact)
  69991. if (this._joystickPointerID == e.pointerId) {
  69992. this._joystickPointerPos.x = e.clientX;
  69993. this._joystickPointerPos.y = e.clientY;
  69994. this._deltaJoystickVector = this._joystickPointerPos.clone();
  69995. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  69996. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  69997. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  69998. switch (this._axisTargetedByLeftAndRight) {
  69999. case JoystickAxis.X:
  70000. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70001. break;
  70002. case JoystickAxis.Y:
  70003. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70004. break;
  70005. case JoystickAxis.Z:
  70006. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70007. break;
  70008. }
  70009. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70010. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70011. switch (this._axisTargetedByUpAndDown) {
  70012. case JoystickAxis.X:
  70013. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70014. break;
  70015. case JoystickAxis.Y:
  70016. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70017. break;
  70018. case JoystickAxis.Z:
  70019. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70020. break;
  70021. }
  70022. }
  70023. else {
  70024. var data = this._touches.get(e.pointerId.toString());
  70025. if (data) {
  70026. data.x = e.clientX;
  70027. data.y = e.clientY;
  70028. }
  70029. }
  70030. };
  70031. VirtualJoystick.prototype._onPointerUp = function (e) {
  70032. if (this._joystickPointerID == e.pointerId) {
  70033. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70034. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70035. this._joystickPointerID = -1;
  70036. this.pressed = false;
  70037. }
  70038. else {
  70039. var touch = this._touches.get(e.pointerId.toString());
  70040. if (touch) {
  70041. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70042. }
  70043. }
  70044. this._deltaJoystickVector.x = 0;
  70045. this._deltaJoystickVector.y = 0;
  70046. this._touches.remove(e.pointerId.toString());
  70047. };
  70048. /**
  70049. * Change the color of the virtual joystick
  70050. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70051. */
  70052. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70053. this._joystickColor = newColor;
  70054. };
  70055. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70056. this._action = action;
  70057. };
  70058. // Define which axis you'd like to control for left & right
  70059. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70060. switch (axis) {
  70061. case JoystickAxis.X:
  70062. case JoystickAxis.Y:
  70063. case JoystickAxis.Z:
  70064. this._axisTargetedByLeftAndRight = axis;
  70065. break;
  70066. default:
  70067. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70068. break;
  70069. }
  70070. };
  70071. // Define which axis you'd like to control for up & down
  70072. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70073. switch (axis) {
  70074. case JoystickAxis.X:
  70075. case JoystickAxis.Y:
  70076. case JoystickAxis.Z:
  70077. this._axisTargetedByUpAndDown = axis;
  70078. break;
  70079. default:
  70080. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70081. break;
  70082. }
  70083. };
  70084. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70085. var _this = this;
  70086. if (this.pressed) {
  70087. this._touches.forEach(function (key, touch) {
  70088. if (touch.pointerId === _this._joystickPointerID) {
  70089. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70090. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70091. VirtualJoystick.vjCanvasContext.beginPath();
  70092. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70094. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70095. VirtualJoystick.vjCanvasContext.stroke();
  70096. VirtualJoystick.vjCanvasContext.closePath();
  70097. VirtualJoystick.vjCanvasContext.beginPath();
  70098. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70099. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70101. VirtualJoystick.vjCanvasContext.stroke();
  70102. VirtualJoystick.vjCanvasContext.closePath();
  70103. VirtualJoystick.vjCanvasContext.beginPath();
  70104. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70105. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70106. VirtualJoystick.vjCanvasContext.stroke();
  70107. VirtualJoystick.vjCanvasContext.closePath();
  70108. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70109. }
  70110. else {
  70111. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70112. VirtualJoystick.vjCanvasContext.beginPath();
  70113. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70114. VirtualJoystick.vjCanvasContext.beginPath();
  70115. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70116. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70117. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70118. VirtualJoystick.vjCanvasContext.stroke();
  70119. VirtualJoystick.vjCanvasContext.closePath();
  70120. touch.prevX = touch.x;
  70121. touch.prevY = touch.y;
  70122. }
  70123. ;
  70124. });
  70125. }
  70126. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70127. };
  70128. VirtualJoystick.prototype.releaseCanvas = function () {
  70129. if (VirtualJoystick.vjCanvas) {
  70130. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70131. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70132. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70133. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70134. window.removeEventListener("resize", this._onResize);
  70135. document.body.removeChild(VirtualJoystick.vjCanvas);
  70136. VirtualJoystick.vjCanvas = null;
  70137. }
  70138. };
  70139. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70140. VirtualJoystick._globalJoystickIndex = 0;
  70141. return VirtualJoystick;
  70142. }());
  70143. BABYLON.VirtualJoystick = VirtualJoystick;
  70144. })(BABYLON || (BABYLON = {}));
  70145. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70146. var BABYLON;
  70147. (function (BABYLON) {
  70148. // We're mainly based on the logic defined into the FreeCamera code
  70149. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70150. __extends(VirtualJoysticksCamera, _super);
  70151. function VirtualJoysticksCamera(name, position, scene) {
  70152. var _this = _super.call(this, name, position, scene) || this;
  70153. _this.inputs.addVirtualJoystick();
  70154. return _this;
  70155. }
  70156. VirtualJoysticksCamera.prototype.getClassName = function () {
  70157. return "VirtualJoysticksCamera";
  70158. };
  70159. return VirtualJoysticksCamera;
  70160. }(BABYLON.FreeCamera));
  70161. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70162. })(BABYLON || (BABYLON = {}));
  70163. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70164. var BABYLON;
  70165. (function (BABYLON) {
  70166. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70167. function FreeCameraVirtualJoystickInput() {
  70168. }
  70169. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70170. return this._leftjoystick;
  70171. };
  70172. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70173. return this._rightjoystick;
  70174. };
  70175. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70176. if (this._leftjoystick) {
  70177. var camera = this.camera;
  70178. var speed = camera._computeLocalCameraSpeed() * 50;
  70179. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70180. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70181. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70182. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70183. if (!this._leftjoystick.pressed) {
  70184. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70185. }
  70186. if (!this._rightjoystick.pressed) {
  70187. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70188. }
  70189. }
  70190. };
  70191. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70192. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70193. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70194. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70195. this._leftjoystick.setJoystickSensibility(0.15);
  70196. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70197. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70198. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70199. this._rightjoystick.reverseUpDown = true;
  70200. this._rightjoystick.setJoystickSensibility(0.05);
  70201. this._rightjoystick.setJoystickColor("yellow");
  70202. };
  70203. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70204. this._leftjoystick.releaseCanvas();
  70205. this._rightjoystick.releaseCanvas();
  70206. };
  70207. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70208. return "FreeCameraVirtualJoystickInput";
  70209. };
  70210. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70211. return "virtualJoystick";
  70212. };
  70213. return FreeCameraVirtualJoystickInput;
  70214. }());
  70215. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70216. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70217. })(BABYLON || (BABYLON = {}));
  70218. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70219. var BABYLON;
  70220. (function (BABYLON) {
  70221. var SimplificationSettings = /** @class */ (function () {
  70222. function SimplificationSettings(quality, distance, optimizeMesh) {
  70223. this.quality = quality;
  70224. this.distance = distance;
  70225. this.optimizeMesh = optimizeMesh;
  70226. }
  70227. return SimplificationSettings;
  70228. }());
  70229. BABYLON.SimplificationSettings = SimplificationSettings;
  70230. var SimplificationQueue = /** @class */ (function () {
  70231. function SimplificationQueue() {
  70232. this.running = false;
  70233. this._simplificationArray = [];
  70234. }
  70235. SimplificationQueue.prototype.addTask = function (task) {
  70236. this._simplificationArray.push(task);
  70237. };
  70238. SimplificationQueue.prototype.executeNext = function () {
  70239. var task = this._simplificationArray.pop();
  70240. if (task) {
  70241. this.running = true;
  70242. this.runSimplification(task);
  70243. }
  70244. else {
  70245. this.running = false;
  70246. }
  70247. };
  70248. SimplificationQueue.prototype.runSimplification = function (task) {
  70249. var _this = this;
  70250. if (task.parallelProcessing) {
  70251. //parallel simplifier
  70252. task.settings.forEach(function (setting) {
  70253. var simplifier = _this.getSimplifier(task);
  70254. simplifier.simplify(setting, function (newMesh) {
  70255. task.mesh.addLODLevel(setting.distance, newMesh);
  70256. newMesh.isVisible = true;
  70257. //check if it is the last
  70258. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70259. //all done, run the success callback.
  70260. task.successCallback();
  70261. }
  70262. _this.executeNext();
  70263. });
  70264. });
  70265. }
  70266. else {
  70267. //single simplifier.
  70268. var simplifier = this.getSimplifier(task);
  70269. var runDecimation = function (setting, callback) {
  70270. simplifier.simplify(setting, function (newMesh) {
  70271. task.mesh.addLODLevel(setting.distance, newMesh);
  70272. newMesh.isVisible = true;
  70273. //run the next quality level
  70274. callback();
  70275. });
  70276. };
  70277. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70278. runDecimation(task.settings[loop.index], function () {
  70279. loop.executeNext();
  70280. });
  70281. }, function () {
  70282. //execution ended, run the success callback.
  70283. if (task.successCallback) {
  70284. task.successCallback();
  70285. }
  70286. _this.executeNext();
  70287. });
  70288. }
  70289. };
  70290. SimplificationQueue.prototype.getSimplifier = function (task) {
  70291. switch (task.simplificationType) {
  70292. case SimplificationType.QUADRATIC:
  70293. default:
  70294. return new QuadraticErrorSimplification(task.mesh);
  70295. }
  70296. };
  70297. return SimplificationQueue;
  70298. }());
  70299. BABYLON.SimplificationQueue = SimplificationQueue;
  70300. /**
  70301. * The implemented types of simplification.
  70302. * At the moment only Quadratic Error Decimation is implemented.
  70303. */
  70304. var SimplificationType;
  70305. (function (SimplificationType) {
  70306. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70307. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70308. var DecimationTriangle = /** @class */ (function () {
  70309. function DecimationTriangle(vertices) {
  70310. this.vertices = vertices;
  70311. this.error = new Array(4);
  70312. this.deleted = false;
  70313. this.isDirty = false;
  70314. this.deletePending = false;
  70315. this.borderFactor = 0;
  70316. }
  70317. return DecimationTriangle;
  70318. }());
  70319. BABYLON.DecimationTriangle = DecimationTriangle;
  70320. var DecimationVertex = /** @class */ (function () {
  70321. function DecimationVertex(position, id) {
  70322. this.position = position;
  70323. this.id = id;
  70324. this.isBorder = true;
  70325. this.q = new QuadraticMatrix();
  70326. this.triangleCount = 0;
  70327. this.triangleStart = 0;
  70328. this.originalOffsets = [];
  70329. }
  70330. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70331. this.position.copyFrom(newPosition);
  70332. };
  70333. return DecimationVertex;
  70334. }());
  70335. BABYLON.DecimationVertex = DecimationVertex;
  70336. var QuadraticMatrix = /** @class */ (function () {
  70337. function QuadraticMatrix(data) {
  70338. this.data = new Array(10);
  70339. for (var i = 0; i < 10; ++i) {
  70340. if (data && data[i]) {
  70341. this.data[i] = data[i];
  70342. }
  70343. else {
  70344. this.data[i] = 0;
  70345. }
  70346. }
  70347. }
  70348. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70349. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70350. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70351. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70352. return det;
  70353. };
  70354. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70355. for (var i = 0; i < 10; ++i) {
  70356. this.data[i] += matrix.data[i];
  70357. }
  70358. };
  70359. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70360. for (var i = 0; i < 10; ++i) {
  70361. this.data[i] += data[i];
  70362. }
  70363. };
  70364. QuadraticMatrix.prototype.add = function (matrix) {
  70365. var m = new QuadraticMatrix();
  70366. for (var i = 0; i < 10; ++i) {
  70367. m.data[i] = this.data[i] + matrix.data[i];
  70368. }
  70369. return m;
  70370. };
  70371. QuadraticMatrix.FromData = function (a, b, c, d) {
  70372. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70373. };
  70374. //returning an array to avoid garbage collection
  70375. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70376. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70377. };
  70378. return QuadraticMatrix;
  70379. }());
  70380. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70381. var Reference = /** @class */ (function () {
  70382. function Reference(vertexId, triangleId) {
  70383. this.vertexId = vertexId;
  70384. this.triangleId = triangleId;
  70385. }
  70386. return Reference;
  70387. }());
  70388. BABYLON.Reference = Reference;
  70389. /**
  70390. * An implementation of the Quadratic Error simplification algorithm.
  70391. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70392. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70393. * @author RaananW
  70394. */
  70395. var QuadraticErrorSimplification = /** @class */ (function () {
  70396. function QuadraticErrorSimplification(_mesh) {
  70397. this._mesh = _mesh;
  70398. this.initialized = false;
  70399. this.syncIterations = 5000;
  70400. this.aggressiveness = 7;
  70401. this.decimationIterations = 100;
  70402. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70403. }
  70404. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70405. var _this = this;
  70406. this.initDecimatedMesh();
  70407. //iterating through the submeshes array, one after the other.
  70408. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70409. _this.initWithMesh(loop.index, function () {
  70410. _this.runDecimation(settings, loop.index, function () {
  70411. loop.executeNext();
  70412. });
  70413. }, settings.optimizeMesh);
  70414. }, function () {
  70415. setTimeout(function () {
  70416. successCallback(_this._reconstructedMesh);
  70417. }, 0);
  70418. });
  70419. };
  70420. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70421. var _this = this;
  70422. var targetCount = ~~(this.triangles.length * settings.quality);
  70423. var deletedTriangles = 0;
  70424. var triangleCount = this.triangles.length;
  70425. var iterationFunction = function (iteration, callback) {
  70426. setTimeout(function () {
  70427. if (iteration % 5 === 0) {
  70428. _this.updateMesh(iteration === 0);
  70429. }
  70430. for (var i = 0; i < _this.triangles.length; ++i) {
  70431. _this.triangles[i].isDirty = false;
  70432. }
  70433. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70434. var trianglesIterator = function (i) {
  70435. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70436. var t = _this.triangles[tIdx];
  70437. if (!t)
  70438. return;
  70439. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70440. return;
  70441. }
  70442. for (var j = 0; j < 3; ++j) {
  70443. if (t.error[j] < threshold) {
  70444. var deleted0 = [];
  70445. var deleted1 = [];
  70446. var v0 = t.vertices[j];
  70447. var v1 = t.vertices[(j + 1) % 3];
  70448. if (v0.isBorder || v1.isBorder)
  70449. continue;
  70450. var p = BABYLON.Vector3.Zero();
  70451. var n = BABYLON.Vector3.Zero();
  70452. var uv = BABYLON.Vector2.Zero();
  70453. var color = new BABYLON.Color4(0, 0, 0, 1);
  70454. _this.calculateError(v0, v1, p, n, uv, color);
  70455. var delTr = new Array();
  70456. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70457. continue;
  70458. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70459. continue;
  70460. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70461. continue;
  70462. var uniqueArray = new Array();
  70463. delTr.forEach(function (deletedT) {
  70464. if (uniqueArray.indexOf(deletedT) === -1) {
  70465. deletedT.deletePending = true;
  70466. uniqueArray.push(deletedT);
  70467. }
  70468. });
  70469. if (uniqueArray.length % 2 !== 0) {
  70470. continue;
  70471. }
  70472. v0.q = v1.q.add(v0.q);
  70473. v0.updatePosition(p);
  70474. var tStart = _this.references.length;
  70475. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70476. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70477. var tCount = _this.references.length - tStart;
  70478. if (tCount <= v0.triangleCount) {
  70479. if (tCount) {
  70480. for (var c = 0; c < tCount; c++) {
  70481. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70482. }
  70483. }
  70484. }
  70485. else {
  70486. v0.triangleStart = tStart;
  70487. }
  70488. v0.triangleCount = tCount;
  70489. break;
  70490. }
  70491. }
  70492. };
  70493. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  70494. }, 0);
  70495. };
  70496. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  70497. if (triangleCount - deletedTriangles <= targetCount)
  70498. loop.breakLoop();
  70499. else {
  70500. iterationFunction(loop.index, function () {
  70501. loop.executeNext();
  70502. });
  70503. }
  70504. }, function () {
  70505. setTimeout(function () {
  70506. //reconstruct this part of the mesh
  70507. _this.reconstructMesh(submeshIndex);
  70508. successCallback();
  70509. }, 0);
  70510. });
  70511. };
  70512. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  70513. var _this = this;
  70514. this.vertices = [];
  70515. this.triangles = [];
  70516. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70517. var indices = this._mesh.getIndices();
  70518. var submesh = this._mesh.subMeshes[submeshIndex];
  70519. var findInVertices = function (positionToSearch) {
  70520. if (optimizeMesh) {
  70521. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  70522. if (_this.vertices[ii].position.equals(positionToSearch)) {
  70523. return _this.vertices[ii];
  70524. }
  70525. }
  70526. }
  70527. return null;
  70528. };
  70529. var vertexReferences = [];
  70530. var vertexInit = function (i) {
  70531. if (!positionData) {
  70532. return;
  70533. }
  70534. var offset = i + submesh.verticesStart;
  70535. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  70536. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  70537. vertex.originalOffsets.push(offset);
  70538. if (vertex.id === _this.vertices.length) {
  70539. _this.vertices.push(vertex);
  70540. }
  70541. vertexReferences.push(vertex.id);
  70542. };
  70543. //var totalVertices = mesh.getTotalVertices();
  70544. var totalVertices = submesh.verticesCount;
  70545. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  70546. var indicesInit = function (i) {
  70547. if (!indices) {
  70548. return;
  70549. }
  70550. var offset = (submesh.indexStart / 3) + i;
  70551. var pos = (offset * 3);
  70552. var i0 = indices[pos + 0];
  70553. var i1 = indices[pos + 1];
  70554. var i2 = indices[pos + 2];
  70555. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  70556. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  70557. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  70558. var triangle = new DecimationTriangle([v0, v1, v2]);
  70559. triangle.originalOffset = pos;
  70560. _this.triangles.push(triangle);
  70561. };
  70562. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  70563. _this.init(callback);
  70564. });
  70565. });
  70566. };
  70567. QuadraticErrorSimplification.prototype.init = function (callback) {
  70568. var _this = this;
  70569. var triangleInit1 = function (i) {
  70570. var t = _this.triangles[i];
  70571. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  70572. for (var j = 0; j < 3; j++) {
  70573. 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))));
  70574. }
  70575. };
  70576. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  70577. var triangleInit2 = function (i) {
  70578. var t = _this.triangles[i];
  70579. for (var j = 0; j < 3; ++j) {
  70580. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  70581. }
  70582. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70583. };
  70584. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  70585. _this.initialized = true;
  70586. callback();
  70587. });
  70588. });
  70589. };
  70590. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  70591. var newTriangles = [];
  70592. var i;
  70593. for (i = 0; i < this.vertices.length; ++i) {
  70594. this.vertices[i].triangleCount = 0;
  70595. }
  70596. var t;
  70597. var j;
  70598. for (i = 0; i < this.triangles.length; ++i) {
  70599. if (!this.triangles[i].deleted) {
  70600. t = this.triangles[i];
  70601. for (j = 0; j < 3; ++j) {
  70602. t.vertices[j].triangleCount = 1;
  70603. }
  70604. newTriangles.push(t);
  70605. }
  70606. }
  70607. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  70608. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  70609. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  70610. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  70611. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70612. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  70613. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  70614. var vertexCount = 0;
  70615. for (i = 0; i < this.vertices.length; ++i) {
  70616. var vertex = this.vertices[i];
  70617. vertex.id = vertexCount;
  70618. if (vertex.triangleCount) {
  70619. vertex.originalOffsets.forEach(function (originalOffset) {
  70620. if (!normalData) {
  70621. return;
  70622. }
  70623. newPositionData.push(vertex.position.x);
  70624. newPositionData.push(vertex.position.y);
  70625. newPositionData.push(vertex.position.z);
  70626. newNormalData.push(normalData[originalOffset * 3]);
  70627. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  70628. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  70629. if (uvs && uvs.length) {
  70630. newUVsData.push(uvs[(originalOffset * 2)]);
  70631. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  70632. }
  70633. else if (colorsData && colorsData.length) {
  70634. newColorsData.push(colorsData[(originalOffset * 4)]);
  70635. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  70636. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  70637. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  70638. }
  70639. ++vertexCount;
  70640. });
  70641. }
  70642. }
  70643. var startingIndex = this._reconstructedMesh.getTotalIndices();
  70644. var startingVertex = this._reconstructedMesh.getTotalVertices();
  70645. var submeshesArray = this._reconstructedMesh.subMeshes;
  70646. this._reconstructedMesh.subMeshes = [];
  70647. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  70648. var originalIndices = this._mesh.getIndices();
  70649. for (i = 0; i < newTriangles.length; ++i) {
  70650. t = newTriangles[i]; //now get the new referencing point for each vertex
  70651. [0, 1, 2].forEach(function (idx) {
  70652. var id = originalIndices[t.originalOffset + idx];
  70653. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  70654. if (offset < 0)
  70655. offset = 0;
  70656. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  70657. });
  70658. }
  70659. //overwriting the old vertex buffers and indices.
  70660. this._reconstructedMesh.setIndices(newIndicesArray);
  70661. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  70662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  70663. if (newUVsData.length > 0)
  70664. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  70665. if (newColorsData.length > 0)
  70666. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  70667. //create submesh
  70668. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  70669. if (submeshIndex > 0) {
  70670. this._reconstructedMesh.subMeshes = [];
  70671. submeshesArray.forEach(function (submesh) {
  70672. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  70673. });
  70674. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  70675. }
  70676. };
  70677. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  70678. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  70679. this._reconstructedMesh.material = this._mesh.material;
  70680. this._reconstructedMesh.parent = this._mesh.parent;
  70681. this._reconstructedMesh.isVisible = false;
  70682. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  70683. };
  70684. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  70685. for (var i = 0; i < vertex1.triangleCount; ++i) {
  70686. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  70687. if (t.deleted)
  70688. continue;
  70689. var s = this.references[vertex1.triangleStart + i].vertexId;
  70690. var v1 = t.vertices[(s + 1) % 3];
  70691. var v2 = t.vertices[(s + 2) % 3];
  70692. if ((v1 === vertex2 || v2 === vertex2)) {
  70693. deletedArray[i] = true;
  70694. delTr.push(t);
  70695. continue;
  70696. }
  70697. var d1 = v1.position.subtract(point);
  70698. d1 = d1.normalize();
  70699. var d2 = v2.position.subtract(point);
  70700. d2 = d2.normalize();
  70701. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  70702. return true;
  70703. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  70704. deletedArray[i] = false;
  70705. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  70706. return true;
  70707. }
  70708. return false;
  70709. };
  70710. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  70711. var newDeleted = deletedTriangles;
  70712. for (var i = 0; i < vertex.triangleCount; ++i) {
  70713. var ref = this.references[vertex.triangleStart + i];
  70714. var t = this.triangles[ref.triangleId];
  70715. if (t.deleted)
  70716. continue;
  70717. if (deletedArray[i] && t.deletePending) {
  70718. t.deleted = true;
  70719. newDeleted++;
  70720. continue;
  70721. }
  70722. t.vertices[ref.vertexId] = origVertex;
  70723. t.isDirty = true;
  70724. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  70725. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  70726. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  70727. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  70728. this.references.push(ref);
  70729. }
  70730. return newDeleted;
  70731. };
  70732. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  70733. for (var i = 0; i < this.vertices.length; ++i) {
  70734. var vCount = [];
  70735. var vId = [];
  70736. var v = this.vertices[i];
  70737. var j;
  70738. for (j = 0; j < v.triangleCount; ++j) {
  70739. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  70740. for (var ii = 0; ii < 3; ii++) {
  70741. var ofs = 0;
  70742. var vv = triangle.vertices[ii];
  70743. while (ofs < vCount.length) {
  70744. if (vId[ofs] === vv.id)
  70745. break;
  70746. ++ofs;
  70747. }
  70748. if (ofs === vCount.length) {
  70749. vCount.push(1);
  70750. vId.push(vv.id);
  70751. }
  70752. else {
  70753. vCount[ofs]++;
  70754. }
  70755. }
  70756. }
  70757. for (j = 0; j < vCount.length; ++j) {
  70758. if (vCount[j] === 1) {
  70759. this.vertices[vId[j]].isBorder = true;
  70760. }
  70761. else {
  70762. this.vertices[vId[j]].isBorder = false;
  70763. }
  70764. }
  70765. }
  70766. };
  70767. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  70768. if (identifyBorders === void 0) { identifyBorders = false; }
  70769. var i;
  70770. if (!identifyBorders) {
  70771. var newTrianglesVector = [];
  70772. for (i = 0; i < this.triangles.length; ++i) {
  70773. if (!this.triangles[i].deleted) {
  70774. newTrianglesVector.push(this.triangles[i]);
  70775. }
  70776. }
  70777. this.triangles = newTrianglesVector;
  70778. }
  70779. for (i = 0; i < this.vertices.length; ++i) {
  70780. this.vertices[i].triangleCount = 0;
  70781. this.vertices[i].triangleStart = 0;
  70782. }
  70783. var t;
  70784. var j;
  70785. var v;
  70786. for (i = 0; i < this.triangles.length; ++i) {
  70787. t = this.triangles[i];
  70788. for (j = 0; j < 3; ++j) {
  70789. v = t.vertices[j];
  70790. v.triangleCount++;
  70791. }
  70792. }
  70793. var tStart = 0;
  70794. for (i = 0; i < this.vertices.length; ++i) {
  70795. this.vertices[i].triangleStart = tStart;
  70796. tStart += this.vertices[i].triangleCount;
  70797. this.vertices[i].triangleCount = 0;
  70798. }
  70799. var newReferences = new Array(this.triangles.length * 3);
  70800. for (i = 0; i < this.triangles.length; ++i) {
  70801. t = this.triangles[i];
  70802. for (j = 0; j < 3; ++j) {
  70803. v = t.vertices[j];
  70804. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  70805. v.triangleCount++;
  70806. }
  70807. }
  70808. this.references = newReferences;
  70809. if (identifyBorders) {
  70810. this.identifyBorder();
  70811. }
  70812. };
  70813. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  70814. var x = point.x;
  70815. var y = point.y;
  70816. var z = point.z;
  70817. 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
  70818. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  70819. };
  70820. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  70821. var q = vertex1.q.add(vertex2.q);
  70822. var border = vertex1.isBorder && vertex2.isBorder;
  70823. var error = 0;
  70824. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  70825. if (qDet !== 0 && !border) {
  70826. if (!pointResult) {
  70827. pointResult = BABYLON.Vector3.Zero();
  70828. }
  70829. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  70830. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  70831. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  70832. error = this.vertexError(q, pointResult);
  70833. }
  70834. else {
  70835. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  70836. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  70837. var error1 = this.vertexError(q, vertex1.position);
  70838. var error2 = this.vertexError(q, vertex2.position);
  70839. var error3 = this.vertexError(q, p3);
  70840. error = Math.min(error1, error2, error3);
  70841. if (error === error1) {
  70842. if (pointResult) {
  70843. pointResult.copyFrom(vertex1.position);
  70844. }
  70845. }
  70846. else if (error === error2) {
  70847. if (pointResult) {
  70848. pointResult.copyFrom(vertex2.position);
  70849. }
  70850. }
  70851. else {
  70852. if (pointResult) {
  70853. pointResult.copyFrom(p3);
  70854. }
  70855. }
  70856. }
  70857. return error;
  70858. };
  70859. return QuadraticErrorSimplification;
  70860. }());
  70861. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  70862. })(BABYLON || (BABYLON = {}));
  70863. //# sourceMappingURL=babylon.meshSimplification.js.map
  70864. var BABYLON;
  70865. (function (BABYLON) {
  70866. var Internals;
  70867. (function (Internals) {
  70868. var MeshLODLevel = /** @class */ (function () {
  70869. function MeshLODLevel(distance, mesh) {
  70870. this.distance = distance;
  70871. this.mesh = mesh;
  70872. }
  70873. return MeshLODLevel;
  70874. }());
  70875. Internals.MeshLODLevel = MeshLODLevel;
  70876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70877. })(BABYLON || (BABYLON = {}));
  70878. //# sourceMappingURL=babylon.meshLODLevel.js.map
  70879. var BABYLON;
  70880. (function (BABYLON) {
  70881. // Standard optimizations
  70882. var SceneOptimization = /** @class */ (function () {
  70883. function SceneOptimization(priority) {
  70884. if (priority === void 0) { priority = 0; }
  70885. this.priority = priority;
  70886. this.apply = function (scene) {
  70887. return true; // Return true if everything that can be done was applied
  70888. };
  70889. }
  70890. return SceneOptimization;
  70891. }());
  70892. BABYLON.SceneOptimization = SceneOptimization;
  70893. var TextureOptimization = /** @class */ (function (_super) {
  70894. __extends(TextureOptimization, _super);
  70895. function TextureOptimization(priority, maximumSize) {
  70896. if (priority === void 0) { priority = 0; }
  70897. if (maximumSize === void 0) { maximumSize = 1024; }
  70898. var _this = _super.call(this, priority) || this;
  70899. _this.priority = priority;
  70900. _this.maximumSize = maximumSize;
  70901. _this.apply = function (scene) {
  70902. var allDone = true;
  70903. for (var index = 0; index < scene.textures.length; index++) {
  70904. var texture = scene.textures[index];
  70905. if (!texture.canRescale || texture.getContext) {
  70906. continue;
  70907. }
  70908. var currentSize = texture.getSize();
  70909. var maxDimension = Math.max(currentSize.width, currentSize.height);
  70910. if (maxDimension > _this.maximumSize) {
  70911. texture.scale(0.5);
  70912. allDone = false;
  70913. }
  70914. }
  70915. return allDone;
  70916. };
  70917. return _this;
  70918. }
  70919. return TextureOptimization;
  70920. }(SceneOptimization));
  70921. BABYLON.TextureOptimization = TextureOptimization;
  70922. var HardwareScalingOptimization = /** @class */ (function (_super) {
  70923. __extends(HardwareScalingOptimization, _super);
  70924. function HardwareScalingOptimization(priority, maximumScale) {
  70925. if (priority === void 0) { priority = 0; }
  70926. if (maximumScale === void 0) { maximumScale = 2; }
  70927. var _this = _super.call(this, priority) || this;
  70928. _this.priority = priority;
  70929. _this.maximumScale = maximumScale;
  70930. _this._currentScale = 1;
  70931. _this.apply = function (scene) {
  70932. _this._currentScale++;
  70933. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  70934. return _this._currentScale >= _this.maximumScale;
  70935. };
  70936. return _this;
  70937. }
  70938. return HardwareScalingOptimization;
  70939. }(SceneOptimization));
  70940. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  70941. var ShadowsOptimization = /** @class */ (function (_super) {
  70942. __extends(ShadowsOptimization, _super);
  70943. function ShadowsOptimization() {
  70944. var _this = _super !== null && _super.apply(this, arguments) || this;
  70945. _this.apply = function (scene) {
  70946. scene.shadowsEnabled = false;
  70947. return true;
  70948. };
  70949. return _this;
  70950. }
  70951. return ShadowsOptimization;
  70952. }(SceneOptimization));
  70953. BABYLON.ShadowsOptimization = ShadowsOptimization;
  70954. var PostProcessesOptimization = /** @class */ (function (_super) {
  70955. __extends(PostProcessesOptimization, _super);
  70956. function PostProcessesOptimization() {
  70957. var _this = _super !== null && _super.apply(this, arguments) || this;
  70958. _this.apply = function (scene) {
  70959. scene.postProcessesEnabled = false;
  70960. return true;
  70961. };
  70962. return _this;
  70963. }
  70964. return PostProcessesOptimization;
  70965. }(SceneOptimization));
  70966. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  70967. var LensFlaresOptimization = /** @class */ (function (_super) {
  70968. __extends(LensFlaresOptimization, _super);
  70969. function LensFlaresOptimization() {
  70970. var _this = _super !== null && _super.apply(this, arguments) || this;
  70971. _this.apply = function (scene) {
  70972. scene.lensFlaresEnabled = false;
  70973. return true;
  70974. };
  70975. return _this;
  70976. }
  70977. return LensFlaresOptimization;
  70978. }(SceneOptimization));
  70979. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  70980. var ParticlesOptimization = /** @class */ (function (_super) {
  70981. __extends(ParticlesOptimization, _super);
  70982. function ParticlesOptimization() {
  70983. var _this = _super !== null && _super.apply(this, arguments) || this;
  70984. _this.apply = function (scene) {
  70985. scene.particlesEnabled = false;
  70986. return true;
  70987. };
  70988. return _this;
  70989. }
  70990. return ParticlesOptimization;
  70991. }(SceneOptimization));
  70992. BABYLON.ParticlesOptimization = ParticlesOptimization;
  70993. var RenderTargetsOptimization = /** @class */ (function (_super) {
  70994. __extends(RenderTargetsOptimization, _super);
  70995. function RenderTargetsOptimization() {
  70996. var _this = _super !== null && _super.apply(this, arguments) || this;
  70997. _this.apply = function (scene) {
  70998. scene.renderTargetsEnabled = false;
  70999. return true;
  71000. };
  71001. return _this;
  71002. }
  71003. return RenderTargetsOptimization;
  71004. }(SceneOptimization));
  71005. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71006. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71007. __extends(MergeMeshesOptimization, _super);
  71008. function MergeMeshesOptimization() {
  71009. var _this = _super !== null && _super.apply(this, arguments) || this;
  71010. _this._canBeMerged = function (abstractMesh) {
  71011. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71012. return false;
  71013. }
  71014. var mesh = abstractMesh;
  71015. if (!mesh.isVisible || !mesh.isEnabled()) {
  71016. return false;
  71017. }
  71018. if (mesh.instances.length > 0) {
  71019. return false;
  71020. }
  71021. if (mesh.skeleton || mesh.hasLODLevels) {
  71022. return false;
  71023. }
  71024. if (mesh.parent) {
  71025. return false;
  71026. }
  71027. return true;
  71028. };
  71029. _this.apply = function (scene, updateSelectionTree) {
  71030. var globalPool = scene.meshes.slice(0);
  71031. var globalLength = globalPool.length;
  71032. for (var index = 0; index < globalLength; index++) {
  71033. var currentPool = new Array();
  71034. var current = globalPool[index];
  71035. // Checks
  71036. if (!_this._canBeMerged(current)) {
  71037. continue;
  71038. }
  71039. currentPool.push(current);
  71040. // Find compatible meshes
  71041. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71042. var otherMesh = globalPool[subIndex];
  71043. if (!_this._canBeMerged(otherMesh)) {
  71044. continue;
  71045. }
  71046. if (otherMesh.material !== current.material) {
  71047. continue;
  71048. }
  71049. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71050. continue;
  71051. }
  71052. currentPool.push(otherMesh);
  71053. globalLength--;
  71054. globalPool.splice(subIndex, 1);
  71055. subIndex--;
  71056. }
  71057. if (currentPool.length < 2) {
  71058. continue;
  71059. }
  71060. // Merge meshes
  71061. BABYLON.Mesh.MergeMeshes(currentPool);
  71062. }
  71063. if (updateSelectionTree != undefined) {
  71064. if (updateSelectionTree) {
  71065. scene.createOrUpdateSelectionOctree();
  71066. }
  71067. }
  71068. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71069. scene.createOrUpdateSelectionOctree();
  71070. }
  71071. return true;
  71072. };
  71073. return _this;
  71074. }
  71075. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71076. get: function () {
  71077. return MergeMeshesOptimization._UpdateSelectionTree;
  71078. },
  71079. set: function (value) {
  71080. MergeMeshesOptimization._UpdateSelectionTree = value;
  71081. },
  71082. enumerable: true,
  71083. configurable: true
  71084. });
  71085. MergeMeshesOptimization._UpdateSelectionTree = false;
  71086. return MergeMeshesOptimization;
  71087. }(SceneOptimization));
  71088. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71089. // Options
  71090. var SceneOptimizerOptions = /** @class */ (function () {
  71091. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71092. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71093. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71094. this.targetFrameRate = targetFrameRate;
  71095. this.trackerDuration = trackerDuration;
  71096. this.optimizations = new Array();
  71097. }
  71098. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71099. var result = new SceneOptimizerOptions(targetFrameRate);
  71100. var priority = 0;
  71101. result.optimizations.push(new MergeMeshesOptimization(priority));
  71102. result.optimizations.push(new ShadowsOptimization(priority));
  71103. result.optimizations.push(new LensFlaresOptimization(priority));
  71104. // Next priority
  71105. priority++;
  71106. result.optimizations.push(new PostProcessesOptimization(priority));
  71107. result.optimizations.push(new ParticlesOptimization(priority));
  71108. // Next priority
  71109. priority++;
  71110. result.optimizations.push(new TextureOptimization(priority, 1024));
  71111. return result;
  71112. };
  71113. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71114. var result = new SceneOptimizerOptions(targetFrameRate);
  71115. var priority = 0;
  71116. result.optimizations.push(new MergeMeshesOptimization(priority));
  71117. result.optimizations.push(new ShadowsOptimization(priority));
  71118. result.optimizations.push(new LensFlaresOptimization(priority));
  71119. // Next priority
  71120. priority++;
  71121. result.optimizations.push(new PostProcessesOptimization(priority));
  71122. result.optimizations.push(new ParticlesOptimization(priority));
  71123. // Next priority
  71124. priority++;
  71125. result.optimizations.push(new TextureOptimization(priority, 512));
  71126. // Next priority
  71127. priority++;
  71128. result.optimizations.push(new RenderTargetsOptimization(priority));
  71129. // Next priority
  71130. priority++;
  71131. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71132. return result;
  71133. };
  71134. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71135. var result = new SceneOptimizerOptions(targetFrameRate);
  71136. var priority = 0;
  71137. result.optimizations.push(new MergeMeshesOptimization(priority));
  71138. result.optimizations.push(new ShadowsOptimization(priority));
  71139. result.optimizations.push(new LensFlaresOptimization(priority));
  71140. // Next priority
  71141. priority++;
  71142. result.optimizations.push(new PostProcessesOptimization(priority));
  71143. result.optimizations.push(new ParticlesOptimization(priority));
  71144. // Next priority
  71145. priority++;
  71146. result.optimizations.push(new TextureOptimization(priority, 256));
  71147. // Next priority
  71148. priority++;
  71149. result.optimizations.push(new RenderTargetsOptimization(priority));
  71150. // Next priority
  71151. priority++;
  71152. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71153. return result;
  71154. };
  71155. return SceneOptimizerOptions;
  71156. }());
  71157. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71158. // Scene optimizer tool
  71159. var SceneOptimizer = /** @class */ (function () {
  71160. function SceneOptimizer() {
  71161. }
  71162. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71163. // TODO: add an epsilon
  71164. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71165. if (onSuccess) {
  71166. onSuccess();
  71167. }
  71168. return;
  71169. }
  71170. // Apply current level of optimizations
  71171. var allDone = true;
  71172. var noOptimizationApplied = true;
  71173. for (var index = 0; index < options.optimizations.length; index++) {
  71174. var optimization = options.optimizations[index];
  71175. if (optimization.priority === currentPriorityLevel) {
  71176. noOptimizationApplied = false;
  71177. allDone = allDone && optimization.apply(scene);
  71178. }
  71179. }
  71180. // If no optimization was applied, this is a failure :(
  71181. if (noOptimizationApplied) {
  71182. if (onFailure) {
  71183. onFailure();
  71184. }
  71185. return;
  71186. }
  71187. // If all optimizations were done, move to next level
  71188. if (allDone) {
  71189. currentPriorityLevel++;
  71190. }
  71191. // Let's the system running for a specific amount of time before checking FPS
  71192. scene.executeWhenReady(function () {
  71193. setTimeout(function () {
  71194. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71195. }, options.trackerDuration);
  71196. });
  71197. };
  71198. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71199. if (!options) {
  71200. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71201. }
  71202. // Let's the system running for a specific amount of time before checking FPS
  71203. scene.executeWhenReady(function () {
  71204. setTimeout(function () {
  71205. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71206. }, options.trackerDuration);
  71207. });
  71208. };
  71209. return SceneOptimizer;
  71210. }());
  71211. BABYLON.SceneOptimizer = SceneOptimizer;
  71212. })(BABYLON || (BABYLON = {}));
  71213. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71214. var BABYLON;
  71215. (function (BABYLON) {
  71216. var OutlineRenderer = /** @class */ (function () {
  71217. function OutlineRenderer(scene) {
  71218. this.zOffset = 1;
  71219. this._scene = scene;
  71220. }
  71221. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71222. var _this = this;
  71223. if (useOverlay === void 0) { useOverlay = false; }
  71224. var scene = this._scene;
  71225. var engine = this._scene.getEngine();
  71226. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71227. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71228. return;
  71229. }
  71230. var mesh = subMesh.getRenderingMesh();
  71231. var material = subMesh.getMaterial();
  71232. if (!material || !scene.activeCamera) {
  71233. return;
  71234. }
  71235. engine.enableEffect(this._effect);
  71236. // Logarithmic depth
  71237. if (material.useLogarithmicDepth) {
  71238. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71239. }
  71240. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71241. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71242. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71243. // Bones
  71244. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71245. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71246. }
  71247. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71248. // Alpha test
  71249. if (material && material.needAlphaTesting()) {
  71250. var alphaTexture = material.getAlphaTestTexture();
  71251. if (alphaTexture) {
  71252. this._effect.setTexture("diffuseSampler", alphaTexture);
  71253. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71254. }
  71255. }
  71256. engine.setZOffset(-this.zOffset);
  71257. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71258. engine.setZOffset(0);
  71259. };
  71260. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71261. var defines = [];
  71262. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71263. var mesh = subMesh.getMesh();
  71264. var material = subMesh.getMaterial();
  71265. if (material) {
  71266. // Alpha test
  71267. if (material.needAlphaTesting()) {
  71268. defines.push("#define ALPHATEST");
  71269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71270. attribs.push(BABYLON.VertexBuffer.UVKind);
  71271. defines.push("#define UV1");
  71272. }
  71273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71275. defines.push("#define UV2");
  71276. }
  71277. }
  71278. //Logarithmic depth
  71279. if (material.useLogarithmicDepth) {
  71280. defines.push("#define LOGARITHMICDEPTH");
  71281. }
  71282. }
  71283. // Bones
  71284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71287. if (mesh.numBoneInfluencers > 4) {
  71288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71290. }
  71291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71292. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71293. }
  71294. else {
  71295. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71296. }
  71297. // Instances
  71298. if (useInstances) {
  71299. defines.push("#define INSTANCES");
  71300. attribs.push("world0");
  71301. attribs.push("world1");
  71302. attribs.push("world2");
  71303. attribs.push("world3");
  71304. }
  71305. // Get correct effect
  71306. var join = defines.join("\n");
  71307. if (this._cachedDefines !== join) {
  71308. this._cachedDefines = join;
  71309. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71310. }
  71311. return this._effect.isReady();
  71312. };
  71313. return OutlineRenderer;
  71314. }());
  71315. BABYLON.OutlineRenderer = OutlineRenderer;
  71316. })(BABYLON || (BABYLON = {}));
  71317. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71318. var BABYLON;
  71319. (function (BABYLON) {
  71320. var FaceAdjacencies = /** @class */ (function () {
  71321. function FaceAdjacencies() {
  71322. this.edges = new Array();
  71323. this.edgesConnectedCount = 0;
  71324. }
  71325. return FaceAdjacencies;
  71326. }());
  71327. var EdgesRenderer = /** @class */ (function () {
  71328. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71329. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71330. if (epsilon === void 0) { epsilon = 0.95; }
  71331. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71332. this.edgesWidthScalerForOrthographic = 1000.0;
  71333. this.edgesWidthScalerForPerspective = 50.0;
  71334. this._linesPositions = new Array();
  71335. this._linesNormals = new Array();
  71336. this._linesIndices = new Array();
  71337. this._buffers = {};
  71338. this._checkVerticesInsteadOfIndices = false;
  71339. this._source = source;
  71340. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71341. this._epsilon = epsilon;
  71342. this._prepareRessources();
  71343. this._generateEdgesLines();
  71344. }
  71345. EdgesRenderer.prototype._prepareRessources = function () {
  71346. if (this._lineShader) {
  71347. return;
  71348. }
  71349. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71350. attributes: ["position", "normal"],
  71351. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71352. });
  71353. this._lineShader.disableDepthWrite = true;
  71354. this._lineShader.backFaceCulling = false;
  71355. };
  71356. EdgesRenderer.prototype._rebuild = function () {
  71357. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71358. if (buffer) {
  71359. buffer._rebuild();
  71360. }
  71361. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71362. if (buffer) {
  71363. buffer._rebuild();
  71364. }
  71365. var scene = this._source.getScene();
  71366. var engine = scene.getEngine();
  71367. this._ib = engine.createIndexBuffer(this._linesIndices);
  71368. };
  71369. EdgesRenderer.prototype.dispose = function () {
  71370. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71371. if (buffer) {
  71372. buffer.dispose();
  71373. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71374. }
  71375. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71376. if (buffer) {
  71377. buffer.dispose();
  71378. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71379. }
  71380. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71381. this._lineShader.dispose();
  71382. };
  71383. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71384. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71385. return 0;
  71386. }
  71387. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71388. return 1;
  71389. }
  71390. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71391. return 2;
  71392. }
  71393. return -1;
  71394. };
  71395. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71396. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71397. return 0;
  71398. }
  71399. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71400. return 1;
  71401. }
  71402. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71403. return 2;
  71404. }
  71405. return -1;
  71406. };
  71407. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71408. var needToCreateLine;
  71409. if (edge === undefined) {
  71410. needToCreateLine = true;
  71411. }
  71412. else {
  71413. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71414. needToCreateLine = dotProduct < this._epsilon;
  71415. }
  71416. if (needToCreateLine) {
  71417. var offset = this._linesPositions.length / 3;
  71418. var normal = p0.subtract(p1);
  71419. normal.normalize();
  71420. // Positions
  71421. this._linesPositions.push(p0.x);
  71422. this._linesPositions.push(p0.y);
  71423. this._linesPositions.push(p0.z);
  71424. this._linesPositions.push(p0.x);
  71425. this._linesPositions.push(p0.y);
  71426. this._linesPositions.push(p0.z);
  71427. this._linesPositions.push(p1.x);
  71428. this._linesPositions.push(p1.y);
  71429. this._linesPositions.push(p1.z);
  71430. this._linesPositions.push(p1.x);
  71431. this._linesPositions.push(p1.y);
  71432. this._linesPositions.push(p1.z);
  71433. // Normals
  71434. this._linesNormals.push(p1.x);
  71435. this._linesNormals.push(p1.y);
  71436. this._linesNormals.push(p1.z);
  71437. this._linesNormals.push(-1);
  71438. this._linesNormals.push(p1.x);
  71439. this._linesNormals.push(p1.y);
  71440. this._linesNormals.push(p1.z);
  71441. this._linesNormals.push(1);
  71442. this._linesNormals.push(p0.x);
  71443. this._linesNormals.push(p0.y);
  71444. this._linesNormals.push(p0.z);
  71445. this._linesNormals.push(-1);
  71446. this._linesNormals.push(p0.x);
  71447. this._linesNormals.push(p0.y);
  71448. this._linesNormals.push(p0.z);
  71449. this._linesNormals.push(1);
  71450. // Indices
  71451. this._linesIndices.push(offset);
  71452. this._linesIndices.push(offset + 1);
  71453. this._linesIndices.push(offset + 2);
  71454. this._linesIndices.push(offset);
  71455. this._linesIndices.push(offset + 2);
  71456. this._linesIndices.push(offset + 3);
  71457. }
  71458. };
  71459. EdgesRenderer.prototype._generateEdgesLines = function () {
  71460. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71461. var indices = this._source.getIndices();
  71462. if (!indices || !positions) {
  71463. return;
  71464. }
  71465. // First let's find adjacencies
  71466. var adjacencies = new Array();
  71467. var faceNormals = new Array();
  71468. var index;
  71469. var faceAdjacencies;
  71470. // Prepare faces
  71471. for (index = 0; index < indices.length; index += 3) {
  71472. faceAdjacencies = new FaceAdjacencies();
  71473. var p0Index = indices[index];
  71474. var p1Index = indices[index + 1];
  71475. var p2Index = indices[index + 2];
  71476. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71477. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71478. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71479. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71480. faceNormal.normalize();
  71481. faceNormals.push(faceNormal);
  71482. adjacencies.push(faceAdjacencies);
  71483. }
  71484. // Scan
  71485. for (index = 0; index < adjacencies.length; index++) {
  71486. faceAdjacencies = adjacencies[index];
  71487. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71488. var otherFaceAdjacencies = adjacencies[otherIndex];
  71489. if (faceAdjacencies.edgesConnectedCount === 3) {
  71490. break;
  71491. }
  71492. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  71493. continue;
  71494. }
  71495. var otherP0 = indices[otherIndex * 3];
  71496. var otherP1 = indices[otherIndex * 3 + 1];
  71497. var otherP2 = indices[otherIndex * 3 + 2];
  71498. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  71499. var otherEdgeIndex = 0;
  71500. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  71501. continue;
  71502. }
  71503. switch (edgeIndex) {
  71504. case 0:
  71505. if (this._checkVerticesInsteadOfIndices) {
  71506. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71507. }
  71508. else {
  71509. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  71510. }
  71511. break;
  71512. case 1:
  71513. if (this._checkVerticesInsteadOfIndices) {
  71514. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71515. }
  71516. else {
  71517. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  71518. }
  71519. break;
  71520. case 2:
  71521. if (this._checkVerticesInsteadOfIndices) {
  71522. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  71523. }
  71524. else {
  71525. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  71526. }
  71527. break;
  71528. }
  71529. if (otherEdgeIndex === -1) {
  71530. continue;
  71531. }
  71532. faceAdjacencies.edges[edgeIndex] = otherIndex;
  71533. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  71534. faceAdjacencies.edgesConnectedCount++;
  71535. otherFaceAdjacencies.edgesConnectedCount++;
  71536. if (faceAdjacencies.edgesConnectedCount === 3) {
  71537. break;
  71538. }
  71539. }
  71540. }
  71541. }
  71542. // Create lines
  71543. for (index = 0; index < adjacencies.length; index++) {
  71544. // 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
  71545. var current = adjacencies[index];
  71546. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  71547. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  71548. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  71549. }
  71550. // Merge into a single mesh
  71551. var engine = this._source.getScene().getEngine();
  71552. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  71553. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  71554. this._ib = engine.createIndexBuffer(this._linesIndices);
  71555. this._indicesCount = this._linesIndices.length;
  71556. };
  71557. EdgesRenderer.prototype.render = function () {
  71558. var scene = this._source.getScene();
  71559. if (!this._lineShader.isReady() || !scene.activeCamera) {
  71560. return;
  71561. }
  71562. var engine = scene.getEngine();
  71563. this._lineShader._preBind();
  71564. // VBOs
  71565. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  71566. scene.resetCachedMaterial();
  71567. this._lineShader.setColor4("color", this._source.edgesColor);
  71568. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  71569. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  71570. }
  71571. else {
  71572. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  71573. }
  71574. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  71575. this._lineShader.bind(this._source.getWorldMatrix());
  71576. // Draw order
  71577. engine.draw(true, 0, this._indicesCount);
  71578. this._lineShader.unbind();
  71579. engine.setDepthWrite(true);
  71580. };
  71581. return EdgesRenderer;
  71582. }());
  71583. BABYLON.EdgesRenderer = EdgesRenderer;
  71584. })(BABYLON || (BABYLON = {}));
  71585. //# sourceMappingURL=babylon.edgesRenderer.js.map
  71586. var BABYLON;
  71587. (function (BABYLON) {
  71588. /**
  71589. * Special Glow Blur post process only blurring the alpha channel
  71590. * It enforces keeping the most luminous color in the color channel.
  71591. */
  71592. var GlowBlurPostProcess = /** @class */ (function (_super) {
  71593. __extends(GlowBlurPostProcess, _super);
  71594. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  71595. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71596. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  71597. _this.direction = direction;
  71598. _this.kernel = kernel;
  71599. _this.onApplyObservable.add(function (effect) {
  71600. effect.setFloat2("screenSize", _this.width, _this.height);
  71601. effect.setVector2("direction", _this.direction);
  71602. effect.setFloat("blurWidth", _this.kernel);
  71603. });
  71604. return _this;
  71605. }
  71606. return GlowBlurPostProcess;
  71607. }(BABYLON.PostProcess));
  71608. /**
  71609. * The highlight layer Helps adding a glow effect around a mesh.
  71610. *
  71611. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  71612. * glowy meshes to your scene.
  71613. *
  71614. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  71615. */
  71616. var HighlightLayer = /** @class */ (function () {
  71617. /**
  71618. * Instantiates a new highlight Layer and references it to the scene..
  71619. * @param name The name of the layer
  71620. * @param scene The scene to use the layer in
  71621. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  71622. */
  71623. function HighlightLayer(name, scene, options) {
  71624. this.name = name;
  71625. this._vertexBuffers = {};
  71626. this._mainTextureDesiredSize = { width: 0, height: 0 };
  71627. this._meshes = {};
  71628. this._maxSize = 0;
  71629. this._shouldRender = false;
  71630. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  71631. this._excludedMeshes = {};
  71632. /**
  71633. * Specifies whether or not the inner glow is ACTIVE in the layer.
  71634. */
  71635. this.innerGlow = true;
  71636. /**
  71637. * Specifies whether or not the outer glow is ACTIVE in the layer.
  71638. */
  71639. this.outerGlow = true;
  71640. /**
  71641. * Specifies wether the highlight layer is enabled or not.
  71642. */
  71643. this.isEnabled = true;
  71644. /**
  71645. * An event triggered when the highlight layer has been disposed.
  71646. * @type {BABYLON.Observable}
  71647. */
  71648. this.onDisposeObservable = new BABYLON.Observable();
  71649. /**
  71650. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  71651. * @type {BABYLON.Observable}
  71652. */
  71653. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  71654. /**
  71655. * An event triggered when the highlight layer is being blurred.
  71656. * @type {BABYLON.Observable}
  71657. */
  71658. this.onBeforeBlurObservable = new BABYLON.Observable();
  71659. /**
  71660. * An event triggered when the highlight layer has been blurred.
  71661. * @type {BABYLON.Observable}
  71662. */
  71663. this.onAfterBlurObservable = new BABYLON.Observable();
  71664. /**
  71665. * An event triggered when the glowing blurred texture is being merged in the scene.
  71666. * @type {BABYLON.Observable}
  71667. */
  71668. this.onBeforeComposeObservable = new BABYLON.Observable();
  71669. /**
  71670. * An event triggered when the glowing blurred texture has been merged in the scene.
  71671. * @type {BABYLON.Observable}
  71672. */
  71673. this.onAfterComposeObservable = new BABYLON.Observable();
  71674. /**
  71675. * An event triggered when the highlight layer changes its size.
  71676. * @type {BABYLON.Observable}
  71677. */
  71678. this.onSizeChangedObservable = new BABYLON.Observable();
  71679. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71680. var engine = scene.getEngine();
  71681. this._engine = engine;
  71682. this._maxSize = this._engine.getCaps().maxTextureSize;
  71683. this._scene.highlightLayers.push(this);
  71684. // Warn on stencil.
  71685. if (!this._engine.isStencilEnable) {
  71686. 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 }");
  71687. }
  71688. // Adapt options
  71689. this._options = options || {
  71690. mainTextureRatio: 0.5,
  71691. blurTextureSizeRatio: 0.5,
  71692. blurHorizontalSize: 1.0,
  71693. blurVerticalSize: 1.0,
  71694. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  71695. camera: null
  71696. };
  71697. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  71698. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  71699. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  71700. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  71701. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  71702. // VBO
  71703. var vertices = [];
  71704. vertices.push(1, 1);
  71705. vertices.push(-1, 1);
  71706. vertices.push(-1, -1);
  71707. vertices.push(1, -1);
  71708. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71710. this._createIndexBuffer();
  71711. // Effect
  71712. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  71713. // Render target
  71714. this.setMainTextureSize();
  71715. // Create Textures and post processes
  71716. this.createTextureAndPostProcesses();
  71717. }
  71718. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  71719. /**
  71720. * Gets the horizontal size of the blur.
  71721. */
  71722. get: function () {
  71723. return this._horizontalBlurPostprocess.kernel;
  71724. },
  71725. /**
  71726. * Specifies the horizontal size of the blur.
  71727. */
  71728. set: function (value) {
  71729. this._horizontalBlurPostprocess.kernel = value;
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  71735. /**
  71736. * Gets the vertical size of the blur.
  71737. */
  71738. get: function () {
  71739. return this._verticalBlurPostprocess.kernel;
  71740. },
  71741. /**
  71742. * Specifies the vertical size of the blur.
  71743. */
  71744. set: function (value) {
  71745. this._verticalBlurPostprocess.kernel = value;
  71746. },
  71747. enumerable: true,
  71748. configurable: true
  71749. });
  71750. Object.defineProperty(HighlightLayer.prototype, "camera", {
  71751. /**
  71752. * Gets the camera attached to the layer.
  71753. */
  71754. get: function () {
  71755. return this._options.camera;
  71756. },
  71757. enumerable: true,
  71758. configurable: true
  71759. });
  71760. HighlightLayer.prototype._createIndexBuffer = function () {
  71761. var engine = this._scene.getEngine();
  71762. // Indices
  71763. var indices = [];
  71764. indices.push(0);
  71765. indices.push(1);
  71766. indices.push(2);
  71767. indices.push(0);
  71768. indices.push(2);
  71769. indices.push(3);
  71770. this._indexBuffer = engine.createIndexBuffer(indices);
  71771. };
  71772. HighlightLayer.prototype._rebuild = function () {
  71773. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71774. if (vb) {
  71775. vb._rebuild();
  71776. }
  71777. this._createIndexBuffer();
  71778. };
  71779. /**
  71780. * Creates the render target textures and post processes used in the highlight layer.
  71781. */
  71782. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  71783. var _this = this;
  71784. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  71785. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  71786. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  71787. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  71788. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  71789. width: this._mainTextureDesiredSize.width,
  71790. height: this._mainTextureDesiredSize.height
  71791. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71792. this._mainTexture.activeCamera = this._options.camera;
  71793. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71794. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71795. this._mainTexture.anisotropicFilteringLevel = 1;
  71796. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71797. this._mainTexture.renderParticles = false;
  71798. this._mainTexture.renderList = null;
  71799. this._mainTexture.ignoreCameraViewport = true;
  71800. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  71801. width: blurTextureWidth,
  71802. height: blurTextureHeight
  71803. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71804. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71805. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71806. this._blurTexture.anisotropicFilteringLevel = 16;
  71807. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71808. this._blurTexture.renderParticles = false;
  71809. this._blurTexture.ignoreCameraViewport = true;
  71810. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71811. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  71812. effect.setTexture("textureSampler", _this._mainTexture);
  71813. });
  71814. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  71815. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71816. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71817. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71818. });
  71819. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71820. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71821. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71822. });
  71823. }
  71824. else {
  71825. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71826. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  71827. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71828. });
  71829. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  71830. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  71831. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  71832. });
  71833. }
  71834. this._mainTexture.onAfterUnbindObservable.add(function () {
  71835. _this.onBeforeBlurObservable.notifyObservers(_this);
  71836. var internalTexture = _this._blurTexture.getInternalTexture();
  71837. if (internalTexture) {
  71838. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  71839. }
  71840. _this.onAfterBlurObservable.notifyObservers(_this);
  71841. });
  71842. // Custom render function
  71843. var renderSubMesh = function (subMesh) {
  71844. if (!_this._meshes) {
  71845. return;
  71846. }
  71847. var material = subMesh.getMaterial();
  71848. var mesh = subMesh.getRenderingMesh();
  71849. var scene = _this._scene;
  71850. var engine = scene.getEngine();
  71851. if (!material) {
  71852. return;
  71853. }
  71854. // Culling
  71855. engine.setState(material.backFaceCulling);
  71856. // Managing instances
  71857. var batch = mesh._getInstancesRenderList(subMesh._id);
  71858. if (batch.mustReturn) {
  71859. return;
  71860. }
  71861. // Excluded Mesh
  71862. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  71863. return;
  71864. }
  71865. ;
  71866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71867. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  71868. var emissiveTexture = null;
  71869. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  71870. emissiveTexture = material.emissiveTexture;
  71871. }
  71872. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  71873. engine.enableEffect(_this._glowMapGenerationEffect);
  71874. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  71875. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  71876. if (highlightLayerMesh) {
  71877. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  71878. }
  71879. else {
  71880. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  71881. }
  71882. // Alpha test
  71883. if (material && material.needAlphaTesting()) {
  71884. var alphaTexture = material.getAlphaTestTexture();
  71885. if (alphaTexture) {
  71886. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  71887. var textureMatrix = alphaTexture.getTextureMatrix();
  71888. if (textureMatrix) {
  71889. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  71890. }
  71891. }
  71892. }
  71893. // Glow emissive only
  71894. if (emissiveTexture) {
  71895. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  71896. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  71897. }
  71898. // Bones
  71899. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71900. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71901. }
  71902. // Draw
  71903. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  71904. }
  71905. else {
  71906. // Need to reset refresh rate of the shadowMap
  71907. _this._mainTexture.resetRefreshCounter();
  71908. }
  71909. };
  71910. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71911. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  71912. var index;
  71913. var engine = _this._scene.getEngine();
  71914. if (depthOnlySubMeshes.length) {
  71915. engine.setColorWrite(false);
  71916. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71917. renderSubMesh(depthOnlySubMeshes.data[index]);
  71918. }
  71919. engine.setColorWrite(true);
  71920. }
  71921. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71922. renderSubMesh(opaqueSubMeshes.data[index]);
  71923. }
  71924. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71925. renderSubMesh(alphaTestSubMeshes.data[index]);
  71926. }
  71927. for (index = 0; index < transparentSubMeshes.length; index++) {
  71928. renderSubMesh(transparentSubMeshes.data[index]);
  71929. }
  71930. };
  71931. this._mainTexture.onClearObservable.add(function (engine) {
  71932. engine.clear(HighlightLayer.neutralColor, true, true, true);
  71933. });
  71934. };
  71935. /**
  71936. * Checks for the readiness of the element composing the layer.
  71937. * @param subMesh the mesh to check for
  71938. * @param useInstances specify wether or not to use instances to render the mesh
  71939. * @param emissiveTexture the associated emissive texture used to generate the glow
  71940. * @return true if ready otherwise, false
  71941. */
  71942. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  71943. var material = subMesh.getMaterial();
  71944. if (!material) {
  71945. return false;
  71946. }
  71947. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  71948. return false;
  71949. }
  71950. var defines = [];
  71951. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71952. var mesh = subMesh.getMesh();
  71953. var uv1 = false;
  71954. var uv2 = false;
  71955. // Alpha test
  71956. if (material && material.needAlphaTesting()) {
  71957. var alphaTexture = material.getAlphaTestTexture();
  71958. if (alphaTexture) {
  71959. defines.push("#define ALPHATEST");
  71960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71961. alphaTexture.coordinatesIndex === 1) {
  71962. defines.push("#define DIFFUSEUV2");
  71963. uv2 = true;
  71964. }
  71965. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71966. defines.push("#define DIFFUSEUV1");
  71967. uv1 = true;
  71968. }
  71969. }
  71970. }
  71971. // Emissive
  71972. if (emissiveTexture) {
  71973. defines.push("#define EMISSIVE");
  71974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  71975. emissiveTexture.coordinatesIndex === 1) {
  71976. defines.push("#define EMISSIVEUV2");
  71977. uv2 = true;
  71978. }
  71979. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71980. defines.push("#define EMISSIVEUV1");
  71981. uv1 = true;
  71982. }
  71983. }
  71984. if (uv1) {
  71985. attribs.push(BABYLON.VertexBuffer.UVKind);
  71986. defines.push("#define UV1");
  71987. }
  71988. if (uv2) {
  71989. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71990. defines.push("#define UV2");
  71991. }
  71992. // Bones
  71993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71996. if (mesh.numBoneInfluencers > 4) {
  71997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71999. }
  72000. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72001. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72002. }
  72003. else {
  72004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72005. }
  72006. // Instances
  72007. if (useInstances) {
  72008. defines.push("#define INSTANCES");
  72009. attribs.push("world0");
  72010. attribs.push("world1");
  72011. attribs.push("world2");
  72012. attribs.push("world3");
  72013. }
  72014. // Get correct effect
  72015. var join = defines.join("\n");
  72016. if (this._cachedDefines !== join) {
  72017. this._cachedDefines = join;
  72018. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72019. }
  72020. return this._glowMapGenerationEffect.isReady();
  72021. };
  72022. /**
  72023. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72024. */
  72025. HighlightLayer.prototype.render = function () {
  72026. var currentEffect = this._glowMapMergeEffect;
  72027. // Check
  72028. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72029. return;
  72030. var engine = this._scene.getEngine();
  72031. this.onBeforeComposeObservable.notifyObservers(this);
  72032. // Render
  72033. engine.enableEffect(currentEffect);
  72034. engine.setState(false);
  72035. // Cache
  72036. var previousStencilBuffer = engine.getStencilBuffer();
  72037. var previousStencilFunction = engine.getStencilFunction();
  72038. var previousStencilMask = engine.getStencilMask();
  72039. var previousStencilOperationPass = engine.getStencilOperationPass();
  72040. var previousStencilOperationFail = engine.getStencilOperationFail();
  72041. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72042. var previousAlphaMode = engine.getAlphaMode();
  72043. // Texture
  72044. currentEffect.setTexture("textureSampler", this._blurTexture);
  72045. // VBOs
  72046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72047. // Stencil operations
  72048. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72049. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72050. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72051. // Draw order
  72052. engine.setAlphaMode(this._options.alphaBlendingMode);
  72053. engine.setStencilMask(0x00);
  72054. engine.setStencilBuffer(true);
  72055. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72056. if (this.outerGlow) {
  72057. currentEffect.setFloat("offset", 0);
  72058. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72059. engine.draw(true, 0, 6);
  72060. }
  72061. if (this.innerGlow) {
  72062. currentEffect.setFloat("offset", 1);
  72063. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72064. engine.draw(true, 0, 6);
  72065. }
  72066. // Restore Cache
  72067. engine.setStencilFunction(previousStencilFunction);
  72068. engine.setStencilMask(previousStencilMask);
  72069. engine.setAlphaMode(previousAlphaMode);
  72070. engine.setStencilBuffer(previousStencilBuffer);
  72071. engine.setStencilOperationPass(previousStencilOperationPass);
  72072. engine.setStencilOperationFail(previousStencilOperationFail);
  72073. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72074. engine._stencilState.reset();
  72075. this.onAfterComposeObservable.notifyObservers(this);
  72076. // Handle size changes.
  72077. var size = this._mainTexture.getSize();
  72078. this.setMainTextureSize();
  72079. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72080. // Recreate RTT and post processes on size change.
  72081. this.onSizeChangedObservable.notifyObservers(this);
  72082. this.disposeTextureAndPostProcesses();
  72083. this.createTextureAndPostProcesses();
  72084. }
  72085. };
  72086. /**
  72087. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72088. * @param mesh The mesh to exclude from the highlight layer
  72089. */
  72090. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72091. if (!this._excludedMeshes) {
  72092. return;
  72093. }
  72094. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72095. if (!meshExcluded) {
  72096. this._excludedMeshes[mesh.uniqueId] = {
  72097. mesh: mesh,
  72098. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72099. mesh.getEngine().setStencilBuffer(false);
  72100. }),
  72101. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72102. mesh.getEngine().setStencilBuffer(true);
  72103. }),
  72104. };
  72105. }
  72106. };
  72107. /**
  72108. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72109. * @param mesh The mesh to highlight
  72110. */
  72111. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72112. if (!this._excludedMeshes) {
  72113. return;
  72114. }
  72115. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72116. if (meshExcluded) {
  72117. if (meshExcluded.beforeRender) {
  72118. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72119. }
  72120. if (meshExcluded.afterRender) {
  72121. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72122. }
  72123. }
  72124. this._excludedMeshes[mesh.uniqueId] = null;
  72125. };
  72126. /**
  72127. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72128. * @param mesh The mesh to highlight
  72129. * @param color The color of the highlight
  72130. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72131. */
  72132. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72133. var _this = this;
  72134. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72135. if (!this._meshes) {
  72136. return;
  72137. }
  72138. var meshHighlight = this._meshes[mesh.uniqueId];
  72139. if (meshHighlight) {
  72140. meshHighlight.color = color;
  72141. }
  72142. else {
  72143. this._meshes[mesh.uniqueId] = {
  72144. mesh: mesh,
  72145. color: color,
  72146. // Lambda required for capture due to Observable this context
  72147. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72148. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72149. _this.defaultStencilReference(mesh);
  72150. }
  72151. else {
  72152. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72153. }
  72154. }),
  72155. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72156. glowEmissiveOnly: glowEmissiveOnly
  72157. };
  72158. }
  72159. this._shouldRender = true;
  72160. };
  72161. /**
  72162. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72163. * @param mesh The mesh to highlight
  72164. */
  72165. HighlightLayer.prototype.removeMesh = function (mesh) {
  72166. if (!this._meshes) {
  72167. return;
  72168. }
  72169. var meshHighlight = this._meshes[mesh.uniqueId];
  72170. if (meshHighlight) {
  72171. if (meshHighlight.observerHighlight) {
  72172. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72173. }
  72174. if (meshHighlight.observerDefault) {
  72175. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72176. }
  72177. }
  72178. this._meshes[mesh.uniqueId] = null;
  72179. this._shouldRender = false;
  72180. for (var meshHighlightToCheck in this._meshes) {
  72181. if (meshHighlightToCheck) {
  72182. this._shouldRender = true;
  72183. break;
  72184. }
  72185. }
  72186. };
  72187. /**
  72188. * Returns true if the layer contains information to display, otherwise false.
  72189. */
  72190. HighlightLayer.prototype.shouldRender = function () {
  72191. return this.isEnabled && this._shouldRender;
  72192. };
  72193. /**
  72194. * Sets the main texture desired size which is the closest power of two
  72195. * of the engine canvas size.
  72196. */
  72197. HighlightLayer.prototype.setMainTextureSize = function () {
  72198. if (this._options.mainTextureFixedSize) {
  72199. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72200. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72201. }
  72202. else {
  72203. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72204. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72205. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72206. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72207. }
  72208. };
  72209. /**
  72210. * Force the stencil to the normal expected value for none glowing parts
  72211. */
  72212. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72213. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72214. };
  72215. /**
  72216. * Dispose only the render target textures and post process.
  72217. */
  72218. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72219. this._blurTexture.dispose();
  72220. this._mainTexture.dispose();
  72221. this._downSamplePostprocess.dispose();
  72222. this._horizontalBlurPostprocess.dispose();
  72223. this._verticalBlurPostprocess.dispose();
  72224. };
  72225. /**
  72226. * Dispose the highlight layer and free resources.
  72227. */
  72228. HighlightLayer.prototype.dispose = function () {
  72229. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72230. if (vertexBuffer) {
  72231. vertexBuffer.dispose();
  72232. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72233. }
  72234. if (this._indexBuffer) {
  72235. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72236. this._indexBuffer = null;
  72237. }
  72238. // Clean textures and post processes
  72239. this.disposeTextureAndPostProcesses();
  72240. if (this._meshes) {
  72241. // Clean mesh references
  72242. for (var id in this._meshes) {
  72243. var meshHighlight = this._meshes[id];
  72244. if (meshHighlight && meshHighlight.mesh) {
  72245. if (meshHighlight.observerHighlight) {
  72246. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72247. }
  72248. if (meshHighlight.observerDefault) {
  72249. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72250. }
  72251. }
  72252. }
  72253. this._meshes = null;
  72254. }
  72255. if (this._excludedMeshes) {
  72256. for (var id in this._excludedMeshes) {
  72257. var meshHighlight = this._excludedMeshes[id];
  72258. if (meshHighlight) {
  72259. if (meshHighlight.beforeRender) {
  72260. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72261. }
  72262. if (meshHighlight.afterRender) {
  72263. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72264. }
  72265. }
  72266. }
  72267. this._excludedMeshes = null;
  72268. }
  72269. // Remove from scene
  72270. var index = this._scene.highlightLayers.indexOf(this, 0);
  72271. if (index > -1) {
  72272. this._scene.highlightLayers.splice(index, 1);
  72273. }
  72274. // Callback
  72275. this.onDisposeObservable.notifyObservers(this);
  72276. this.onDisposeObservable.clear();
  72277. this.onBeforeRenderMainTextureObservable.clear();
  72278. this.onBeforeBlurObservable.clear();
  72279. this.onBeforeComposeObservable.clear();
  72280. this.onAfterComposeObservable.clear();
  72281. this.onSizeChangedObservable.clear();
  72282. };
  72283. /**
  72284. * The neutral color used during the preparation of the glow effect.
  72285. * This is black by default as the blend operation is a blend operation.
  72286. */
  72287. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72288. /**
  72289. * Stencil value used for glowing meshes.
  72290. */
  72291. HighlightLayer.glowingMeshStencilReference = 0x02;
  72292. /**
  72293. * Stencil value used for the other meshes in the scene.
  72294. */
  72295. HighlightLayer.normalMeshStencilReference = 0x01;
  72296. return HighlightLayer;
  72297. }());
  72298. BABYLON.HighlightLayer = HighlightLayer;
  72299. })(BABYLON || (BABYLON = {}));
  72300. //# sourceMappingURL=babylon.highlightlayer.js.map
  72301. var BABYLON;
  72302. (function (BABYLON) {
  72303. var AssetTaskState;
  72304. (function (AssetTaskState) {
  72305. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72306. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72307. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72308. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72309. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72310. var AbstractAssetTask = /** @class */ (function () {
  72311. function AbstractAssetTask(name) {
  72312. this.name = name;
  72313. this.isCompleted = false;
  72314. this.taskState = AssetTaskState.INIT;
  72315. }
  72316. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72317. var _this = this;
  72318. this.taskState = AssetTaskState.RUNNING;
  72319. this.runTask(scene, function () {
  72320. _this.onDoneCallback(onSuccess, onError);
  72321. }, function (msg, exception) {
  72322. _this.onErrorCallback(onError, msg, exception);
  72323. });
  72324. };
  72325. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72326. throw new Error("runTask is not implemented");
  72327. };
  72328. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72329. this.taskState = AssetTaskState.ERROR;
  72330. this.errorObject = {
  72331. message: message,
  72332. exception: exception
  72333. };
  72334. if (this.onError) {
  72335. this.onError(this, message, exception);
  72336. }
  72337. onError();
  72338. };
  72339. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72340. try {
  72341. this.taskState = AssetTaskState.DONE;
  72342. this.isCompleted = true;
  72343. if (this.onSuccess) {
  72344. this.onSuccess(this);
  72345. }
  72346. onSuccess();
  72347. }
  72348. catch (e) {
  72349. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72350. }
  72351. };
  72352. return AbstractAssetTask;
  72353. }());
  72354. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72355. var AssetsProgressEvent = /** @class */ (function () {
  72356. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72357. this.remainingCount = remainingCount;
  72358. this.totalCount = totalCount;
  72359. this.task = task;
  72360. }
  72361. return AssetsProgressEvent;
  72362. }());
  72363. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72364. var MeshAssetTask = /** @class */ (function (_super) {
  72365. __extends(MeshAssetTask, _super);
  72366. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72367. var _this = _super.call(this, name) || this;
  72368. _this.name = name;
  72369. _this.meshesNames = meshesNames;
  72370. _this.rootUrl = rootUrl;
  72371. _this.sceneFilename = sceneFilename;
  72372. return _this;
  72373. }
  72374. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72375. var _this = this;
  72376. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72377. _this.loadedMeshes = meshes;
  72378. _this.loadedParticleSystems = particleSystems;
  72379. _this.loadedSkeletons = skeletons;
  72380. onSuccess();
  72381. }, null, function (scene, message, exception) {
  72382. onError(message, exception);
  72383. });
  72384. };
  72385. return MeshAssetTask;
  72386. }(AbstractAssetTask));
  72387. BABYLON.MeshAssetTask = MeshAssetTask;
  72388. var TextFileAssetTask = /** @class */ (function (_super) {
  72389. __extends(TextFileAssetTask, _super);
  72390. function TextFileAssetTask(name, url) {
  72391. var _this = _super.call(this, name) || this;
  72392. _this.name = name;
  72393. _this.url = url;
  72394. return _this;
  72395. }
  72396. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72397. var _this = this;
  72398. BABYLON.Tools.LoadFile(this.url, function (data) {
  72399. _this.text = data;
  72400. onSuccess();
  72401. }, undefined, scene.database, false, function (request, exception) {
  72402. if (request) {
  72403. onError(request.status + " " + request.statusText, exception);
  72404. }
  72405. });
  72406. };
  72407. return TextFileAssetTask;
  72408. }(AbstractAssetTask));
  72409. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72410. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72411. __extends(BinaryFileAssetTask, _super);
  72412. function BinaryFileAssetTask(name, url) {
  72413. var _this = _super.call(this, name) || this;
  72414. _this.name = name;
  72415. _this.url = url;
  72416. return _this;
  72417. }
  72418. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72419. var _this = this;
  72420. BABYLON.Tools.LoadFile(this.url, function (data) {
  72421. _this.data = data;
  72422. onSuccess();
  72423. }, undefined, scene.database, true, function (request, exception) {
  72424. if (request) {
  72425. onError(request.status + " " + request.statusText, exception);
  72426. }
  72427. });
  72428. };
  72429. return BinaryFileAssetTask;
  72430. }(AbstractAssetTask));
  72431. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72432. var ImageAssetTask = /** @class */ (function (_super) {
  72433. __extends(ImageAssetTask, _super);
  72434. function ImageAssetTask(name, url) {
  72435. var _this = _super.call(this, name) || this;
  72436. _this.name = name;
  72437. _this.url = url;
  72438. return _this;
  72439. }
  72440. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72441. var _this = this;
  72442. var img = new Image();
  72443. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72444. img.onload = function () {
  72445. _this.image = img;
  72446. onSuccess();
  72447. };
  72448. img.onerror = function (err) {
  72449. onError("Error loading image", err);
  72450. };
  72451. img.src = this.url;
  72452. };
  72453. return ImageAssetTask;
  72454. }(AbstractAssetTask));
  72455. BABYLON.ImageAssetTask = ImageAssetTask;
  72456. var TextureAssetTask = /** @class */ (function (_super) {
  72457. __extends(TextureAssetTask, _super);
  72458. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72460. var _this = _super.call(this, name) || this;
  72461. _this.name = name;
  72462. _this.url = url;
  72463. _this.noMipmap = noMipmap;
  72464. _this.invertY = invertY;
  72465. _this.samplingMode = samplingMode;
  72466. return _this;
  72467. }
  72468. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72469. var onload = function () {
  72470. onSuccess();
  72471. };
  72472. var onerror = function (msg, exception) {
  72473. onError(msg, exception);
  72474. };
  72475. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72476. };
  72477. return TextureAssetTask;
  72478. }(AbstractAssetTask));
  72479. BABYLON.TextureAssetTask = TextureAssetTask;
  72480. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72481. __extends(CubeTextureAssetTask, _super);
  72482. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72483. var _this = _super.call(this, name) || this;
  72484. _this.name = name;
  72485. _this.url = url;
  72486. _this.extensions = extensions;
  72487. _this.noMipmap = noMipmap;
  72488. _this.files = files;
  72489. return _this;
  72490. }
  72491. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72492. var onload = function () {
  72493. onSuccess();
  72494. };
  72495. var onerror = function (msg, exception) {
  72496. onError(msg, exception);
  72497. };
  72498. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  72499. };
  72500. return CubeTextureAssetTask;
  72501. }(AbstractAssetTask));
  72502. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  72503. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  72504. __extends(HDRCubeTextureAssetTask, _super);
  72505. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72506. if (noMipmap === void 0) { noMipmap = false; }
  72507. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72508. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72509. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72510. var _this = _super.call(this, name) || this;
  72511. _this.name = name;
  72512. _this.url = url;
  72513. _this.size = size;
  72514. _this.noMipmap = noMipmap;
  72515. _this.generateHarmonics = generateHarmonics;
  72516. _this.useInGammaSpace = useInGammaSpace;
  72517. _this.usePMREMGenerator = usePMREMGenerator;
  72518. return _this;
  72519. }
  72520. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72521. var onload = function () {
  72522. onSuccess();
  72523. };
  72524. var onerror = function (message, exception) {
  72525. onError(message, exception);
  72526. };
  72527. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  72528. };
  72529. return HDRCubeTextureAssetTask;
  72530. }(AbstractAssetTask));
  72531. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  72532. var AssetsManager = /** @class */ (function () {
  72533. function AssetsManager(scene) {
  72534. this.tasks = new Array();
  72535. this.waitingTasksCount = 0;
  72536. //Observables
  72537. this.onTaskSuccessObservable = new BABYLON.Observable();
  72538. this.onTaskErrorObservable = new BABYLON.Observable();
  72539. this.onTasksDoneObservable = new BABYLON.Observable();
  72540. this.onProgressObservable = new BABYLON.Observable();
  72541. this.useDefaultLoadingScreen = true;
  72542. this._scene = scene;
  72543. }
  72544. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  72545. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  72546. this.tasks.push(task);
  72547. return task;
  72548. };
  72549. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  72550. var task = new TextFileAssetTask(taskName, url);
  72551. this.tasks.push(task);
  72552. return task;
  72553. };
  72554. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  72555. var task = new BinaryFileAssetTask(taskName, url);
  72556. this.tasks.push(task);
  72557. return task;
  72558. };
  72559. AssetsManager.prototype.addImageTask = function (taskName, url) {
  72560. var task = new ImageAssetTask(taskName, url);
  72561. this.tasks.push(task);
  72562. return task;
  72563. };
  72564. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  72565. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72566. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  72567. this.tasks.push(task);
  72568. return task;
  72569. };
  72570. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  72571. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  72572. this.tasks.push(task);
  72573. return task;
  72574. };
  72575. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  72576. if (noMipmap === void 0) { noMipmap = false; }
  72577. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72578. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72579. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72580. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  72581. this.tasks.push(task);
  72582. return task;
  72583. };
  72584. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  72585. this.waitingTasksCount--;
  72586. try {
  72587. if (this.onProgress) {
  72588. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  72589. }
  72590. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  72591. }
  72592. catch (e) {
  72593. BABYLON.Tools.Error("Error running progress callbacks.");
  72594. console.log(e);
  72595. }
  72596. if (this.waitingTasksCount === 0) {
  72597. try {
  72598. if (this.onFinish) {
  72599. this.onFinish(this.tasks);
  72600. }
  72601. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72602. }
  72603. catch (e) {
  72604. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  72605. console.log(e);
  72606. }
  72607. this._scene.getEngine().hideLoadingUI();
  72608. }
  72609. };
  72610. AssetsManager.prototype._runTask = function (task) {
  72611. var _this = this;
  72612. var done = function () {
  72613. try {
  72614. if (_this.onTaskSuccess) {
  72615. _this.onTaskSuccess(task);
  72616. }
  72617. _this.onTaskSuccessObservable.notifyObservers(task);
  72618. _this._decreaseWaitingTasksCount(task);
  72619. }
  72620. catch (e) {
  72621. error("Error executing task success callbacks", e);
  72622. }
  72623. };
  72624. var error = function (message, exception) {
  72625. task.errorObject = task.errorObject || {
  72626. message: message,
  72627. exception: exception
  72628. };
  72629. if (_this.onTaskError) {
  72630. _this.onTaskError(task);
  72631. }
  72632. _this.onTaskErrorObservable.notifyObservers(task);
  72633. _this._decreaseWaitingTasksCount(task);
  72634. };
  72635. task.run(this._scene, done, error);
  72636. };
  72637. AssetsManager.prototype.reset = function () {
  72638. this.tasks = new Array();
  72639. return this;
  72640. };
  72641. AssetsManager.prototype.load = function () {
  72642. this.waitingTasksCount = this.tasks.length;
  72643. if (this.waitingTasksCount === 0) {
  72644. if (this.onFinish) {
  72645. this.onFinish(this.tasks);
  72646. }
  72647. this.onTasksDoneObservable.notifyObservers(this.tasks);
  72648. return this;
  72649. }
  72650. if (this.useDefaultLoadingScreen) {
  72651. this._scene.getEngine().displayLoadingUI();
  72652. }
  72653. for (var index = 0; index < this.tasks.length; index++) {
  72654. var task = this.tasks[index];
  72655. this._runTask(task);
  72656. }
  72657. return this;
  72658. };
  72659. return AssetsManager;
  72660. }());
  72661. BABYLON.AssetsManager = AssetsManager;
  72662. })(BABYLON || (BABYLON = {}));
  72663. //# sourceMappingURL=babylon.assetsManager.js.map
  72664. var BABYLON;
  72665. (function (BABYLON) {
  72666. var serializedGeometries = [];
  72667. var serializeGeometry = function (geometry, serializationGeometries) {
  72668. if (serializedGeometries[geometry.id]) {
  72669. return;
  72670. }
  72671. if (geometry.doNotSerialize) {
  72672. return;
  72673. }
  72674. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  72675. serializationGeometries.boxes.push(geometry.serialize());
  72676. }
  72677. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  72678. serializationGeometries.spheres.push(geometry.serialize());
  72679. }
  72680. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  72681. serializationGeometries.cylinders.push(geometry.serialize());
  72682. }
  72683. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  72684. serializationGeometries.toruses.push(geometry.serialize());
  72685. }
  72686. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  72687. serializationGeometries.grounds.push(geometry.serialize());
  72688. }
  72689. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  72690. serializationGeometries.planes.push(geometry.serialize());
  72691. }
  72692. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  72693. serializationGeometries.torusKnots.push(geometry.serialize());
  72694. }
  72695. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  72696. throw new Error("Unknown primitive type");
  72697. }
  72698. else {
  72699. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  72700. }
  72701. serializedGeometries[geometry.id] = true;
  72702. };
  72703. var serializeMesh = function (mesh, serializationScene) {
  72704. var serializationObject = {};
  72705. // Geometry
  72706. var geometry = mesh._geometry;
  72707. if (geometry) {
  72708. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  72709. // 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
  72710. serializeGeometry(geometry, serializationScene.geometries);
  72711. }
  72712. }
  72713. // Custom
  72714. if (mesh.serialize) {
  72715. mesh.serialize(serializationObject);
  72716. }
  72717. return serializationObject;
  72718. };
  72719. var finalizeSingleMesh = function (mesh, serializationObject) {
  72720. //only works if the mesh is already loaded
  72721. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72722. //serialize material
  72723. if (mesh.material) {
  72724. if (mesh.material instanceof BABYLON.StandardMaterial) {
  72725. serializationObject.materials = serializationObject.materials || [];
  72726. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72727. serializationObject.materials.push(mesh.material.serialize());
  72728. }
  72729. }
  72730. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  72731. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  72732. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  72733. serializationObject.multiMaterials.push(mesh.material.serialize());
  72734. }
  72735. }
  72736. }
  72737. //serialize geometry
  72738. var geometry = mesh._geometry;
  72739. if (geometry) {
  72740. if (!serializationObject.geometries) {
  72741. serializationObject.geometries = {};
  72742. serializationObject.geometries.boxes = [];
  72743. serializationObject.geometries.spheres = [];
  72744. serializationObject.geometries.cylinders = [];
  72745. serializationObject.geometries.toruses = [];
  72746. serializationObject.geometries.grounds = [];
  72747. serializationObject.geometries.planes = [];
  72748. serializationObject.geometries.torusKnots = [];
  72749. serializationObject.geometries.vertexData = [];
  72750. }
  72751. serializeGeometry(geometry, serializationObject.geometries);
  72752. }
  72753. // Skeletons
  72754. if (mesh.skeleton) {
  72755. serializationObject.skeletons = serializationObject.skeletons || [];
  72756. serializationObject.skeletons.push(mesh.skeleton.serialize());
  72757. }
  72758. //serialize the actual mesh
  72759. serializationObject.meshes = serializationObject.meshes || [];
  72760. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72761. }
  72762. };
  72763. var SceneSerializer = /** @class */ (function () {
  72764. function SceneSerializer() {
  72765. }
  72766. SceneSerializer.ClearCache = function () {
  72767. serializedGeometries = [];
  72768. };
  72769. SceneSerializer.Serialize = function (scene) {
  72770. var serializationObject = {};
  72771. SceneSerializer.ClearCache();
  72772. // Scene
  72773. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  72774. serializationObject.autoClear = scene.autoClear;
  72775. serializationObject.clearColor = scene.clearColor.asArray();
  72776. serializationObject.ambientColor = scene.ambientColor.asArray();
  72777. serializationObject.gravity = scene.gravity.asArray();
  72778. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  72779. serializationObject.workerCollisions = scene.workerCollisions;
  72780. // Fog
  72781. if (scene.fogMode && scene.fogMode !== 0) {
  72782. serializationObject.fogMode = scene.fogMode;
  72783. serializationObject.fogColor = scene.fogColor.asArray();
  72784. serializationObject.fogStart = scene.fogStart;
  72785. serializationObject.fogEnd = scene.fogEnd;
  72786. serializationObject.fogDensity = scene.fogDensity;
  72787. }
  72788. //Physics
  72789. if (scene.isPhysicsEnabled()) {
  72790. var physicEngine = scene.getPhysicsEngine();
  72791. if (physicEngine) {
  72792. serializationObject.physicsEnabled = true;
  72793. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  72794. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  72795. }
  72796. }
  72797. // Metadata
  72798. if (scene.metadata) {
  72799. serializationObject.metadata = scene.metadata;
  72800. }
  72801. // Morph targets
  72802. serializationObject.morphTargetManagers = [];
  72803. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  72804. var abstractMesh = _a[_i];
  72805. var manager = abstractMesh.morphTargetManager;
  72806. if (manager) {
  72807. serializationObject.morphTargetManagers.push(manager.serialize());
  72808. }
  72809. }
  72810. // Lights
  72811. serializationObject.lights = [];
  72812. var index;
  72813. var light;
  72814. for (index = 0; index < scene.lights.length; index++) {
  72815. light = scene.lights[index];
  72816. if (!light.doNotSerialize) {
  72817. serializationObject.lights.push(light.serialize());
  72818. }
  72819. }
  72820. // Cameras
  72821. serializationObject.cameras = [];
  72822. for (index = 0; index < scene.cameras.length; index++) {
  72823. var camera = scene.cameras[index];
  72824. if (!camera.doNotSerialize) {
  72825. serializationObject.cameras.push(camera.serialize());
  72826. }
  72827. }
  72828. if (scene.activeCamera) {
  72829. serializationObject.activeCameraID = scene.activeCamera.id;
  72830. }
  72831. // Animations
  72832. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  72833. // Materials
  72834. serializationObject.materials = [];
  72835. serializationObject.multiMaterials = [];
  72836. var material;
  72837. for (index = 0; index < scene.materials.length; index++) {
  72838. material = scene.materials[index];
  72839. if (!material.doNotSerialize) {
  72840. serializationObject.materials.push(material.serialize());
  72841. }
  72842. }
  72843. // MultiMaterials
  72844. serializationObject.multiMaterials = [];
  72845. for (index = 0; index < scene.multiMaterials.length; index++) {
  72846. var multiMaterial = scene.multiMaterials[index];
  72847. serializationObject.multiMaterials.push(multiMaterial.serialize());
  72848. }
  72849. // Skeletons
  72850. serializationObject.skeletons = [];
  72851. for (index = 0; index < scene.skeletons.length; index++) {
  72852. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  72853. }
  72854. // Geometries
  72855. serializationObject.geometries = {};
  72856. serializationObject.geometries.boxes = [];
  72857. serializationObject.geometries.spheres = [];
  72858. serializationObject.geometries.cylinders = [];
  72859. serializationObject.geometries.toruses = [];
  72860. serializationObject.geometries.grounds = [];
  72861. serializationObject.geometries.planes = [];
  72862. serializationObject.geometries.torusKnots = [];
  72863. serializationObject.geometries.vertexData = [];
  72864. serializedGeometries = [];
  72865. var geometries = scene.getGeometries();
  72866. for (index = 0; index < geometries.length; index++) {
  72867. var geometry = geometries[index];
  72868. if (geometry.isReady()) {
  72869. serializeGeometry(geometry, serializationObject.geometries);
  72870. }
  72871. }
  72872. // Meshes
  72873. serializationObject.meshes = [];
  72874. for (index = 0; index < scene.meshes.length; index++) {
  72875. var abstractMesh = scene.meshes[index];
  72876. if (abstractMesh instanceof BABYLON.Mesh) {
  72877. var mesh = abstractMesh;
  72878. if (!mesh.doNotSerialize) {
  72879. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  72880. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  72881. }
  72882. }
  72883. }
  72884. }
  72885. // Particles Systems
  72886. serializationObject.particleSystems = [];
  72887. for (index = 0; index < scene.particleSystems.length; index++) {
  72888. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  72889. }
  72890. // Lens flares
  72891. serializationObject.lensFlareSystems = [];
  72892. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  72893. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  72894. }
  72895. // Shadows
  72896. serializationObject.shadowGenerators = [];
  72897. for (index = 0; index < scene.lights.length; index++) {
  72898. light = scene.lights[index];
  72899. var shadowGenerator = light.getShadowGenerator();
  72900. if (shadowGenerator) {
  72901. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72902. }
  72903. }
  72904. // Action Manager
  72905. if (scene.actionManager) {
  72906. serializationObject.actions = scene.actionManager.serialize("scene");
  72907. }
  72908. // Audio
  72909. serializationObject.sounds = [];
  72910. for (index = 0; index < scene.soundTracks.length; index++) {
  72911. var soundtrack = scene.soundTracks[index];
  72912. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72913. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72914. }
  72915. }
  72916. return serializationObject;
  72917. };
  72918. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  72919. if (withParents === void 0) { withParents = false; }
  72920. if (withChildren === void 0) { withChildren = false; }
  72921. var serializationObject = {};
  72922. SceneSerializer.ClearCache();
  72923. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  72924. if (withParents || withChildren) {
  72925. //deliberate for loop! not for each, appended should be processed as well.
  72926. for (var i = 0; i < toSerialize.length; ++i) {
  72927. if (withChildren) {
  72928. toSerialize[i].getDescendants().forEach(function (node) {
  72929. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  72930. toSerialize.push(node);
  72931. }
  72932. });
  72933. }
  72934. //make sure the array doesn't contain the object already
  72935. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  72936. toSerialize.push(toSerialize[i].parent);
  72937. }
  72938. }
  72939. }
  72940. toSerialize.forEach(function (mesh) {
  72941. finalizeSingleMesh(mesh, serializationObject);
  72942. });
  72943. return serializationObject;
  72944. };
  72945. return SceneSerializer;
  72946. }());
  72947. BABYLON.SceneSerializer = SceneSerializer;
  72948. })(BABYLON || (BABYLON = {}));
  72949. //# sourceMappingURL=babylon.sceneSerializer.js.map
  72950. var BABYLON;
  72951. (function (BABYLON) {
  72952. var ReflectionProbe = /** @class */ (function () {
  72953. function ReflectionProbe(name, size, scene, generateMipMaps) {
  72954. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72955. var _this = this;
  72956. this.name = name;
  72957. this._viewMatrix = BABYLON.Matrix.Identity();
  72958. this._target = BABYLON.Vector3.Zero();
  72959. this._add = BABYLON.Vector3.Zero();
  72960. this.invertYAxis = false;
  72961. this.position = BABYLON.Vector3.Zero();
  72962. this._scene = scene;
  72963. this._scene.reflectionProbes.push(this);
  72964. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  72965. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  72966. switch (faceIndex) {
  72967. case 0:
  72968. _this._add.copyFromFloats(1, 0, 0);
  72969. break;
  72970. case 1:
  72971. _this._add.copyFromFloats(-1, 0, 0);
  72972. break;
  72973. case 2:
  72974. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  72975. break;
  72976. case 3:
  72977. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  72978. break;
  72979. case 4:
  72980. _this._add.copyFromFloats(0, 0, 1);
  72981. break;
  72982. case 5:
  72983. _this._add.copyFromFloats(0, 0, -1);
  72984. break;
  72985. }
  72986. if (_this._attachedMesh) {
  72987. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  72988. }
  72989. _this.position.addToRef(_this._add, _this._target);
  72990. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  72991. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  72992. });
  72993. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  72994. scene.updateTransformMatrix(true);
  72995. });
  72996. if (scene.activeCamera) {
  72997. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  72998. }
  72999. }
  73000. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73001. get: function () {
  73002. return this._renderTargetTexture.samples;
  73003. },
  73004. set: function (value) {
  73005. this._renderTargetTexture.samples = value;
  73006. },
  73007. enumerable: true,
  73008. configurable: true
  73009. });
  73010. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73011. get: function () {
  73012. return this._renderTargetTexture.refreshRate;
  73013. },
  73014. set: function (value) {
  73015. this._renderTargetTexture.refreshRate = value;
  73016. },
  73017. enumerable: true,
  73018. configurable: true
  73019. });
  73020. ReflectionProbe.prototype.getScene = function () {
  73021. return this._scene;
  73022. };
  73023. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73024. get: function () {
  73025. return this._renderTargetTexture;
  73026. },
  73027. enumerable: true,
  73028. configurable: true
  73029. });
  73030. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73031. get: function () {
  73032. return this._renderTargetTexture.renderList;
  73033. },
  73034. enumerable: true,
  73035. configurable: true
  73036. });
  73037. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73038. this._attachedMesh = mesh;
  73039. };
  73040. /**
  73041. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73042. *
  73043. * @param renderingGroupId The rendering group id corresponding to its index
  73044. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73045. */
  73046. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73047. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73048. };
  73049. ReflectionProbe.prototype.dispose = function () {
  73050. var index = this._scene.reflectionProbes.indexOf(this);
  73051. if (index !== -1) {
  73052. // Remove from the scene if found
  73053. this._scene.reflectionProbes.splice(index, 1);
  73054. }
  73055. if (this._renderTargetTexture) {
  73056. this._renderTargetTexture.dispose();
  73057. this._renderTargetTexture = null;
  73058. }
  73059. };
  73060. return ReflectionProbe;
  73061. }());
  73062. BABYLON.ReflectionProbe = ReflectionProbe;
  73063. })(BABYLON || (BABYLON = {}));
  73064. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73065. var BABYLON;
  73066. (function (BABYLON) {
  73067. var Layer = /** @class */ (function () {
  73068. function Layer(name, imgUrl, scene, isBackground, color) {
  73069. this.name = name;
  73070. this.scale = new BABYLON.Vector2(1, 1);
  73071. this.offset = new BABYLON.Vector2(0, 0);
  73072. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73073. this.layerMask = 0x0FFFFFFF;
  73074. this._vertexBuffers = {};
  73075. // Events
  73076. /**
  73077. * An event triggered when the layer is disposed.
  73078. * @type {BABYLON.Observable}
  73079. */
  73080. this.onDisposeObservable = new BABYLON.Observable();
  73081. /**
  73082. * An event triggered before rendering the scene
  73083. * @type {BABYLON.Observable}
  73084. */
  73085. this.onBeforeRenderObservable = new BABYLON.Observable();
  73086. /**
  73087. * An event triggered after rendering the scene
  73088. * @type {BABYLON.Observable}
  73089. */
  73090. this.onAfterRenderObservable = new BABYLON.Observable();
  73091. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73092. this.isBackground = isBackground === undefined ? true : isBackground;
  73093. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73094. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73095. this._scene.layers.push(this);
  73096. var engine = this._scene.getEngine();
  73097. // VBO
  73098. var vertices = [];
  73099. vertices.push(1, 1);
  73100. vertices.push(-1, 1);
  73101. vertices.push(-1, -1);
  73102. vertices.push(1, -1);
  73103. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73104. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73105. this._createIndexBuffer();
  73106. // Effects
  73107. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73108. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73109. }
  73110. Object.defineProperty(Layer.prototype, "onDispose", {
  73111. set: function (callback) {
  73112. if (this._onDisposeObserver) {
  73113. this.onDisposeObservable.remove(this._onDisposeObserver);
  73114. }
  73115. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73116. },
  73117. enumerable: true,
  73118. configurable: true
  73119. });
  73120. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73121. set: function (callback) {
  73122. if (this._onBeforeRenderObserver) {
  73123. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73124. }
  73125. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73126. },
  73127. enumerable: true,
  73128. configurable: true
  73129. });
  73130. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73131. set: function (callback) {
  73132. if (this._onAfterRenderObserver) {
  73133. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73134. }
  73135. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73136. },
  73137. enumerable: true,
  73138. configurable: true
  73139. });
  73140. Layer.prototype._createIndexBuffer = function () {
  73141. var engine = this._scene.getEngine();
  73142. // Indices
  73143. var indices = [];
  73144. indices.push(0);
  73145. indices.push(1);
  73146. indices.push(2);
  73147. indices.push(0);
  73148. indices.push(2);
  73149. indices.push(3);
  73150. this._indexBuffer = engine.createIndexBuffer(indices);
  73151. };
  73152. Layer.prototype._rebuild = function () {
  73153. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73154. if (vb) {
  73155. vb._rebuild();
  73156. }
  73157. this._createIndexBuffer();
  73158. };
  73159. Layer.prototype.render = function () {
  73160. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73161. // Check
  73162. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73163. return;
  73164. var engine = this._scene.getEngine();
  73165. this.onBeforeRenderObservable.notifyObservers(this);
  73166. // Render
  73167. engine.enableEffect(currentEffect);
  73168. engine.setState(false);
  73169. // Texture
  73170. currentEffect.setTexture("textureSampler", this.texture);
  73171. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73172. // Color
  73173. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73174. // Scale / offset
  73175. currentEffect.setVector2("offset", this.offset);
  73176. currentEffect.setVector2("scale", this.scale);
  73177. // VBOs
  73178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73179. // Draw order
  73180. if (!this.alphaTest) {
  73181. engine.setAlphaMode(this.alphaBlendingMode);
  73182. engine.draw(true, 0, 6);
  73183. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73184. }
  73185. else {
  73186. engine.draw(true, 0, 6);
  73187. }
  73188. this.onAfterRenderObservable.notifyObservers(this);
  73189. };
  73190. Layer.prototype.dispose = function () {
  73191. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73192. if (vertexBuffer) {
  73193. vertexBuffer.dispose();
  73194. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73195. }
  73196. if (this._indexBuffer) {
  73197. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73198. this._indexBuffer = null;
  73199. }
  73200. if (this.texture) {
  73201. this.texture.dispose();
  73202. this.texture = null;
  73203. }
  73204. // Remove from scene
  73205. var index = this._scene.layers.indexOf(this);
  73206. this._scene.layers.splice(index, 1);
  73207. // Callback
  73208. this.onDisposeObservable.notifyObservers(this);
  73209. this.onDisposeObservable.clear();
  73210. this.onAfterRenderObservable.clear();
  73211. this.onBeforeRenderObservable.clear();
  73212. };
  73213. return Layer;
  73214. }());
  73215. BABYLON.Layer = Layer;
  73216. })(BABYLON || (BABYLON = {}));
  73217. //# sourceMappingURL=babylon.layer.js.map
  73218. var BABYLON;
  73219. (function (BABYLON) {
  73220. var TextureTools = /** @class */ (function () {
  73221. function TextureTools() {
  73222. }
  73223. /**
  73224. * Uses the GPU to create a copy texture rescaled at a given size
  73225. * @param texture Texture to copy from
  73226. * @param width Desired width
  73227. * @param height Desired height
  73228. * @return Generated texture
  73229. */
  73230. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73231. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73232. var scene = texture.getScene();
  73233. var engine = scene.getEngine();
  73234. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73235. rtt.wrapU = texture.wrapU;
  73236. rtt.wrapV = texture.wrapV;
  73237. rtt.uOffset = texture.uOffset;
  73238. rtt.vOffset = texture.vOffset;
  73239. rtt.uScale = texture.uScale;
  73240. rtt.vScale = texture.vScale;
  73241. rtt.uAng = texture.uAng;
  73242. rtt.vAng = texture.vAng;
  73243. rtt.wAng = texture.wAng;
  73244. rtt.coordinatesIndex = texture.coordinatesIndex;
  73245. rtt.level = texture.level;
  73246. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73247. rtt._texture.isReady = false;
  73248. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73249. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73250. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73251. passPostProcess.getEffect().executeWhenCompiled(function () {
  73252. passPostProcess.onApply = function (effect) {
  73253. effect.setTexture("textureSampler", texture);
  73254. };
  73255. var internalTexture = rtt.getInternalTexture();
  73256. if (internalTexture) {
  73257. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73258. engine.unBindFramebuffer(internalTexture);
  73259. rtt.disposeFramebufferObjects();
  73260. passPostProcess.dispose();
  73261. internalTexture.isReady = true;
  73262. }
  73263. });
  73264. return rtt;
  73265. };
  73266. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73267. if (!scene._environmentBRDFTexture) {
  73268. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73269. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73270. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73271. scene._environmentBRDFTexture = texture;
  73272. }
  73273. return scene._environmentBRDFTexture;
  73274. };
  73275. 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=";
  73276. return TextureTools;
  73277. }());
  73278. BABYLON.TextureTools = TextureTools;
  73279. })(BABYLON || (BABYLON = {}));
  73280. //# sourceMappingURL=babylon.textureTools.js.map
  73281. var BABYLON;
  73282. (function (BABYLON) {
  73283. var FramingBehavior = /** @class */ (function () {
  73284. function FramingBehavior() {
  73285. this._mode = FramingBehavior.FitFrustumSidesMode;
  73286. this._radiusScale = 1.0;
  73287. this._positionScale = 0.5;
  73288. this._defaultElevation = 0.3;
  73289. this._elevationReturnTime = 1500;
  73290. this._elevationReturnWaitTime = 1000;
  73291. this._zoomStopsAnimation = false;
  73292. this._framingTime = 1500;
  73293. this._isPointerDown = false;
  73294. this._lastInteractionTime = -Infinity;
  73295. // Framing control
  73296. this._animatables = new Array();
  73297. this._betaIsAnimating = false;
  73298. }
  73299. Object.defineProperty(FramingBehavior.prototype, "name", {
  73300. get: function () {
  73301. return "Framing";
  73302. },
  73303. enumerable: true,
  73304. configurable: true
  73305. });
  73306. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73307. /**
  73308. * Gets current mode used by the behavior.
  73309. */
  73310. get: function () {
  73311. return this._mode;
  73312. },
  73313. /**
  73314. * Sets the current mode used by the behavior
  73315. */
  73316. set: function (mode) {
  73317. this._mode = mode;
  73318. },
  73319. enumerable: true,
  73320. configurable: true
  73321. });
  73322. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73323. /**
  73324. * Gets the scale applied to the radius
  73325. */
  73326. get: function () {
  73327. return this._radiusScale;
  73328. },
  73329. /**
  73330. * Sets the scale applied to the radius (1 by default)
  73331. */
  73332. set: function (radius) {
  73333. this._radiusScale = radius;
  73334. },
  73335. enumerable: true,
  73336. configurable: true
  73337. });
  73338. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73339. /**
  73340. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73341. */
  73342. get: function () {
  73343. return this._positionScale;
  73344. },
  73345. /**
  73346. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73347. */
  73348. set: function (scale) {
  73349. this._positionScale = scale;
  73350. },
  73351. enumerable: true,
  73352. configurable: true
  73353. });
  73354. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73355. /**
  73356. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73357. * behaviour is triggered, in radians.
  73358. */
  73359. get: function () {
  73360. return this._defaultElevation;
  73361. },
  73362. /**
  73363. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73364. * behaviour is triggered, in radians.
  73365. */
  73366. set: function (elevation) {
  73367. this._defaultElevation = elevation;
  73368. },
  73369. enumerable: true,
  73370. configurable: true
  73371. });
  73372. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73373. /**
  73374. * Gets the time (in milliseconds) taken to return to the default beta position.
  73375. * Negative value indicates camera should not return to default.
  73376. */
  73377. get: function () {
  73378. return this._elevationReturnTime;
  73379. },
  73380. /**
  73381. * Sets the time (in milliseconds) taken to return to the default beta position.
  73382. * Negative value indicates camera should not return to default.
  73383. */
  73384. set: function (speed) {
  73385. this._elevationReturnTime = speed;
  73386. },
  73387. enumerable: true,
  73388. configurable: true
  73389. });
  73390. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73391. /**
  73392. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73393. */
  73394. get: function () {
  73395. return this._elevationReturnWaitTime;
  73396. },
  73397. /**
  73398. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73399. */
  73400. set: function (time) {
  73401. this._elevationReturnWaitTime = time;
  73402. },
  73403. enumerable: true,
  73404. configurable: true
  73405. });
  73406. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73407. /**
  73408. * Gets the flag that indicates if user zooming should stop animation.
  73409. */
  73410. get: function () {
  73411. return this._zoomStopsAnimation;
  73412. },
  73413. /**
  73414. * Sets the flag that indicates if user zooming should stop animation.
  73415. */
  73416. set: function (flag) {
  73417. this._zoomStopsAnimation = flag;
  73418. },
  73419. enumerable: true,
  73420. configurable: true
  73421. });
  73422. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73423. /**
  73424. * Gets the transition time when framing the mesh, in milliseconds
  73425. */
  73426. get: function () {
  73427. return this._framingTime;
  73428. },
  73429. /**
  73430. * Sets the transition time when framing the mesh, in milliseconds
  73431. */
  73432. set: function (time) {
  73433. this._framingTime = time;
  73434. },
  73435. enumerable: true,
  73436. configurable: true
  73437. });
  73438. FramingBehavior.prototype.attach = function (camera) {
  73439. var _this = this;
  73440. this._attachedCamera = camera;
  73441. var scene = this._attachedCamera.getScene();
  73442. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73443. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73444. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73445. _this._isPointerDown = true;
  73446. return;
  73447. }
  73448. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73449. _this._isPointerDown = false;
  73450. }
  73451. });
  73452. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73453. if (mesh) {
  73454. _this.zoomOnMesh(mesh);
  73455. }
  73456. });
  73457. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73458. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73459. _this._applyUserInteraction();
  73460. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73461. // back to the default position after a given timeout
  73462. _this._maintainCameraAboveGround();
  73463. });
  73464. };
  73465. FramingBehavior.prototype.detach = function () {
  73466. if (!this._attachedCamera) {
  73467. return;
  73468. }
  73469. var scene = this._attachedCamera.getScene();
  73470. if (this._onPrePointerObservableObserver) {
  73471. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73472. }
  73473. if (this._onAfterCheckInputsObserver) {
  73474. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73475. }
  73476. if (this._onMeshTargetChangedObserver) {
  73477. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73478. }
  73479. this._attachedCamera = null;
  73480. };
  73481. /**
  73482. * Targets the given mesh and updates zoom level accordingly.
  73483. * @param mesh The mesh to target.
  73484. * @param radius Optional. If a cached radius position already exists, overrides default.
  73485. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73486. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73487. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73488. */
  73489. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  73490. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73491. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73492. mesh.computeWorldMatrix(true);
  73493. var boundingBox = mesh.getBoundingInfo().boundingBox;
  73494. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  73495. };
  73496. /**
  73497. * Targets the given mesh and updates zoom level accordingly.
  73498. * @param mesh The mesh to target.
  73499. * @param radius Optional. If a cached radius position already exists, overrides default.
  73500. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73501. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  73502. * @param onAnimationEnd Callback triggered at the end of the framing animation
  73503. */
  73504. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  73505. var _this = this;
  73506. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  73507. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  73508. var zoomTarget;
  73509. if (!this._attachedCamera) {
  73510. return;
  73511. }
  73512. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  73513. var bottom = minimumWorld.y;
  73514. var top = maximumWorld.y;
  73515. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  73516. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  73517. if (focusOnOriginXZ) {
  73518. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  73519. }
  73520. else {
  73521. var centerWorld = minimumWorld.add(radiusWorld);
  73522. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  73523. }
  73524. if (!this._vectorTransition) {
  73525. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  73526. }
  73527. this._betaIsAnimating = true;
  73528. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  73529. if (animatable) {
  73530. this._animatables.push(animatable);
  73531. }
  73532. // sets the radius and lower radius bounds
  73533. // Small delta ensures camera is not always at lower zoom limit.
  73534. var radius = 0;
  73535. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  73536. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73537. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  73538. radius = position;
  73539. }
  73540. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73541. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  73542. if (this._attachedCamera.lowerRadiusLimit === null) {
  73543. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  73544. }
  73545. }
  73546. // Set sensibilities
  73547. var extend = maximumWorld.subtract(minimumWorld).length();
  73548. this._attachedCamera.panningSensibility = 5000 / extend;
  73549. this._attachedCamera.wheelPrecision = 100 / radius;
  73550. // transition to new radius
  73551. if (!this._radiusTransition) {
  73552. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73553. }
  73554. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  73555. if (onAnimationEnd) {
  73556. onAnimationEnd();
  73557. }
  73558. if (_this._attachedCamera) {
  73559. _this._attachedCamera.storeState();
  73560. }
  73561. });
  73562. if (animatable) {
  73563. this._animatables.push(animatable);
  73564. }
  73565. };
  73566. /**
  73567. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  73568. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  73569. * frustum width.
  73570. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  73571. * to fully enclose the mesh in the viewing frustum.
  73572. */
  73573. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  73574. var size = maximumWorld.subtract(minimumWorld);
  73575. var boxVectorGlobalDiagonal = size.length();
  73576. var frustumSlope = this._getFrustumSlope();
  73577. // Formula for setting distance
  73578. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  73579. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  73580. // Horizon distance
  73581. var radius = radiusWithoutFraming * this._radiusScale;
  73582. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  73583. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  73584. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  73585. var camera = this._attachedCamera;
  73586. if (!camera) {
  73587. return 0;
  73588. }
  73589. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  73590. // Don't exceed the requested limit
  73591. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  73592. }
  73593. // Don't exceed the upper radius limit
  73594. if (camera.upperRadiusLimit) {
  73595. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  73596. }
  73597. return distance;
  73598. };
  73599. /**
  73600. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  73601. * is automatically returned to its default position (expected to be above ground plane).
  73602. */
  73603. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  73604. var _this = this;
  73605. if (this._elevationReturnTime < 0) {
  73606. return;
  73607. }
  73608. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  73609. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  73610. var limitBeta = Math.PI * 0.5;
  73611. // Bring the camera back up if below the ground plane
  73612. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  73613. this._betaIsAnimating = true;
  73614. //Transition to new position
  73615. this.stopAllAnimations();
  73616. if (!this._betaTransition) {
  73617. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  73618. }
  73619. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  73620. _this._clearAnimationLocks();
  73621. _this.stopAllAnimations();
  73622. });
  73623. if (animatabe) {
  73624. this._animatables.push(animatabe);
  73625. }
  73626. }
  73627. };
  73628. /**
  73629. * Returns the frustum slope based on the canvas ratio and camera FOV
  73630. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  73631. */
  73632. FramingBehavior.prototype._getFrustumSlope = function () {
  73633. // Calculate the viewport ratio
  73634. // Aspect Ratio is Height/Width.
  73635. var camera = this._attachedCamera;
  73636. if (!camera) {
  73637. return BABYLON.Vector2.Zero();
  73638. }
  73639. var engine = camera.getScene().getEngine();
  73640. var aspectRatio = engine.getAspectRatio(camera);
  73641. // Camera FOV is the vertical field of view (top-bottom) in radians.
  73642. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  73643. var frustumSlopeY = Math.tan(camera.fov / 2);
  73644. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  73645. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  73646. // along the forward vector.
  73647. var frustumSlopeX = frustumSlopeY * aspectRatio;
  73648. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  73649. };
  73650. /**
  73651. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  73652. */
  73653. FramingBehavior.prototype._clearAnimationLocks = function () {
  73654. this._betaIsAnimating = false;
  73655. };
  73656. /**
  73657. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  73658. */
  73659. FramingBehavior.prototype._applyUserInteraction = function () {
  73660. if (this.isUserIsMoving) {
  73661. this._lastInteractionTime = BABYLON.Tools.Now;
  73662. this.stopAllAnimations();
  73663. this._clearAnimationLocks();
  73664. }
  73665. };
  73666. /**
  73667. * Stops and removes all animations that have been applied to the camera
  73668. */
  73669. FramingBehavior.prototype.stopAllAnimations = function () {
  73670. if (this._attachedCamera) {
  73671. this._attachedCamera.animations = [];
  73672. }
  73673. while (this._animatables.length) {
  73674. if (this._animatables[0]) {
  73675. this._animatables[0].onAnimationEnd = null;
  73676. this._animatables[0].stop();
  73677. }
  73678. this._animatables.shift();
  73679. }
  73680. };
  73681. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  73682. /**
  73683. * Gets a value indicating if the user is moving the camera
  73684. */
  73685. get: function () {
  73686. if (!this._attachedCamera) {
  73687. return false;
  73688. }
  73689. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  73690. this._attachedCamera.inertialBetaOffset !== 0 ||
  73691. this._attachedCamera.inertialRadiusOffset !== 0 ||
  73692. this._attachedCamera.inertialPanningX !== 0 ||
  73693. this._attachedCamera.inertialPanningY !== 0 ||
  73694. this._isPointerDown;
  73695. },
  73696. enumerable: true,
  73697. configurable: true
  73698. });
  73699. /**
  73700. * The easing function used by animations
  73701. */
  73702. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  73703. /**
  73704. * The easing mode used by animations
  73705. */
  73706. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  73707. // Statics
  73708. /**
  73709. * The camera can move all the way towards the mesh.
  73710. */
  73711. FramingBehavior.IgnoreBoundsSizeMode = 0;
  73712. /**
  73713. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  73714. */
  73715. FramingBehavior.FitFrustumSidesMode = 1;
  73716. return FramingBehavior;
  73717. }());
  73718. BABYLON.FramingBehavior = FramingBehavior;
  73719. })(BABYLON || (BABYLON = {}));
  73720. //# sourceMappingURL=babylon.framingBehavior.js.map
  73721. var BABYLON;
  73722. (function (BABYLON) {
  73723. /**
  73724. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  73725. */
  73726. var BouncingBehavior = /** @class */ (function () {
  73727. function BouncingBehavior() {
  73728. /**
  73729. * The duration of the animation, in milliseconds
  73730. */
  73731. this.transitionDuration = 450;
  73732. /**
  73733. * Length of the distance animated by the transition when lower radius is reached
  73734. */
  73735. this.lowerRadiusTransitionRange = 2;
  73736. /**
  73737. * Length of the distance animated by the transition when upper radius is reached
  73738. */
  73739. this.upperRadiusTransitionRange = -2;
  73740. this._autoTransitionRange = false;
  73741. // Animations
  73742. this._radiusIsAnimating = false;
  73743. this._radiusBounceTransition = null;
  73744. this._animatables = new Array();
  73745. }
  73746. Object.defineProperty(BouncingBehavior.prototype, "name", {
  73747. get: function () {
  73748. return "Bouncing";
  73749. },
  73750. enumerable: true,
  73751. configurable: true
  73752. });
  73753. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  73754. /**
  73755. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73756. */
  73757. get: function () {
  73758. return this._autoTransitionRange;
  73759. },
  73760. /**
  73761. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  73762. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  73763. */
  73764. set: function (value) {
  73765. var _this = this;
  73766. if (this._autoTransitionRange === value) {
  73767. return;
  73768. }
  73769. this._autoTransitionRange = value;
  73770. var camera = this._attachedCamera;
  73771. if (!camera) {
  73772. return;
  73773. }
  73774. if (value) {
  73775. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73776. if (!mesh) {
  73777. return;
  73778. }
  73779. mesh.computeWorldMatrix(true);
  73780. var diagonal = mesh.getBoundingInfo().diagonalLength;
  73781. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  73782. _this.upperRadiusTransitionRange = diagonal * 0.05;
  73783. });
  73784. }
  73785. else if (this._onMeshTargetChangedObserver) {
  73786. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73787. }
  73788. },
  73789. enumerable: true,
  73790. configurable: true
  73791. });
  73792. BouncingBehavior.prototype.attach = function (camera) {
  73793. var _this = this;
  73794. this._attachedCamera = camera;
  73795. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73796. if (!_this._attachedCamera) {
  73797. return;
  73798. }
  73799. // Add the bounce animation to the lower radius limit
  73800. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  73801. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  73802. }
  73803. // Add the bounce animation to the upper radius limit
  73804. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  73805. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  73806. }
  73807. });
  73808. };
  73809. BouncingBehavior.prototype.detach = function () {
  73810. if (!this._attachedCamera) {
  73811. return;
  73812. }
  73813. if (this._onAfterCheckInputsObserver) {
  73814. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73815. }
  73816. if (this._onMeshTargetChangedObserver) {
  73817. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73818. }
  73819. this._attachedCamera = null;
  73820. };
  73821. /**
  73822. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  73823. * @param radiusLimit The limit to check against.
  73824. * @return Bool to indicate if at limit.
  73825. */
  73826. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  73827. if (!this._attachedCamera) {
  73828. return false;
  73829. }
  73830. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  73831. return true;
  73832. }
  73833. return false;
  73834. };
  73835. /**
  73836. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  73837. * @param radiusDelta The delta by which to animate to. Can be negative.
  73838. */
  73839. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  73840. var _this = this;
  73841. if (!this._attachedCamera) {
  73842. return;
  73843. }
  73844. if (!this._radiusBounceTransition) {
  73845. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  73846. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  73847. }
  73848. // Prevent zoom until bounce has completed
  73849. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  73850. this._attachedCamera.wheelPrecision = Infinity;
  73851. this._attachedCamera.inertialRadiusOffset = 0;
  73852. // Animate to the radius limit
  73853. this.stopAllAnimations();
  73854. this._radiusIsAnimating = true;
  73855. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  73856. if (animatable) {
  73857. this._animatables.push(animatable);
  73858. }
  73859. };
  73860. /**
  73861. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  73862. */
  73863. BouncingBehavior.prototype._clearAnimationLocks = function () {
  73864. this._radiusIsAnimating = false;
  73865. if (this._attachedCamera) {
  73866. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  73867. }
  73868. };
  73869. /**
  73870. * Stops and removes all animations that have been applied to the camera
  73871. */
  73872. BouncingBehavior.prototype.stopAllAnimations = function () {
  73873. if (this._attachedCamera) {
  73874. this._attachedCamera.animations = [];
  73875. }
  73876. while (this._animatables.length) {
  73877. this._animatables[0].onAnimationEnd = null;
  73878. this._animatables[0].stop();
  73879. this._animatables.shift();
  73880. }
  73881. };
  73882. /**
  73883. * The easing function used by animations
  73884. */
  73885. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  73886. /**
  73887. * The easing mode used by animations
  73888. */
  73889. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  73890. return BouncingBehavior;
  73891. }());
  73892. BABYLON.BouncingBehavior = BouncingBehavior;
  73893. })(BABYLON || (BABYLON = {}));
  73894. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  73895. var BABYLON;
  73896. (function (BABYLON) {
  73897. var AutoRotationBehavior = /** @class */ (function () {
  73898. function AutoRotationBehavior() {
  73899. this._zoomStopsAnimation = false;
  73900. this._idleRotationSpeed = 0.05;
  73901. this._idleRotationWaitTime = 2000;
  73902. this._idleRotationSpinupTime = 2000;
  73903. this._isPointerDown = false;
  73904. this._lastFrameTime = null;
  73905. this._lastInteractionTime = -Infinity;
  73906. this._cameraRotationSpeed = 0;
  73907. this._lastFrameRadius = 0;
  73908. }
  73909. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  73910. get: function () {
  73911. return "AutoRotation";
  73912. },
  73913. enumerable: true,
  73914. configurable: true
  73915. });
  73916. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  73917. /**
  73918. * Gets the flag that indicates if user zooming should stop animation.
  73919. */
  73920. get: function () {
  73921. return this._zoomStopsAnimation;
  73922. },
  73923. /**
  73924. * Sets the flag that indicates if user zooming should stop animation.
  73925. */
  73926. set: function (flag) {
  73927. this._zoomStopsAnimation = flag;
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  73933. /**
  73934. * Gets the default speed at which the camera rotates around the model.
  73935. */
  73936. get: function () {
  73937. return this._idleRotationSpeed;
  73938. },
  73939. /**
  73940. * Sets the default speed at which the camera rotates around the model.
  73941. */
  73942. set: function (speed) {
  73943. this._idleRotationSpeed = speed;
  73944. },
  73945. enumerable: true,
  73946. configurable: true
  73947. });
  73948. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  73949. /**
  73950. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  73951. */
  73952. get: function () {
  73953. return this._idleRotationWaitTime;
  73954. },
  73955. /**
  73956. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  73957. */
  73958. set: function (time) {
  73959. this._idleRotationWaitTime = time;
  73960. },
  73961. enumerable: true,
  73962. configurable: true
  73963. });
  73964. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  73965. /**
  73966. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73967. */
  73968. get: function () {
  73969. return this._idleRotationSpinupTime;
  73970. },
  73971. /**
  73972. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  73973. */
  73974. set: function (time) {
  73975. this._idleRotationSpinupTime = time;
  73976. },
  73977. enumerable: true,
  73978. configurable: true
  73979. });
  73980. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  73981. /**
  73982. * Gets a value indicating if the camera is currently rotating because of this behavior
  73983. */
  73984. get: function () {
  73985. return Math.abs(this._cameraRotationSpeed) > 0;
  73986. },
  73987. enumerable: true,
  73988. configurable: true
  73989. });
  73990. AutoRotationBehavior.prototype.attach = function (camera) {
  73991. var _this = this;
  73992. this._attachedCamera = camera;
  73993. var scene = this._attachedCamera.getScene();
  73994. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73995. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73996. _this._isPointerDown = true;
  73997. return;
  73998. }
  73999. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74000. _this._isPointerDown = false;
  74001. }
  74002. });
  74003. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74004. var now = BABYLON.Tools.Now;
  74005. var dt = 0;
  74006. if (_this._lastFrameTime != null) {
  74007. dt = now - _this._lastFrameTime;
  74008. }
  74009. _this._lastFrameTime = now;
  74010. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74011. _this._applyUserInteraction();
  74012. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74013. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74014. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74015. // Step camera rotation by rotation speed
  74016. if (_this._attachedCamera) {
  74017. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74018. }
  74019. });
  74020. };
  74021. AutoRotationBehavior.prototype.detach = function () {
  74022. if (!this._attachedCamera) {
  74023. return;
  74024. }
  74025. var scene = this._attachedCamera.getScene();
  74026. if (this._onPrePointerObservableObserver) {
  74027. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74028. }
  74029. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74030. this._attachedCamera = null;
  74031. };
  74032. /**
  74033. * Returns true if user is scrolling.
  74034. * @return true if user is scrolling.
  74035. */
  74036. AutoRotationBehavior.prototype._userIsZooming = function () {
  74037. if (!this._attachedCamera) {
  74038. return false;
  74039. }
  74040. return this._attachedCamera.inertialRadiusOffset !== 0;
  74041. };
  74042. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74043. if (!this._attachedCamera) {
  74044. return false;
  74045. }
  74046. var zoomHasHitLimit = false;
  74047. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74048. zoomHasHitLimit = true;
  74049. }
  74050. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74051. this._lastFrameRadius = this._attachedCamera.radius;
  74052. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74053. };
  74054. /**
  74055. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74056. */
  74057. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74058. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74059. this._lastInteractionTime = BABYLON.Tools.Now;
  74060. }
  74061. };
  74062. // Tools
  74063. AutoRotationBehavior.prototype._userIsMoving = function () {
  74064. if (!this._attachedCamera) {
  74065. return false;
  74066. }
  74067. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74068. this._attachedCamera.inertialBetaOffset !== 0 ||
  74069. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74070. this._attachedCamera.inertialPanningX !== 0 ||
  74071. this._attachedCamera.inertialPanningY !== 0 ||
  74072. this._isPointerDown;
  74073. };
  74074. return AutoRotationBehavior;
  74075. }());
  74076. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74077. })(BABYLON || (BABYLON = {}));
  74078. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74079. var BABYLON;
  74080. (function (BABYLON) {
  74081. /**
  74082. * This class can be used to get instrumentation data from a Babylon engine
  74083. */
  74084. var EngineInstrumentation = /** @class */ (function () {
  74085. function EngineInstrumentation(engine) {
  74086. this.engine = engine;
  74087. this._captureGPUFrameTime = false;
  74088. this._gpuFrameTime = new BABYLON.PerfCounter();
  74089. this._captureShaderCompilationTime = false;
  74090. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74091. // Observers
  74092. this._onBeginFrameObserver = null;
  74093. this._onEndFrameObserver = null;
  74094. this._onBeforeShaderCompilationObserver = null;
  74095. this._onAfterShaderCompilationObserver = null;
  74096. }
  74097. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74098. // Properties
  74099. /**
  74100. * Gets the perf counter used for GPU frame time
  74101. */
  74102. get: function () {
  74103. return this._gpuFrameTime;
  74104. },
  74105. enumerable: true,
  74106. configurable: true
  74107. });
  74108. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74109. /**
  74110. * Gets the GPU frame time capture status
  74111. */
  74112. get: function () {
  74113. return this._captureGPUFrameTime;
  74114. },
  74115. /**
  74116. * Enable or disable the GPU frame time capture
  74117. */
  74118. set: function (value) {
  74119. var _this = this;
  74120. if (value === this._captureGPUFrameTime) {
  74121. return;
  74122. }
  74123. if (value) {
  74124. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74125. if (!_this._gpuFrameTimeToken) {
  74126. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74127. }
  74128. });
  74129. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74130. if (!_this._gpuFrameTimeToken) {
  74131. return;
  74132. }
  74133. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74134. if (time > -1) {
  74135. _this._gpuFrameTimeToken = null;
  74136. _this._gpuFrameTime.fetchNewFrame();
  74137. _this._gpuFrameTime.addCount(time, true);
  74138. }
  74139. });
  74140. }
  74141. else {
  74142. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74143. this._onBeginFrameObserver = null;
  74144. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74145. this._onEndFrameObserver = null;
  74146. }
  74147. },
  74148. enumerable: true,
  74149. configurable: true
  74150. });
  74151. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74152. /**
  74153. * Gets the perf counter used for shader compilation time
  74154. */
  74155. get: function () {
  74156. return this._shaderCompilationTime;
  74157. },
  74158. enumerable: true,
  74159. configurable: true
  74160. });
  74161. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  74162. /**
  74163. * Gets the shader compilation time capture status
  74164. */
  74165. get: function () {
  74166. return this._captureShaderCompilationTime;
  74167. },
  74168. /**
  74169. * Enable or disable the shader compilation time capture
  74170. */
  74171. set: function (value) {
  74172. var _this = this;
  74173. if (value === this._captureShaderCompilationTime) {
  74174. return;
  74175. }
  74176. if (value) {
  74177. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  74178. _this._shaderCompilationTime.fetchNewFrame();
  74179. _this._shaderCompilationTime.beginMonitoring();
  74180. });
  74181. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  74182. _this._shaderCompilationTime.endMonitoring();
  74183. });
  74184. }
  74185. else {
  74186. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74187. this._onBeforeShaderCompilationObserver = null;
  74188. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74189. this._onAfterShaderCompilationObserver = null;
  74190. }
  74191. },
  74192. enumerable: true,
  74193. configurable: true
  74194. });
  74195. EngineInstrumentation.prototype.dispose = function () {
  74196. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74197. this._onBeginFrameObserver = null;
  74198. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74199. this._onEndFrameObserver = null;
  74200. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  74201. this._onBeforeShaderCompilationObserver = null;
  74202. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  74203. this._onAfterShaderCompilationObserver = null;
  74204. this.engine = null;
  74205. };
  74206. return EngineInstrumentation;
  74207. }());
  74208. BABYLON.EngineInstrumentation = EngineInstrumentation;
  74209. })(BABYLON || (BABYLON = {}));
  74210. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  74211. var BABYLON;
  74212. (function (BABYLON) {
  74213. /**
  74214. * This class can be used to get instrumentation data from a Babylon engine
  74215. */
  74216. var SceneInstrumentation = /** @class */ (function () {
  74217. function SceneInstrumentation(scene) {
  74218. var _this = this;
  74219. this.scene = scene;
  74220. this._captureActiveMeshesEvaluationTime = false;
  74221. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  74222. this._captureRenderTargetsRenderTime = false;
  74223. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  74224. // Observers
  74225. this._onBeforeActiveMeshesEvaluationObserver = null;
  74226. this._onAfterActiveMeshesEvaluationObserver = null;
  74227. this._onBeforeRenderTargetsRenderObserver = null;
  74228. this._onAfterRenderTargetsRenderObserver = null;
  74229. this._onBeforeRenderObserver = null;
  74230. this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function () {
  74231. if (_this._captureActiveMeshesEvaluationTime) {
  74232. _this._activeMeshesEvaluationTime.fetchNewFrame();
  74233. }
  74234. if (_this._captureRenderTargetsRenderTime) {
  74235. _this._renderTargetsRenderTime.fetchNewFrame();
  74236. }
  74237. });
  74238. }
  74239. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTime", {
  74240. // Properties
  74241. /**
  74242. * Gets the perf counter used for active meshes evaluation time
  74243. */
  74244. get: function () {
  74245. return this._activeMeshesEvaluationTime;
  74246. },
  74247. enumerable: true,
  74248. configurable: true
  74249. });
  74250. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  74251. /**
  74252. * Gets the active meshes evaluation time capture status
  74253. */
  74254. get: function () {
  74255. return this._captureActiveMeshesEvaluationTime;
  74256. },
  74257. /**
  74258. * Enable or disable the active meshes evaluation time capture
  74259. */
  74260. set: function (value) {
  74261. var _this = this;
  74262. if (value === this._captureActiveMeshesEvaluationTime) {
  74263. return;
  74264. }
  74265. if (value) {
  74266. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  74267. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  74268. _this._activeMeshesEvaluationTime.beginMonitoring();
  74269. });
  74270. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  74271. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  74272. _this._activeMeshesEvaluationTime.endMonitoring();
  74273. });
  74274. }
  74275. else {
  74276. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74277. this._onBeforeActiveMeshesEvaluationObserver = null;
  74278. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74279. this._onAfterActiveMeshesEvaluationObserver = null;
  74280. }
  74281. },
  74282. enumerable: true,
  74283. configurable: true
  74284. });
  74285. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  74286. /**
  74287. * Gets the perf counter used for render targets render time
  74288. */
  74289. get: function () {
  74290. return this._renderTargetsRenderTime;
  74291. },
  74292. enumerable: true,
  74293. configurable: true
  74294. });
  74295. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  74296. /**
  74297. * Gets the render targets render time capture status
  74298. */
  74299. get: function () {
  74300. return this._captureRenderTargetsRenderTime;
  74301. },
  74302. /**
  74303. * Enable or disable the render targets render time capture
  74304. */
  74305. set: function (value) {
  74306. var _this = this;
  74307. if (value === this._captureRenderTargetsRenderTime) {
  74308. return;
  74309. }
  74310. if (value) {
  74311. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  74312. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  74313. _this._renderTargetsRenderTime.beginMonitoring();
  74314. });
  74315. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  74316. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  74317. _this._renderTargetsRenderTime.endMonitoring(false);
  74318. });
  74319. }
  74320. else {
  74321. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74322. this._onBeforeRenderTargetsRenderObserver = null;
  74323. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74324. this._onAfterRenderTargetsRenderObserver = null;
  74325. }
  74326. },
  74327. enumerable: true,
  74328. configurable: true
  74329. });
  74330. SceneInstrumentation.prototype.dispose = function () {
  74331. this.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74332. this._onBeforeRenderObserver = null;
  74333. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  74334. this._onBeforeActiveMeshesEvaluationObserver = null;
  74335. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  74336. this._onAfterActiveMeshesEvaluationObserver = null;
  74337. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  74338. this._onBeforeRenderTargetsRenderObserver = null;
  74339. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  74340. this._onAfterRenderTargetsRenderObserver = null;
  74341. this.scene = null;
  74342. };
  74343. return SceneInstrumentation;
  74344. }());
  74345. BABYLON.SceneInstrumentation = SceneInstrumentation;
  74346. })(BABYLON || (BABYLON = {}));
  74347. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  74348. var BABYLON;
  74349. (function (BABYLON) {
  74350. var _TimeToken = /** @class */ (function () {
  74351. function _TimeToken() {
  74352. this._timeElapsedQueryEnded = false;
  74353. }
  74354. return _TimeToken;
  74355. }());
  74356. BABYLON._TimeToken = _TimeToken;
  74357. })(BABYLON || (BABYLON = {}));
  74358. //# sourceMappingURL=babylon.timeToken.js.map
  74359. 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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\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(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  74360. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  74361. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74362. var BABYLON;
  74363. (function (BABYLON) {
  74364. var GridMaterialDefines = /** @class */ (function (_super) {
  74365. __extends(GridMaterialDefines, _super);
  74366. function GridMaterialDefines() {
  74367. var _this = _super.call(this) || this;
  74368. _this.TRANSPARENT = false;
  74369. _this.FOG = false;
  74370. _this.PREMULTIPLYALPHA = false;
  74371. _this.rebuild();
  74372. return _this;
  74373. }
  74374. return GridMaterialDefines;
  74375. }(BABYLON.MaterialDefines));
  74376. /**
  74377. * The grid materials allows you to wrap any shape with a grid.
  74378. * Colors are customizable.
  74379. */
  74380. var GridMaterial = /** @class */ (function (_super) {
  74381. __extends(GridMaterial, _super);
  74382. /**
  74383. * constructor
  74384. * @param name The name given to the material in order to identify it afterwards.
  74385. * @param scene The scene the material is used in.
  74386. */
  74387. function GridMaterial(name, scene) {
  74388. var _this = _super.call(this, name, scene) || this;
  74389. /**
  74390. * Main color of the grid (e.g. between lines)
  74391. */
  74392. _this.mainColor = BABYLON.Color3.Black();
  74393. /**
  74394. * Color of the grid lines.
  74395. */
  74396. _this.lineColor = BABYLON.Color3.Teal();
  74397. /**
  74398. * The scale of the grid compared to unit.
  74399. */
  74400. _this.gridRatio = 1.0;
  74401. /**
  74402. * Allows setting an offset for the grid lines.
  74403. */
  74404. _this.gridOffset = BABYLON.Vector3.Zero();
  74405. /**
  74406. * The frequency of thicker lines.
  74407. */
  74408. _this.majorUnitFrequency = 10;
  74409. /**
  74410. * The visibility of minor units in the grid.
  74411. */
  74412. _this.minorUnitVisibility = 0.33;
  74413. /**
  74414. * The grid opacity outside of the lines.
  74415. */
  74416. _this.opacity = 1.0;
  74417. /**
  74418. * Determine RBG output is premultiplied by alpha value.
  74419. */
  74420. _this.preMultiplyAlpha = false;
  74421. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  74422. return _this;
  74423. }
  74424. /**
  74425. * Returns wehter or not the grid requires alpha blending.
  74426. */
  74427. GridMaterial.prototype.needAlphaBlending = function () {
  74428. return this.opacity < 1.0;
  74429. };
  74430. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74431. if (this.isFrozen) {
  74432. if (this._wasPreviouslyReady && subMesh.effect) {
  74433. return true;
  74434. }
  74435. }
  74436. if (!subMesh._materialDefines) {
  74437. subMesh._materialDefines = new GridMaterialDefines();
  74438. }
  74439. var defines = subMesh._materialDefines;
  74440. var scene = this.getScene();
  74441. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74442. if (this._renderId === scene.getRenderId()) {
  74443. return true;
  74444. }
  74445. }
  74446. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  74447. defines.TRANSPARENT = !defines.TRANSPARENT;
  74448. defines.markAsUnprocessed();
  74449. }
  74450. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  74451. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  74452. defines.markAsUnprocessed();
  74453. }
  74454. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  74455. // Get correct effect
  74456. if (defines.isDirty) {
  74457. defines.markAsProcessed();
  74458. scene.resetCachedMaterial();
  74459. // Attributes
  74460. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74461. // Defines
  74462. var join = defines.toString();
  74463. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  74464. }
  74465. if (!subMesh.effect || !subMesh.effect.isReady()) {
  74466. return false;
  74467. }
  74468. this._renderId = scene.getRenderId();
  74469. this._wasPreviouslyReady = true;
  74470. return true;
  74471. };
  74472. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  74473. var scene = this.getScene();
  74474. var defines = subMesh._materialDefines;
  74475. if (!defines) {
  74476. return;
  74477. }
  74478. var effect = subMesh.effect;
  74479. if (!effect) {
  74480. return;
  74481. }
  74482. this._activeEffect = effect;
  74483. // Matrices
  74484. this.bindOnlyWorldMatrix(world);
  74485. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  74486. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  74487. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  74488. // Uniforms
  74489. if (this._mustRebind(scene, effect)) {
  74490. this._activeEffect.setColor3("mainColor", this.mainColor);
  74491. this._activeEffect.setColor3("lineColor", this.lineColor);
  74492. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  74493. this._gridControl.x = this.gridRatio;
  74494. this._gridControl.y = Math.round(this.majorUnitFrequency);
  74495. this._gridControl.z = this.minorUnitVisibility;
  74496. this._gridControl.w = this.opacity;
  74497. this._activeEffect.setVector4("gridControl", this._gridControl);
  74498. }
  74499. // Fog
  74500. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  74501. this._afterBind(mesh, this._activeEffect);
  74502. };
  74503. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  74504. _super.prototype.dispose.call(this, forceDisposeEffect);
  74505. };
  74506. GridMaterial.prototype.clone = function (name) {
  74507. var _this = this;
  74508. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  74509. };
  74510. GridMaterial.prototype.serialize = function () {
  74511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74512. serializationObject.customType = "BABYLON.GridMaterial";
  74513. return serializationObject;
  74514. };
  74515. GridMaterial.prototype.getClassName = function () {
  74516. return "GridMaterial";
  74517. };
  74518. GridMaterial.Parse = function (source, scene, rootUrl) {
  74519. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  74520. };
  74521. __decorate([
  74522. BABYLON.serializeAsColor3()
  74523. ], GridMaterial.prototype, "mainColor", void 0);
  74524. __decorate([
  74525. BABYLON.serializeAsColor3()
  74526. ], GridMaterial.prototype, "lineColor", void 0);
  74527. __decorate([
  74528. BABYLON.serialize()
  74529. ], GridMaterial.prototype, "gridRatio", void 0);
  74530. __decorate([
  74531. BABYLON.serializeAsColor3()
  74532. ], GridMaterial.prototype, "gridOffset", void 0);
  74533. __decorate([
  74534. BABYLON.serialize()
  74535. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  74536. __decorate([
  74537. BABYLON.serialize()
  74538. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  74539. __decorate([
  74540. BABYLON.serialize()
  74541. ], GridMaterial.prototype, "opacity", void 0);
  74542. __decorate([
  74543. BABYLON.serialize()
  74544. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  74545. return GridMaterial;
  74546. }(BABYLON.PushMaterial));
  74547. BABYLON.GridMaterial = GridMaterial;
  74548. })(BABYLON || (BABYLON = {}));
  74549. //# sourceMappingURL=babylon.gridmaterial.js.map
  74550. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  74551. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  74552. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  74553. var BABYLON;
  74554. (function (BABYLON) {
  74555. /**
  74556. * Background material defines definition.
  74557. */
  74558. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  74559. __extends(BackgroundMaterialDefines, _super);
  74560. /**
  74561. * Constructor of the defines.
  74562. */
  74563. function BackgroundMaterialDefines() {
  74564. var _this = _super.call(this) || this;
  74565. /**
  74566. * True if the diffuse texture is in use.
  74567. */
  74568. _this.DIFFUSE = false;
  74569. /**
  74570. * The direct UV channel to use.
  74571. */
  74572. _this.DIFFUSEDIRECTUV = 0;
  74573. /**
  74574. * True if the diffuse texture is in gamma space.
  74575. */
  74576. _this.GAMMADIFFUSE = false;
  74577. /**
  74578. * True if the diffuse texture has opacity in the alpha channel.
  74579. */
  74580. _this.DIFFUSEHASALPHA = false;
  74581. /**
  74582. * True if you want the material to fade to transparent at grazing angle.
  74583. */
  74584. _this.OPACITYFRESNEL = false;
  74585. /**
  74586. * True if an extra blur needs to be added in the reflection.
  74587. */
  74588. _this.REFLECTIONBLUR = false;
  74589. /**
  74590. * False if the current Webgl implementation does not support the texture lod extension.
  74591. */
  74592. _this.TEXTURELODSUPPORT = false;
  74593. /**
  74594. * True to ensure the data are premultiplied.
  74595. */
  74596. _this.PREMULTIPLYALPHA = false;
  74597. /**
  74598. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  74599. */
  74600. _this.USERGBCOLOR = false;
  74601. // Image Processing Configuration.
  74602. _this.IMAGEPROCESSING = false;
  74603. _this.VIGNETTE = false;
  74604. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  74605. _this.VIGNETTEBLENDMODEOPAQUE = false;
  74606. _this.TONEMAPPING = false;
  74607. _this.CONTRAST = false;
  74608. _this.COLORCURVES = false;
  74609. _this.COLORGRADING = false;
  74610. _this.COLORGRADING3D = false;
  74611. _this.SAMPLER3DGREENDEPTH = false;
  74612. _this.SAMPLER3DBGRMAP = false;
  74613. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  74614. _this.EXPOSURE = false;
  74615. // Reflection.
  74616. _this.REFLECTION = false;
  74617. _this.REFLECTIONMAP_3D = false;
  74618. _this.REFLECTIONMAP_SPHERICAL = false;
  74619. _this.REFLECTIONMAP_PLANAR = false;
  74620. _this.REFLECTIONMAP_CUBIC = false;
  74621. _this.REFLECTIONMAP_PROJECTION = false;
  74622. _this.REFLECTIONMAP_SKYBOX = false;
  74623. _this.REFLECTIONMAP_EXPLICIT = false;
  74624. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  74625. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  74626. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  74627. _this.INVERTCUBICMAP = false;
  74628. _this.REFLECTIONMAP_OPPOSITEZ = false;
  74629. _this.LODINREFLECTIONALPHA = false;
  74630. _this.GAMMAREFLECTION = false;
  74631. // Default BJS.
  74632. _this.MAINUV1 = false;
  74633. _this.MAINUV2 = false;
  74634. _this.UV1 = false;
  74635. _this.UV2 = false;
  74636. _this.CLIPPLANE = false;
  74637. _this.POINTSIZE = false;
  74638. _this.FOG = false;
  74639. _this.NORMAL = false;
  74640. _this.NUM_BONE_INFLUENCERS = 0;
  74641. _this.BonesPerMesh = 0;
  74642. _this.INSTANCES = false;
  74643. _this.SHADOWFLOAT = false;
  74644. _this.rebuild();
  74645. return _this;
  74646. }
  74647. return BackgroundMaterialDefines;
  74648. }(BABYLON.MaterialDefines));
  74649. /**
  74650. * Background material
  74651. */
  74652. var BackgroundMaterial = /** @class */ (function (_super) {
  74653. __extends(BackgroundMaterial, _super);
  74654. /**
  74655. * constructor
  74656. * @param name The name of the material
  74657. * @param scene The scene to add the material to
  74658. */
  74659. function BackgroundMaterial(name, scene) {
  74660. var _this = _super.call(this, name, scene) || this;
  74661. _this.primaryColor = BABYLON.Color3.White();
  74662. _this.primaryLevel = 1;
  74663. _this.secondaryColor = BABYLON.Color3.Gray();
  74664. _this.secondaryLevel = 1;
  74665. _this.thirdColor = BABYLON.Color3.Black();
  74666. _this.thirdLevel = 1;
  74667. _this.reflectionTexture = null;
  74668. _this.reflectionBlur = 0;
  74669. _this.diffuseTexture = null;
  74670. /**
  74671. * Specify the list of lights casting shadow on the material.
  74672. * All scene shadow lights will be included if null.
  74673. */
  74674. _this._shadowLights = null;
  74675. _this.shadowLights = null;
  74676. _this.shadowBlurScale = 1;
  74677. _this.shadowLevel = 0;
  74678. _this.opacityFresnel = true;
  74679. _this.useRGBColor = true;
  74680. /**
  74681. * Number of Simultaneous lights allowed on the material.
  74682. */
  74683. _this._maxSimultaneousLights = 4;
  74684. _this.maxSimultaneousLights = 4;
  74685. /**
  74686. * Keep track of the image processing observer to allow dispose and replace.
  74687. */
  74688. _this._imageProcessingObserver = null;
  74689. // Temp values kept as cache in the material.
  74690. _this._renderTargets = new BABYLON.SmartArray(16);
  74691. // Setup the default processing configuration to the scene.
  74692. _this._attachImageProcessingConfiguration(null);
  74693. _this.getRenderTargetTextures = function () {
  74694. _this._renderTargets.reset();
  74695. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  74696. _this._renderTargets.push(_this._diffuseTexture);
  74697. }
  74698. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  74699. _this._renderTargets.push(_this._reflectionTexture);
  74700. }
  74701. return _this._renderTargets;
  74702. };
  74703. return _this;
  74704. }
  74705. /**
  74706. * Attaches a new image processing configuration to the PBR Material.
  74707. * @param configuration (if null the scene configuration will be use)
  74708. */
  74709. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  74710. var _this = this;
  74711. if (configuration === this._imageProcessingConfiguration) {
  74712. return;
  74713. }
  74714. // Detaches observer.
  74715. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  74716. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  74717. }
  74718. // Pick the scene configuration if needed.
  74719. if (!configuration) {
  74720. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  74721. }
  74722. else {
  74723. this._imageProcessingConfiguration = configuration;
  74724. }
  74725. // Attaches observer.
  74726. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  74727. _this._markAllSubMeshesAsImageProcessingDirty();
  74728. });
  74729. };
  74730. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  74731. /**
  74732. * Gets the image processing configuration used either in this material.
  74733. */
  74734. get: function () {
  74735. return this._imageProcessingConfiguration;
  74736. },
  74737. /**
  74738. * Sets the Default image processing configuration used either in the this material.
  74739. *
  74740. * If sets to null, the scene one is in use.
  74741. */
  74742. set: function (value) {
  74743. this._attachImageProcessingConfiguration(value);
  74744. // Ensure the effect will be rebuilt.
  74745. this._markAllSubMeshesAsTexturesDirty();
  74746. },
  74747. enumerable: true,
  74748. configurable: true
  74749. });
  74750. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  74751. /**
  74752. * Gets wether the color curves effect is enabled.
  74753. */
  74754. get: function () {
  74755. return this.imageProcessingConfiguration.colorCurvesEnabled;
  74756. },
  74757. /**
  74758. * Sets wether the color curves effect is enabled.
  74759. */
  74760. set: function (value) {
  74761. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  74762. },
  74763. enumerable: true,
  74764. configurable: true
  74765. });
  74766. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  74767. /**
  74768. * Gets wether the color grading effect is enabled.
  74769. */
  74770. get: function () {
  74771. return this.imageProcessingConfiguration.colorGradingEnabled;
  74772. },
  74773. /**
  74774. * Gets wether the color grading effect is enabled.
  74775. */
  74776. set: function (value) {
  74777. this.imageProcessingConfiguration.colorGradingEnabled = value;
  74778. },
  74779. enumerable: true,
  74780. configurable: true
  74781. });
  74782. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  74783. /**
  74784. * Gets wether tonemapping is enabled or not.
  74785. */
  74786. get: function () {
  74787. return this._imageProcessingConfiguration.toneMappingEnabled;
  74788. },
  74789. /**
  74790. * Sets wether tonemapping is enabled or not
  74791. */
  74792. set: function (value) {
  74793. this._imageProcessingConfiguration.toneMappingEnabled = value;
  74794. },
  74795. enumerable: true,
  74796. configurable: true
  74797. });
  74798. ;
  74799. ;
  74800. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  74801. /**
  74802. * The camera exposure used on this material.
  74803. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74804. * This corresponds to a photographic exposure.
  74805. */
  74806. get: function () {
  74807. return this._imageProcessingConfiguration.exposure;
  74808. },
  74809. /**
  74810. * The camera exposure used on this material.
  74811. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  74812. * This corresponds to a photographic exposure.
  74813. */
  74814. set: function (value) {
  74815. this._imageProcessingConfiguration.exposure = value;
  74816. },
  74817. enumerable: true,
  74818. configurable: true
  74819. });
  74820. ;
  74821. ;
  74822. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  74823. /**
  74824. * Gets The camera contrast used on this material.
  74825. */
  74826. get: function () {
  74827. return this._imageProcessingConfiguration.contrast;
  74828. },
  74829. /**
  74830. * Sets The camera contrast used on this material.
  74831. */
  74832. set: function (value) {
  74833. this._imageProcessingConfiguration.contrast = value;
  74834. },
  74835. enumerable: true,
  74836. configurable: true
  74837. });
  74838. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  74839. /**
  74840. * Gets the Color Grading 2D Lookup Texture.
  74841. */
  74842. get: function () {
  74843. return this._imageProcessingConfiguration.colorGradingTexture;
  74844. },
  74845. /**
  74846. * Sets the Color Grading 2D Lookup Texture.
  74847. */
  74848. set: function (value) {
  74849. this.imageProcessingConfiguration.colorGradingTexture = value;
  74850. },
  74851. enumerable: true,
  74852. configurable: true
  74853. });
  74854. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  74855. /**
  74856. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74857. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74858. * 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;
  74859. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74860. */
  74861. get: function () {
  74862. return this.imageProcessingConfiguration.colorCurves;
  74863. },
  74864. /**
  74865. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  74866. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  74867. * 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;
  74868. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  74869. */
  74870. set: function (value) {
  74871. this.imageProcessingConfiguration.colorCurves = value;
  74872. },
  74873. enumerable: true,
  74874. configurable: true
  74875. });
  74876. /**
  74877. * The entire material has been created in order to prevent overdraw.
  74878. * @returns false
  74879. */
  74880. BackgroundMaterial.prototype.needAlphaTesting = function () {
  74881. return false;
  74882. };
  74883. /**
  74884. * The entire material has been created in order to prevent overdraw.
  74885. * @returns true if blending is enable
  74886. */
  74887. BackgroundMaterial.prototype.needAlphaBlending = function () {
  74888. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  74889. };
  74890. /**
  74891. * Checks wether the material is ready to be rendered for a given mesh.
  74892. * @param mesh The mesh to render
  74893. * @param subMesh The submesh to check against
  74894. * @param useInstances Specify wether or not the material is used with instances
  74895. */
  74896. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  74897. var _this = this;
  74898. if (useInstances === void 0) { useInstances = false; }
  74899. if (subMesh.effect && this.isFrozen) {
  74900. if (this._wasPreviouslyReady) {
  74901. return true;
  74902. }
  74903. }
  74904. if (!subMesh._materialDefines) {
  74905. subMesh._materialDefines = new BackgroundMaterialDefines();
  74906. }
  74907. var scene = this.getScene();
  74908. var defines = subMesh._materialDefines;
  74909. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  74910. if (defines._renderId === scene.getRenderId()) {
  74911. return true;
  74912. }
  74913. }
  74914. var engine = scene.getEngine();
  74915. // Lights
  74916. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  74917. defines._needNormals = true;
  74918. // Textures
  74919. if (defines._areTexturesDirty) {
  74920. defines._needUVs = false;
  74921. if (scene.texturesEnabled) {
  74922. if (scene.getEngine().getCaps().textureLOD) {
  74923. defines.TEXTURELODSUPPORT = true;
  74924. }
  74925. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  74926. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  74927. return false;
  74928. }
  74929. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  74930. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  74931. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  74932. defines.OPACITYFRESNEL = this._opacityFresnel;
  74933. }
  74934. else {
  74935. defines.DIFFUSE = false;
  74936. defines.DIFFUSEHASALPHA = false;
  74937. defines.GAMMADIFFUSE = false;
  74938. defines.OPACITYFRESNEL = false;
  74939. }
  74940. var reflectionTexture = this._reflectionTexture;
  74941. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  74942. if (!reflectionTexture.isReadyOrNotBlocking()) {
  74943. return false;
  74944. }
  74945. defines.REFLECTION = true;
  74946. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  74947. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  74948. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  74949. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  74950. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  74951. defines.INVERTCUBICMAP = true;
  74952. }
  74953. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  74954. switch (reflectionTexture.coordinatesMode) {
  74955. case BABYLON.Texture.CUBIC_MODE:
  74956. case BABYLON.Texture.INVCUBIC_MODE:
  74957. defines.REFLECTIONMAP_CUBIC = true;
  74958. break;
  74959. case BABYLON.Texture.EXPLICIT_MODE:
  74960. defines.REFLECTIONMAP_EXPLICIT = true;
  74961. break;
  74962. case BABYLON.Texture.PLANAR_MODE:
  74963. defines.REFLECTIONMAP_PLANAR = true;
  74964. break;
  74965. case BABYLON.Texture.PROJECTION_MODE:
  74966. defines.REFLECTIONMAP_PROJECTION = true;
  74967. break;
  74968. case BABYLON.Texture.SKYBOX_MODE:
  74969. defines.REFLECTIONMAP_SKYBOX = true;
  74970. break;
  74971. case BABYLON.Texture.SPHERICAL_MODE:
  74972. defines.REFLECTIONMAP_SPHERICAL = true;
  74973. break;
  74974. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  74975. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  74976. break;
  74977. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  74978. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  74979. break;
  74980. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  74981. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  74982. break;
  74983. }
  74984. }
  74985. else {
  74986. defines.REFLECTION = false;
  74987. defines.REFLECTIONBLUR = false;
  74988. defines.REFLECTIONMAP_3D = false;
  74989. defines.REFLECTIONMAP_SPHERICAL = false;
  74990. defines.REFLECTIONMAP_PLANAR = false;
  74991. defines.REFLECTIONMAP_CUBIC = false;
  74992. defines.REFLECTIONMAP_PROJECTION = false;
  74993. defines.REFLECTIONMAP_SKYBOX = false;
  74994. defines.REFLECTIONMAP_EXPLICIT = false;
  74995. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  74996. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  74997. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  74998. defines.INVERTCUBICMAP = false;
  74999. defines.REFLECTIONMAP_OPPOSITEZ = false;
  75000. defines.LODINREFLECTIONALPHA = false;
  75001. defines.GAMMAREFLECTION = false;
  75002. }
  75003. }
  75004. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  75005. defines.USERGBCOLOR = this._useRGBColor;
  75006. }
  75007. if (defines._areImageProcessingDirty) {
  75008. if (!this._imageProcessingConfiguration.isReady()) {
  75009. return false;
  75010. }
  75011. this._imageProcessingConfiguration.prepareDefines(defines);
  75012. }
  75013. // Misc.
  75014. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  75015. // Values that need to be evaluated on every frame
  75016. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  75017. // Attribs
  75018. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  75019. if (mesh) {
  75020. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75021. mesh.createNormals(true);
  75022. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  75023. }
  75024. }
  75025. }
  75026. // Get correct effect
  75027. if (defines.isDirty) {
  75028. defines.markAsProcessed();
  75029. scene.resetCachedMaterial();
  75030. // Fallbacks
  75031. var fallbacks = new BABYLON.EffectFallbacks();
  75032. if (defines.FOG) {
  75033. fallbacks.addFallback(0, "FOG");
  75034. }
  75035. if (defines.POINTSIZE) {
  75036. fallbacks.addFallback(1, "POINTSIZE");
  75037. }
  75038. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  75039. if (defines.NUM_BONE_INFLUENCERS > 0) {
  75040. fallbacks.addCPUSkinningFallback(0, mesh);
  75041. }
  75042. //Attributes
  75043. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75044. if (defines.NORMAL) {
  75045. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75046. }
  75047. if (defines.UV1) {
  75048. attribs.push(BABYLON.VertexBuffer.UVKind);
  75049. }
  75050. if (defines.UV2) {
  75051. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75052. }
  75053. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  75054. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  75055. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  75056. "vFogInfos", "vFogColor", "pointSize",
  75057. "vClipPlane", "mBones",
  75058. "vPrimaryColor", "vSecondaryColor", "vThirdColor",
  75059. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  75060. "shadowLevel", "alpha",
  75061. "vDiffuseInfos", "diffuseMatrix",
  75062. ];
  75063. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  75064. var uniformBuffers = ["Material", "Scene"];
  75065. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  75066. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  75067. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  75068. uniformsNames: uniforms,
  75069. uniformBuffersNames: uniformBuffers,
  75070. samplers: samplers,
  75071. defines: defines,
  75072. maxSimultaneousLights: this._maxSimultaneousLights
  75073. });
  75074. var onCompiled = function (effect) {
  75075. if (_this.onCompiled) {
  75076. _this.onCompiled(effect);
  75077. }
  75078. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  75079. };
  75080. var join = defines.toString();
  75081. subMesh.setEffect(scene.getEngine().createEffect("background", {
  75082. attributes: attribs,
  75083. uniformsNames: uniforms,
  75084. uniformBuffersNames: uniformBuffers,
  75085. samplers: samplers,
  75086. defines: join,
  75087. fallbacks: fallbacks,
  75088. onCompiled: onCompiled,
  75089. onError: this.onError,
  75090. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  75091. }, engine), defines);
  75092. this.buildUniformLayout();
  75093. }
  75094. if (!subMesh.effect || !subMesh.effect.isReady()) {
  75095. return false;
  75096. }
  75097. defines._renderId = scene.getRenderId();
  75098. this._wasPreviouslyReady = true;
  75099. return true;
  75100. };
  75101. /**
  75102. * Build the uniform buffer used in the material.
  75103. */
  75104. BackgroundMaterial.prototype.buildUniformLayout = function () {
  75105. // Order is important !
  75106. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  75107. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  75108. this._uniformBuffer.addUniform("vThirdColor", 4);
  75109. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  75110. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  75111. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  75112. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  75113. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  75114. this._uniformBuffer.addUniform("pointSize", 1);
  75115. this._uniformBuffer.addUniform("shadowLevel", 1);
  75116. this._uniformBuffer.addUniform("alpha", 1);
  75117. this._uniformBuffer.create();
  75118. };
  75119. /**
  75120. * Unbind the material.
  75121. */
  75122. BackgroundMaterial.prototype.unbind = function () {
  75123. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  75124. this._uniformBuffer.setTexture("diffuseSampler", null);
  75125. }
  75126. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  75127. this._uniformBuffer.setTexture("reflectionSampler", null);
  75128. }
  75129. _super.prototype.unbind.call(this);
  75130. };
  75131. /**
  75132. * Bind only the world matrix to the material.
  75133. * @param world The world matrix to bind.
  75134. */
  75135. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  75136. this._activeEffect.setMatrix("world", world);
  75137. };
  75138. /**
  75139. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  75140. * @param world The world matrix to bind.
  75141. * @param subMesh The submesh to bind for.
  75142. */
  75143. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  75144. var scene = this.getScene();
  75145. var defines = subMesh._materialDefines;
  75146. if (!defines) {
  75147. return;
  75148. }
  75149. var effect = subMesh.effect;
  75150. if (!effect) {
  75151. return;
  75152. }
  75153. this._activeEffect = effect;
  75154. // Matrices
  75155. this.bindOnlyWorldMatrix(world);
  75156. // Bones
  75157. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  75158. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  75159. if (mustRebind) {
  75160. this._uniformBuffer.bindToEffect(effect, "Material");
  75161. this.bindViewProjection(effect);
  75162. var reflectionTexture = this._reflectionTexture;
  75163. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  75164. // Texture uniforms
  75165. if (scene.texturesEnabled) {
  75166. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75167. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  75168. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  75169. }
  75170. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75171. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  75172. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  75173. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  75174. }
  75175. }
  75176. if (this.shadowLevel > 0) {
  75177. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  75178. }
  75179. this._uniformBuffer.updateFloat("alpha", this.alpha);
  75180. // Point size
  75181. if (this.pointsCloud) {
  75182. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  75183. }
  75184. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  75185. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  75186. this._uniformBuffer.updateColor4("vThirdColor", this._thirdColor, this._thirdLevel);
  75187. }
  75188. // Textures
  75189. if (scene.texturesEnabled) {
  75190. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  75191. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  75192. }
  75193. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  75194. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  75195. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75196. }
  75197. else if (!defines.REFLECTIONBLUR) {
  75198. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  75199. }
  75200. else {
  75201. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  75202. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  75203. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  75204. }
  75205. }
  75206. }
  75207. // Clip plane
  75208. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  75209. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  75210. // var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  75211. effect.setFloat3("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z);
  75212. }
  75213. if (mustRebind || !this.isFrozen) {
  75214. if (scene.lightsEnabled) {
  75215. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  75216. }
  75217. // View
  75218. this.bindView(effect);
  75219. // Fog
  75220. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  75221. // image processing
  75222. this._imageProcessingConfiguration.bind(this._activeEffect);
  75223. }
  75224. this._uniformBuffer.update();
  75225. this._afterBind(mesh);
  75226. };
  75227. /**
  75228. * Dispose the material.
  75229. * @forceDisposeEffect Force disposal of the associated effect.
  75230. * @forceDisposeTextures Force disposal of the associated textures.
  75231. */
  75232. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75233. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  75234. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  75235. if (forceDisposeTextures) {
  75236. if (this.diffuseTexture) {
  75237. this.diffuseTexture.dispose();
  75238. }
  75239. if (this.reflectionTexture) {
  75240. this.reflectionTexture.dispose();
  75241. }
  75242. }
  75243. this._renderTargets.dispose();
  75244. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75245. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75246. }
  75247. _super.prototype.dispose.call(this, forceDisposeEffect);
  75248. };
  75249. /**
  75250. * Clones the material.
  75251. * @name The cloned name.
  75252. * @returns The cloned material.
  75253. */
  75254. BackgroundMaterial.prototype.clone = function (name) {
  75255. var _this = this;
  75256. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  75257. };
  75258. /**
  75259. * Serializes the current material to its JSON representation.
  75260. * @returns The JSON representation.
  75261. */
  75262. BackgroundMaterial.prototype.serialize = function () {
  75263. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75264. serializationObject.customType = "BABYLON.BackgroundMaterial";
  75265. return serializationObject;
  75266. };
  75267. /**
  75268. * Gets the class name of the material
  75269. * @returns "BackgroundMaterial"
  75270. */
  75271. BackgroundMaterial.prototype.getClassName = function () {
  75272. return "BackgroundMaterial";
  75273. };
  75274. /**
  75275. * Parse a JSON input to create back a background material.
  75276. * @param source
  75277. * @param scene
  75278. * @param rootUrl
  75279. * @returns the instantiated BackgroundMaterial.
  75280. */
  75281. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  75282. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  75283. };
  75284. __decorate([
  75285. BABYLON.serializeAsColor3()
  75286. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  75287. __decorate([
  75288. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75289. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  75290. __decorate([
  75291. BABYLON.serialize()
  75292. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  75293. __decorate([
  75294. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75295. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  75296. __decorate([
  75297. BABYLON.serializeAsColor3()
  75298. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  75299. __decorate([
  75300. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75301. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  75302. __decorate([
  75303. BABYLON.serialize()
  75304. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  75305. __decorate([
  75306. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75307. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  75308. __decorate([
  75309. BABYLON.serializeAsColor3()
  75310. ], BackgroundMaterial.prototype, "_thirdColor", void 0);
  75311. __decorate([
  75312. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75313. ], BackgroundMaterial.prototype, "thirdColor", void 0);
  75314. __decorate([
  75315. BABYLON.serialize()
  75316. ], BackgroundMaterial.prototype, "_thirdLevel", void 0);
  75317. __decorate([
  75318. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  75319. ], BackgroundMaterial.prototype, "thirdLevel", void 0);
  75320. __decorate([
  75321. BABYLON.serializeAsTexture()
  75322. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  75323. __decorate([
  75324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75325. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  75326. __decorate([
  75327. BABYLON.serialize()
  75328. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  75329. __decorate([
  75330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75331. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  75332. __decorate([
  75333. BABYLON.serializeAsTexture()
  75334. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  75335. __decorate([
  75336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75337. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  75338. __decorate([
  75339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75340. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  75341. __decorate([
  75342. BABYLON.serialize()
  75343. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  75344. __decorate([
  75345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75346. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  75347. __decorate([
  75348. BABYLON.serialize()
  75349. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  75350. __decorate([
  75351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75352. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  75353. __decorate([
  75354. BABYLON.serialize()
  75355. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  75356. __decorate([
  75357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75358. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  75359. __decorate([
  75360. BABYLON.serialize()
  75361. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  75362. __decorate([
  75363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75364. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  75365. __decorate([
  75366. BABYLON.serialize()
  75367. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  75368. __decorate([
  75369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  75370. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  75371. __decorate([
  75372. BABYLON.serializeAsImageProcessingConfiguration()
  75373. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  75374. return BackgroundMaterial;
  75375. }(BABYLON.PushMaterial));
  75376. BABYLON.BackgroundMaterial = BackgroundMaterial;
  75377. })(BABYLON || (BABYLON = {}));
  75378. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  75379. BABYLON.Effect.ShadersStore['backgroundVertexShader'] = "precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n";
  75380. BABYLON.Effect.ShadersStore['backgroundPixelShader'] = "#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 environmentColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nenvironmentColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nenvironmentColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nenvironmentColor=sampleReflection(reflectionSampler,reflectionCoords).rgb;\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentColor=toLinearSpace(environmentColor.rgb);\n#endif\n\nenvironmentColor*=vReflectionInfos.x;\n#endif\n\nvec3 groundColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ngroundColor=diffuseMap.rgb;\n#endif\n\nvec3 colorBase=environmentColor*groundColor;\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vThirdColor.rgb*vThirdColor.a;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n#ifdef OPACITYFRESNEL\n\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}";
  75381. BABYLON.Effect.IncludesShadersStore['backgroundFragmentDeclaration'] = " uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\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";
  75382. BABYLON.Effect.IncludesShadersStore['backgroundUboDeclaration'] = "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vThirdColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};";
  75383. BABYLON.Effect.IncludesShadersStore['backgroundVertexDeclaration'] = "uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  75384. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  75385. var BABYLON;
  75386. (function (BABYLON) {
  75387. var GLTFLoaderCoordinateSystemMode;
  75388. (function (GLTFLoaderCoordinateSystemMode) {
  75389. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  75390. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  75391. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  75392. // The glTF right-handed data is not transformed in any form and is loaded directly.
  75393. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  75394. // Sets the useRightHandedSystem flag on the scene.
  75395. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  75396. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  75397. var GLTFFileLoader = /** @class */ (function () {
  75398. function GLTFFileLoader() {
  75399. // V2 options
  75400. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  75401. this.name = "gltf";
  75402. this.extensions = {
  75403. ".gltf": { isBinary: false },
  75404. ".glb": { isBinary: true }
  75405. };
  75406. }
  75407. GLTFFileLoader.prototype.dispose = function () {
  75408. if (this._loader) {
  75409. this._loader.dispose();
  75410. this._loader = null;
  75411. }
  75412. };
  75413. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75414. var loaderData = GLTFFileLoader._parse(data, onError);
  75415. if (!loaderData) {
  75416. return;
  75417. }
  75418. if (this.onParsed) {
  75419. this.onParsed(loaderData);
  75420. }
  75421. this._loader = this._getLoader(loaderData, onError);
  75422. if (!this._loader) {
  75423. return;
  75424. }
  75425. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75426. };
  75427. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75428. var loaderData = GLTFFileLoader._parse(data, onError);
  75429. if (!loaderData) {
  75430. return;
  75431. }
  75432. if (this.onParsed) {
  75433. this.onParsed(loaderData);
  75434. }
  75435. this._loader = this._getLoader(loaderData, onError);
  75436. if (!this._loader) {
  75437. return;
  75438. }
  75439. return this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  75440. };
  75441. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  75442. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  75443. };
  75444. GLTFFileLoader._parse = function (data, onError) {
  75445. try {
  75446. if (data instanceof ArrayBuffer) {
  75447. return GLTFFileLoader._parseBinary(data, onError);
  75448. }
  75449. return {
  75450. json: JSON.parse(data),
  75451. bin: null
  75452. };
  75453. }
  75454. catch (e) {
  75455. onError(e.message);
  75456. return null;
  75457. }
  75458. };
  75459. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  75460. var loaderVersion = { major: 2, minor: 0 };
  75461. var asset = loaderData.json.asset || {};
  75462. var version = GLTFFileLoader._parseVersion(asset.version);
  75463. if (!version) {
  75464. onError("Invalid version: " + asset.version);
  75465. return null;
  75466. }
  75467. if (asset.minVersion !== undefined) {
  75468. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  75469. if (!minVersion) {
  75470. onError("Invalid minimum version: " + asset.minVersion);
  75471. return null;
  75472. }
  75473. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  75474. onError("Incompatible minimum version: " + asset.minVersion);
  75475. return null;
  75476. }
  75477. }
  75478. var createLoaders = {
  75479. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  75480. 2: GLTFFileLoader.CreateGLTFLoaderV2
  75481. };
  75482. var createLoader = createLoaders[version.major];
  75483. if (!createLoader) {
  75484. onError("Unsupported version: " + asset.version);
  75485. return null;
  75486. }
  75487. return createLoader(this);
  75488. };
  75489. GLTFFileLoader._parseBinary = function (data, onError) {
  75490. var Binary = {
  75491. Magic: 0x46546C67
  75492. };
  75493. var binaryReader = new BinaryReader(data);
  75494. var magic = binaryReader.readUint32();
  75495. if (magic !== Binary.Magic) {
  75496. onError("Unexpected magic: " + magic);
  75497. return null;
  75498. }
  75499. var version = binaryReader.readUint32();
  75500. switch (version) {
  75501. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  75502. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  75503. }
  75504. onError("Unsupported version: " + version);
  75505. return null;
  75506. };
  75507. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  75508. var ContentFormat = {
  75509. JSON: 0
  75510. };
  75511. var length = binaryReader.readUint32();
  75512. if (length != binaryReader.getLength()) {
  75513. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75514. return null;
  75515. }
  75516. var contentLength = binaryReader.readUint32();
  75517. var contentFormat = binaryReader.readUint32();
  75518. var content;
  75519. switch (contentFormat) {
  75520. case ContentFormat.JSON:
  75521. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  75522. break;
  75523. default:
  75524. onError("Unexpected content format: " + contentFormat);
  75525. return null;
  75526. }
  75527. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  75528. var body = binaryReader.readUint8Array(bytesRemaining);
  75529. return {
  75530. json: content,
  75531. bin: body
  75532. };
  75533. };
  75534. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  75535. var ChunkFormat = {
  75536. JSON: 0x4E4F534A,
  75537. BIN: 0x004E4942
  75538. };
  75539. var length = binaryReader.readUint32();
  75540. if (length !== binaryReader.getLength()) {
  75541. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  75542. return null;
  75543. }
  75544. // JSON chunk
  75545. var chunkLength = binaryReader.readUint32();
  75546. var chunkFormat = binaryReader.readUint32();
  75547. if (chunkFormat !== ChunkFormat.JSON) {
  75548. onError("First chunk format is not JSON");
  75549. return null;
  75550. }
  75551. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  75552. // Look for BIN chunk
  75553. var bin = null;
  75554. while (binaryReader.getPosition() < binaryReader.getLength()) {
  75555. var chunkLength_1 = binaryReader.readUint32();
  75556. var chunkFormat_1 = binaryReader.readUint32();
  75557. switch (chunkFormat_1) {
  75558. case ChunkFormat.JSON:
  75559. onError("Unexpected JSON chunk");
  75560. return null;
  75561. case ChunkFormat.BIN:
  75562. bin = binaryReader.readUint8Array(chunkLength_1);
  75563. break;
  75564. default:
  75565. // ignore unrecognized chunkFormat
  75566. binaryReader.skipBytes(chunkLength_1);
  75567. break;
  75568. }
  75569. }
  75570. return {
  75571. json: json,
  75572. bin: bin
  75573. };
  75574. };
  75575. GLTFFileLoader._parseVersion = function (version) {
  75576. var match = (version + "").match(/^(\d+)\.(\d+)$/);
  75577. if (!match) {
  75578. return null;
  75579. }
  75580. return {
  75581. major: parseInt(match[1]),
  75582. minor: parseInt(match[2])
  75583. };
  75584. };
  75585. GLTFFileLoader._compareVersion = function (a, b) {
  75586. if (a.major > b.major)
  75587. return 1;
  75588. if (a.major < b.major)
  75589. return -1;
  75590. if (a.minor > b.minor)
  75591. return 1;
  75592. if (a.minor < b.minor)
  75593. return -1;
  75594. return 0;
  75595. };
  75596. GLTFFileLoader._decodeBufferToText = function (buffer) {
  75597. var result = "";
  75598. var length = buffer.byteLength;
  75599. for (var i = 0; i < length; i++) {
  75600. result += String.fromCharCode(buffer[i]);
  75601. }
  75602. return result;
  75603. };
  75604. // V1 options
  75605. GLTFFileLoader.HomogeneousCoordinates = false;
  75606. GLTFFileLoader.IncrementalLoading = true;
  75607. return GLTFFileLoader;
  75608. }());
  75609. BABYLON.GLTFFileLoader = GLTFFileLoader;
  75610. var BinaryReader = /** @class */ (function () {
  75611. function BinaryReader(arrayBuffer) {
  75612. this._arrayBuffer = arrayBuffer;
  75613. this._dataView = new DataView(arrayBuffer);
  75614. this._byteOffset = 0;
  75615. }
  75616. BinaryReader.prototype.getPosition = function () {
  75617. return this._byteOffset;
  75618. };
  75619. BinaryReader.prototype.getLength = function () {
  75620. return this._arrayBuffer.byteLength;
  75621. };
  75622. BinaryReader.prototype.readUint32 = function () {
  75623. var value = this._dataView.getUint32(this._byteOffset, true);
  75624. this._byteOffset += 4;
  75625. return value;
  75626. };
  75627. BinaryReader.prototype.readUint8Array = function (length) {
  75628. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75629. this._byteOffset += length;
  75630. return value;
  75631. };
  75632. BinaryReader.prototype.skipBytes = function (length) {
  75633. this._byteOffset += length;
  75634. };
  75635. return BinaryReader;
  75636. }());
  75637. if (BABYLON.SceneLoader) {
  75638. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  75639. }
  75640. })(BABYLON || (BABYLON = {}));
  75641. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  75642. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75643. var BABYLON;
  75644. (function (BABYLON) {
  75645. var GLTF1;
  75646. (function (GLTF1) {
  75647. /**
  75648. * Enums
  75649. */
  75650. var EComponentType;
  75651. (function (EComponentType) {
  75652. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75653. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75654. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75655. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75656. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75657. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  75658. var EShaderType;
  75659. (function (EShaderType) {
  75660. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  75661. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  75662. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  75663. var EParameterType;
  75664. (function (EParameterType) {
  75665. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  75666. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75667. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  75668. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75669. EParameterType[EParameterType["INT"] = 5124] = "INT";
  75670. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75671. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  75672. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  75673. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  75674. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  75675. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  75676. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  75677. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  75678. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  75679. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  75680. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  75681. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  75682. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  75683. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  75684. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  75685. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  75686. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  75687. var ETextureWrapMode;
  75688. (function (ETextureWrapMode) {
  75689. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75690. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75691. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75692. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  75693. var ETextureFilterType;
  75694. (function (ETextureFilterType) {
  75695. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  75696. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  75697. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75698. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75699. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75700. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75701. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  75702. var ETextureFormat;
  75703. (function (ETextureFormat) {
  75704. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  75705. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  75706. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  75707. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  75708. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  75709. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  75710. var ECullingType;
  75711. (function (ECullingType) {
  75712. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  75713. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  75714. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  75715. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  75716. var EBlendingFunction;
  75717. (function (EBlendingFunction) {
  75718. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  75719. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  75720. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  75721. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  75722. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  75723. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  75724. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  75725. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  75726. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  75727. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  75728. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  75729. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  75730. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  75731. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  75732. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  75733. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  75734. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75735. })(BABYLON || (BABYLON = {}));
  75736. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75737. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75738. var BABYLON;
  75739. (function (BABYLON) {
  75740. var GLTF1;
  75741. (function (GLTF1) {
  75742. /**
  75743. * Tokenizer. Used for shaders compatibility
  75744. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  75745. */
  75746. var ETokenType;
  75747. (function (ETokenType) {
  75748. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  75749. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  75750. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  75751. })(ETokenType || (ETokenType = {}));
  75752. var Tokenizer = /** @class */ (function () {
  75753. function Tokenizer(toParse) {
  75754. this._pos = 0;
  75755. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  75756. this._toParse = toParse;
  75757. this._maxPos = toParse.length;
  75758. }
  75759. Tokenizer.prototype.getNextToken = function () {
  75760. if (this.isEnd())
  75761. return ETokenType.END_OF_INPUT;
  75762. this.currentString = this.read();
  75763. this.currentToken = ETokenType.UNKNOWN;
  75764. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  75765. this.currentToken = ETokenType.IDENTIFIER;
  75766. this.currentIdentifier = this.currentString;
  75767. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  75768. this.currentIdentifier += this.currentString;
  75769. this.forward();
  75770. }
  75771. }
  75772. return this.currentToken;
  75773. };
  75774. Tokenizer.prototype.peek = function () {
  75775. return this._toParse[this._pos];
  75776. };
  75777. Tokenizer.prototype.read = function () {
  75778. return this._toParse[this._pos++];
  75779. };
  75780. Tokenizer.prototype.forward = function () {
  75781. this._pos++;
  75782. };
  75783. Tokenizer.prototype.isEnd = function () {
  75784. return this._pos >= this._maxPos;
  75785. };
  75786. return Tokenizer;
  75787. }());
  75788. /**
  75789. * Values
  75790. */
  75791. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  75792. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  75793. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  75794. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  75795. /**
  75796. * Parse
  75797. */
  75798. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  75799. for (var buf in parsedBuffers) {
  75800. var parsedBuffer = parsedBuffers[buf];
  75801. gltfRuntime.buffers[buf] = parsedBuffer;
  75802. gltfRuntime.buffersCount++;
  75803. }
  75804. };
  75805. var parseShaders = function (parsedShaders, gltfRuntime) {
  75806. for (var sha in parsedShaders) {
  75807. var parsedShader = parsedShaders[sha];
  75808. gltfRuntime.shaders[sha] = parsedShader;
  75809. gltfRuntime.shaderscount++;
  75810. }
  75811. };
  75812. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  75813. for (var object in parsedObjects) {
  75814. var parsedObject = parsedObjects[object];
  75815. gltfRuntime[runtimeProperty][object] = parsedObject;
  75816. }
  75817. };
  75818. /**
  75819. * Utils
  75820. */
  75821. var normalizeUVs = function (buffer) {
  75822. if (!buffer) {
  75823. return;
  75824. }
  75825. for (var i = 0; i < buffer.length / 2; i++) {
  75826. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  75827. }
  75828. };
  75829. var getAttribute = function (attributeParameter) {
  75830. if (attributeParameter.semantic === "NORMAL") {
  75831. return "normal";
  75832. }
  75833. else if (attributeParameter.semantic === "POSITION") {
  75834. return "position";
  75835. }
  75836. else if (attributeParameter.semantic === "JOINT") {
  75837. return "matricesIndices";
  75838. }
  75839. else if (attributeParameter.semantic === "WEIGHT") {
  75840. return "matricesWeights";
  75841. }
  75842. else if (attributeParameter.semantic === "COLOR") {
  75843. return "color";
  75844. }
  75845. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  75846. var channel = Number(attributeParameter.semantic.split("_")[1]);
  75847. return "uv" + (channel === 0 ? "" : channel + 1);
  75848. }
  75849. return null;
  75850. };
  75851. /**
  75852. * Loads and creates animations
  75853. */
  75854. var loadAnimations = function (gltfRuntime) {
  75855. for (var anim in gltfRuntime.animations) {
  75856. var animation = gltfRuntime.animations[anim];
  75857. if (!animation.channels || !animation.samplers) {
  75858. continue;
  75859. }
  75860. var lastAnimation = null;
  75861. for (var i = 0; i < animation.channels.length; i++) {
  75862. // Get parameters and load buffers
  75863. var channel = animation.channels[i];
  75864. var sampler = animation.samplers[channel.sampler];
  75865. if (!sampler) {
  75866. continue;
  75867. }
  75868. var inputData = null;
  75869. var outputData = null;
  75870. if (animation.parameters) {
  75871. inputData = animation.parameters[sampler.input];
  75872. outputData = animation.parameters[sampler.output];
  75873. }
  75874. else {
  75875. inputData = sampler.input;
  75876. outputData = sampler.output;
  75877. }
  75878. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  75879. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  75880. var targetID = channel.target.id;
  75881. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  75882. if (targetNode === null) {
  75883. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  75884. }
  75885. if (targetNode === null) {
  75886. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  75887. continue;
  75888. }
  75889. var isBone = targetNode instanceof BABYLON.Bone;
  75890. // Get target path (position, rotation or scaling)
  75891. var targetPath = channel.target.path;
  75892. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  75893. if (targetPathIndex !== -1) {
  75894. targetPath = babylonAnimationPaths[targetPathIndex];
  75895. }
  75896. // Determine animation type
  75897. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  75898. if (!isBone) {
  75899. if (targetPath === "rotationQuaternion") {
  75900. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  75901. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  75902. }
  75903. else {
  75904. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  75905. }
  75906. }
  75907. // Create animation and key frames
  75908. var babylonAnimation = null;
  75909. var keys = [];
  75910. var arrayOffset = 0;
  75911. var modifyKey = false;
  75912. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  75913. babylonAnimation = lastAnimation;
  75914. modifyKey = true;
  75915. }
  75916. if (!modifyKey) {
  75917. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75918. }
  75919. // For each frame
  75920. for (var j = 0; j < bufferInput.length; j++) {
  75921. var value = null;
  75922. if (targetPath === "rotationQuaternion") {
  75923. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  75924. arrayOffset += 4;
  75925. }
  75926. else {
  75927. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  75928. arrayOffset += 3;
  75929. }
  75930. if (isBone) {
  75931. var bone = targetNode;
  75932. var translation = BABYLON.Vector3.Zero();
  75933. var rotationQuaternion = new BABYLON.Quaternion();
  75934. var scaling = BABYLON.Vector3.Zero();
  75935. // Warning on decompose
  75936. var mat = bone.getBaseMatrix();
  75937. if (modifyKey && lastAnimation) {
  75938. mat = lastAnimation.getKeys()[j].value;
  75939. }
  75940. mat.decompose(scaling, rotationQuaternion, translation);
  75941. if (targetPath === "position") {
  75942. translation = value;
  75943. }
  75944. else if (targetPath === "rotationQuaternion") {
  75945. rotationQuaternion = value;
  75946. }
  75947. else {
  75948. scaling = value;
  75949. }
  75950. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  75951. }
  75952. if (!modifyKey) {
  75953. keys.push({
  75954. frame: bufferInput[j],
  75955. value: value
  75956. });
  75957. }
  75958. else if (lastAnimation) {
  75959. lastAnimation.getKeys()[j].value = value;
  75960. }
  75961. }
  75962. // Finish
  75963. if (!modifyKey && babylonAnimation) {
  75964. babylonAnimation.setKeys(keys);
  75965. targetNode.animations.push(babylonAnimation);
  75966. }
  75967. lastAnimation = babylonAnimation;
  75968. gltfRuntime.scene.stopAnimation(targetNode);
  75969. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  75970. }
  75971. }
  75972. };
  75973. /**
  75974. * Returns the bones transformation matrix
  75975. */
  75976. var configureBoneTransformation = function (node) {
  75977. var mat = null;
  75978. if (node.translation || node.rotation || node.scale) {
  75979. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  75980. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  75981. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  75982. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  75983. }
  75984. else {
  75985. mat = BABYLON.Matrix.FromArray(node.matrix);
  75986. }
  75987. return mat;
  75988. };
  75989. /**
  75990. * Returns the parent bone
  75991. */
  75992. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  75993. // Try to find
  75994. for (var i = 0; i < newSkeleton.bones.length; i++) {
  75995. if (newSkeleton.bones[i].name === jointName) {
  75996. return newSkeleton.bones[i];
  75997. }
  75998. }
  75999. // Not found, search in gltf nodes
  76000. var nodes = gltfRuntime.nodes;
  76001. for (var nde in nodes) {
  76002. var node = nodes[nde];
  76003. if (!node.jointName) {
  76004. continue;
  76005. }
  76006. var children = node.children;
  76007. for (var i = 0; i < children.length; i++) {
  76008. var child = gltfRuntime.nodes[children[i]];
  76009. if (!child.jointName) {
  76010. continue;
  76011. }
  76012. if (child.jointName === jointName) {
  76013. var mat = configureBoneTransformation(node);
  76014. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  76015. bone.id = nde;
  76016. return bone;
  76017. }
  76018. }
  76019. }
  76020. return null;
  76021. };
  76022. /**
  76023. * Returns the appropriate root node
  76024. */
  76025. var getNodeToRoot = function (nodesToRoot, id) {
  76026. for (var i = 0; i < nodesToRoot.length; i++) {
  76027. var nodeToRoot = nodesToRoot[i];
  76028. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  76029. var child = nodeToRoot.node.children[j];
  76030. if (child === id) {
  76031. return nodeToRoot.bone;
  76032. }
  76033. }
  76034. }
  76035. return null;
  76036. };
  76037. /**
  76038. * Returns the node with the joint name
  76039. */
  76040. var getJointNode = function (gltfRuntime, jointName) {
  76041. var nodes = gltfRuntime.nodes;
  76042. var node = nodes[jointName];
  76043. if (node) {
  76044. return {
  76045. node: node,
  76046. id: jointName
  76047. };
  76048. }
  76049. for (var nde in nodes) {
  76050. node = nodes[nde];
  76051. if (node.jointName === jointName) {
  76052. return {
  76053. node: node,
  76054. id: nde
  76055. };
  76056. }
  76057. }
  76058. return null;
  76059. };
  76060. /**
  76061. * Checks if a nodes is in joints
  76062. */
  76063. var nodeIsInJoints = function (skins, id) {
  76064. for (var i = 0; i < skins.jointNames.length; i++) {
  76065. if (skins.jointNames[i] === id) {
  76066. return true;
  76067. }
  76068. }
  76069. return false;
  76070. };
  76071. /**
  76072. * Fills the nodes to root for bones and builds hierarchy
  76073. */
  76074. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  76075. // Creates nodes for root
  76076. for (var nde in gltfRuntime.nodes) {
  76077. var node = gltfRuntime.nodes[nde];
  76078. var id = nde;
  76079. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  76080. continue;
  76081. }
  76082. // Create node to root bone
  76083. var mat = configureBoneTransformation(node);
  76084. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  76085. bone.id = id;
  76086. nodesToRoot.push({ bone: bone, node: node, id: id });
  76087. }
  76088. // Parenting
  76089. for (var i = 0; i < nodesToRoot.length; i++) {
  76090. var nodeToRoot = nodesToRoot[i];
  76091. var children = nodeToRoot.node.children;
  76092. for (var j = 0; j < children.length; j++) {
  76093. var child = null;
  76094. for (var k = 0; k < nodesToRoot.length; k++) {
  76095. if (nodesToRoot[k].id === children[j]) {
  76096. child = nodesToRoot[k];
  76097. break;
  76098. }
  76099. }
  76100. if (child) {
  76101. child.bone._parent = nodeToRoot.bone;
  76102. nodeToRoot.bone.children.push(child.bone);
  76103. }
  76104. }
  76105. }
  76106. };
  76107. /**
  76108. * Imports a skeleton
  76109. */
  76110. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  76111. if (!newSkeleton) {
  76112. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  76113. }
  76114. if (!skins.babylonSkeleton) {
  76115. return newSkeleton;
  76116. }
  76117. // Find the root bones
  76118. var nodesToRoot = [];
  76119. var nodesToRootToAdd = [];
  76120. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  76121. newSkeleton.bones = [];
  76122. // Joints
  76123. for (var i = 0; i < skins.jointNames.length; i++) {
  76124. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76125. if (!jointNode) {
  76126. continue;
  76127. }
  76128. var node = jointNode.node;
  76129. if (!node) {
  76130. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  76131. continue;
  76132. }
  76133. var id = jointNode.id;
  76134. // Optimize, if the bone already exists...
  76135. var existingBone = gltfRuntime.scene.getBoneByID(id);
  76136. if (existingBone) {
  76137. newSkeleton.bones.push(existingBone);
  76138. continue;
  76139. }
  76140. // Search for parent bone
  76141. var foundBone = false;
  76142. var parentBone = null;
  76143. for (var j = 0; j < i; j++) {
  76144. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  76145. if (!jointNode_1) {
  76146. continue;
  76147. }
  76148. var joint = jointNode_1.node;
  76149. if (!joint) {
  76150. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  76151. continue;
  76152. }
  76153. var children = joint.children;
  76154. if (!children) {
  76155. continue;
  76156. }
  76157. foundBone = false;
  76158. for (var k = 0; k < children.length; k++) {
  76159. if (children[k] === id) {
  76160. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  76161. foundBone = true;
  76162. break;
  76163. }
  76164. }
  76165. if (foundBone) {
  76166. break;
  76167. }
  76168. }
  76169. // Create bone
  76170. var mat = configureBoneTransformation(node);
  76171. if (!parentBone && nodesToRoot.length > 0) {
  76172. parentBone = getNodeToRoot(nodesToRoot, id);
  76173. if (parentBone) {
  76174. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  76175. nodesToRootToAdd.push(parentBone);
  76176. }
  76177. }
  76178. }
  76179. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  76180. bone.id = id;
  76181. }
  76182. // Polish
  76183. var bones = newSkeleton.bones;
  76184. newSkeleton.bones = [];
  76185. for (var i = 0; i < skins.jointNames.length; i++) {
  76186. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  76187. if (!jointNode) {
  76188. continue;
  76189. }
  76190. for (var j = 0; j < bones.length; j++) {
  76191. if (bones[j].id === jointNode.id) {
  76192. newSkeleton.bones.push(bones[j]);
  76193. break;
  76194. }
  76195. }
  76196. }
  76197. newSkeleton.prepare();
  76198. // Finish
  76199. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  76200. newSkeleton.bones.push(nodesToRootToAdd[i]);
  76201. }
  76202. return newSkeleton;
  76203. };
  76204. /**
  76205. * Imports a mesh and its geometries
  76206. */
  76207. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  76208. if (!newMesh) {
  76209. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76210. newMesh.id = id;
  76211. }
  76212. if (!node.babylonNode) {
  76213. return newMesh;
  76214. }
  76215. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  76216. if (!newMesh.material) {
  76217. newMesh.material = multiMat;
  76218. }
  76219. var vertexData = new BABYLON.VertexData();
  76220. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  76221. var verticesStarts = new Array();
  76222. var verticesCounts = new Array();
  76223. var indexStarts = new Array();
  76224. var indexCounts = new Array();
  76225. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76226. var meshID = meshes[meshIndex];
  76227. var mesh = gltfRuntime.meshes[meshID];
  76228. if (!mesh) {
  76229. continue;
  76230. }
  76231. // Positions, normals and UVs
  76232. for (var i = 0; i < mesh.primitives.length; i++) {
  76233. // Temporary vertex data
  76234. var tempVertexData = new BABYLON.VertexData();
  76235. var primitive = mesh.primitives[i];
  76236. if (primitive.mode !== 4) {
  76237. // continue;
  76238. }
  76239. var attributes = primitive.attributes;
  76240. var accessor = null;
  76241. var buffer = null;
  76242. // Set positions, normal and uvs
  76243. for (var semantic in attributes) {
  76244. // Link accessor and buffer view
  76245. accessor = gltfRuntime.accessors[attributes[semantic]];
  76246. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76247. if (semantic === "NORMAL") {
  76248. tempVertexData.normals = new Float32Array(buffer.length);
  76249. tempVertexData.normals.set(buffer);
  76250. }
  76251. else if (semantic === "POSITION") {
  76252. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  76253. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  76254. for (var j = 0; j < buffer.length; j += 4) {
  76255. tempVertexData.positions[j] = buffer[j];
  76256. tempVertexData.positions[j + 1] = buffer[j + 1];
  76257. tempVertexData.positions[j + 2] = buffer[j + 2];
  76258. }
  76259. }
  76260. else {
  76261. tempVertexData.positions = new Float32Array(buffer.length);
  76262. tempVertexData.positions.set(buffer);
  76263. }
  76264. verticesCounts.push(tempVertexData.positions.length);
  76265. }
  76266. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  76267. var channel = Number(semantic.split("_")[1]);
  76268. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  76269. var uvs = new Float32Array(buffer.length);
  76270. uvs.set(buffer);
  76271. normalizeUVs(uvs);
  76272. tempVertexData.set(uvs, uvKind);
  76273. }
  76274. else if (semantic === "JOINT") {
  76275. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  76276. tempVertexData.matricesIndices.set(buffer);
  76277. }
  76278. else if (semantic === "WEIGHT") {
  76279. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  76280. tempVertexData.matricesWeights.set(buffer);
  76281. }
  76282. else if (semantic === "COLOR") {
  76283. tempVertexData.colors = new Float32Array(buffer.length);
  76284. tempVertexData.colors.set(buffer);
  76285. }
  76286. }
  76287. // Indices
  76288. accessor = gltfRuntime.accessors[primitive.indices];
  76289. if (accessor) {
  76290. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  76291. tempVertexData.indices = new Int32Array(buffer.length);
  76292. tempVertexData.indices.set(buffer);
  76293. indexCounts.push(tempVertexData.indices.length);
  76294. }
  76295. else {
  76296. // Set indices on the fly
  76297. var indices = [];
  76298. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  76299. indices.push(j);
  76300. }
  76301. tempVertexData.indices = new Int32Array(indices);
  76302. indexCounts.push(tempVertexData.indices.length);
  76303. }
  76304. vertexData.merge(tempVertexData);
  76305. // Sub material
  76306. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  76307. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  76308. // Update vertices start and index start
  76309. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  76310. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  76311. }
  76312. }
  76313. // Apply geometry
  76314. geometry.setAllVerticesData(vertexData, false);
  76315. newMesh.computeWorldMatrix(true);
  76316. // Apply submeshes
  76317. newMesh.subMeshes = [];
  76318. var index = 0;
  76319. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  76320. var meshID = meshes[meshIndex];
  76321. var mesh = gltfRuntime.meshes[meshID];
  76322. if (!mesh) {
  76323. continue;
  76324. }
  76325. for (var i = 0; i < mesh.primitives.length; i++) {
  76326. if (mesh.primitives[i].mode !== 4) {
  76327. //continue;
  76328. }
  76329. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  76330. index++;
  76331. }
  76332. }
  76333. // Finish
  76334. return newMesh;
  76335. };
  76336. /**
  76337. * Configure node transformation from position, rotation and scaling
  76338. */
  76339. var configureNode = function (newNode, position, rotation, scaling) {
  76340. if (newNode.position) {
  76341. newNode.position = position;
  76342. }
  76343. if (newNode.rotationQuaternion || newNode.rotation) {
  76344. newNode.rotationQuaternion = rotation;
  76345. }
  76346. if (newNode.scaling) {
  76347. newNode.scaling = scaling;
  76348. }
  76349. };
  76350. /**
  76351. * Configures node from transformation matrix
  76352. */
  76353. var configureNodeFromMatrix = function (newNode, node, parent) {
  76354. if (node.matrix) {
  76355. var position = new BABYLON.Vector3(0, 0, 0);
  76356. var rotation = new BABYLON.Quaternion();
  76357. var scaling = new BABYLON.Vector3(0, 0, 0);
  76358. var mat = BABYLON.Matrix.FromArray(node.matrix);
  76359. mat.decompose(scaling, rotation, position);
  76360. configureNode(newNode, position, rotation, scaling);
  76361. }
  76362. else if (node.translation && node.rotation && node.scale) {
  76363. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  76364. }
  76365. newNode.computeWorldMatrix(true);
  76366. };
  76367. /**
  76368. * Imports a node
  76369. */
  76370. var importNode = function (gltfRuntime, node, id, parent) {
  76371. var lastNode = null;
  76372. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  76373. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  76374. return null;
  76375. }
  76376. }
  76377. // Meshes
  76378. if (node.skin) {
  76379. if (node.meshes) {
  76380. var skin = gltfRuntime.skins[node.skin];
  76381. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  76382. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  76383. if (newMesh.skeleton === null && skin.babylonSkeleton) {
  76384. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  76385. if (!skin.babylonSkeleton) {
  76386. skin.babylonSkeleton = newMesh.skeleton;
  76387. }
  76388. }
  76389. lastNode = newMesh;
  76390. }
  76391. }
  76392. else if (node.meshes) {
  76393. /**
  76394. * Improve meshes property
  76395. */
  76396. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  76397. lastNode = newMesh;
  76398. }
  76399. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76400. var light = gltfRuntime.lights[node.light];
  76401. if (light) {
  76402. if (light.type === "ambient") {
  76403. var ambienLight = light[light.type];
  76404. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76405. hemiLight.name = node.name || "";
  76406. if (ambienLight.color) {
  76407. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  76408. }
  76409. lastNode = hemiLight;
  76410. }
  76411. else if (light.type === "directional") {
  76412. var directionalLight = light[light.type];
  76413. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76414. dirLight.name = node.name || "";
  76415. if (directionalLight.color) {
  76416. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  76417. }
  76418. lastNode = dirLight;
  76419. }
  76420. else if (light.type === "point") {
  76421. var pointLight = light[light.type];
  76422. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76423. ptLight.name = node.name || "";
  76424. if (pointLight.color) {
  76425. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  76426. }
  76427. lastNode = ptLight;
  76428. }
  76429. else if (light.type === "spot") {
  76430. var spotLight = light[light.type];
  76431. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  76432. spLight.name = node.name || "";
  76433. if (spotLight.color) {
  76434. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  76435. }
  76436. if (spotLight.fallOfAngle) {
  76437. spLight.angle = spotLight.fallOfAngle;
  76438. }
  76439. if (spotLight.fallOffExponent) {
  76440. spLight.exponent = spotLight.fallOffExponent;
  76441. }
  76442. lastNode = spLight;
  76443. }
  76444. }
  76445. }
  76446. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  76447. var camera = gltfRuntime.cameras[node.camera];
  76448. if (camera) {
  76449. if (camera.type === "orthographic") {
  76450. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76451. orthoCamera.name = node.name || "";
  76452. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  76453. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76454. lastNode = orthoCamera;
  76455. }
  76456. else if (camera.type === "perspective") {
  76457. var perspectiveCamera = camera[camera.type];
  76458. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  76459. persCamera.name = node.name || "";
  76460. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  76461. if (!perspectiveCamera.aspectRatio) {
  76462. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  76463. }
  76464. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  76465. persCamera.maxZ = perspectiveCamera.zfar;
  76466. persCamera.minZ = perspectiveCamera.znear;
  76467. }
  76468. lastNode = persCamera;
  76469. }
  76470. }
  76471. }
  76472. // Empty node
  76473. if (!node.jointName) {
  76474. if (node.babylonNode) {
  76475. return node.babylonNode;
  76476. }
  76477. else if (lastNode === null) {
  76478. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  76479. node.babylonNode = dummy;
  76480. lastNode = dummy;
  76481. }
  76482. }
  76483. if (lastNode !== null) {
  76484. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  76485. configureNodeFromMatrix(lastNode, node, parent);
  76486. }
  76487. else {
  76488. var translation = node.translation || [0, 0, 0];
  76489. var rotation = node.rotation || [0, 0, 0, 1];
  76490. var scale = node.scale || [1, 1, 1];
  76491. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  76492. }
  76493. lastNode.updateCache(true);
  76494. node.babylonNode = lastNode;
  76495. }
  76496. return lastNode;
  76497. };
  76498. /**
  76499. * Traverses nodes and creates them
  76500. */
  76501. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  76502. if (meshIncluded === void 0) { meshIncluded = false; }
  76503. var node = gltfRuntime.nodes[id];
  76504. var newNode = null;
  76505. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  76506. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  76507. meshIncluded = true;
  76508. }
  76509. else {
  76510. meshIncluded = false;
  76511. }
  76512. }
  76513. else {
  76514. meshIncluded = true;
  76515. }
  76516. if (!node.jointName && meshIncluded) {
  76517. newNode = importNode(gltfRuntime, node, id, parent);
  76518. if (newNode !== null) {
  76519. newNode.id = id;
  76520. newNode.parent = parent;
  76521. }
  76522. }
  76523. if (node.children) {
  76524. for (var i = 0; i < node.children.length; i++) {
  76525. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  76526. }
  76527. }
  76528. };
  76529. /**
  76530. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  76531. */
  76532. var postLoad = function (gltfRuntime) {
  76533. // Nodes
  76534. var currentScene = gltfRuntime.currentScene;
  76535. if (currentScene) {
  76536. for (var i = 0; i < currentScene.nodes.length; i++) {
  76537. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76538. }
  76539. }
  76540. else {
  76541. for (var thing in gltfRuntime.scenes) {
  76542. currentScene = gltfRuntime.scenes[thing];
  76543. for (var i = 0; i < currentScene.nodes.length; i++) {
  76544. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  76545. }
  76546. }
  76547. }
  76548. // Set animations
  76549. loadAnimations(gltfRuntime);
  76550. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  76551. var skeleton = gltfRuntime.scene.skeletons[i];
  76552. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  76553. }
  76554. };
  76555. /**
  76556. * onBind shaderrs callback to set uniforms and matrices
  76557. */
  76558. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  76559. var materialValues = material.values || technique.parameters;
  76560. for (var unif in unTreatedUniforms) {
  76561. var uniform = unTreatedUniforms[unif];
  76562. var type = uniform.type;
  76563. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  76564. if (uniform.semantic && !uniform.source && !uniform.node) {
  76565. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  76566. }
  76567. else if (uniform.semantic && (uniform.source || uniform.node)) {
  76568. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  76569. if (source === null) {
  76570. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  76571. }
  76572. if (source === null) {
  76573. continue;
  76574. }
  76575. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  76576. }
  76577. }
  76578. else {
  76579. var value = materialValues[technique.uniforms[unif]];
  76580. if (!value) {
  76581. continue;
  76582. }
  76583. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76584. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  76585. if (texture === null || texture === undefined) {
  76586. continue;
  76587. }
  76588. shaderMaterial.getEffect().setTexture(unif, texture);
  76589. }
  76590. else {
  76591. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  76592. }
  76593. }
  76594. }
  76595. onSuccess(shaderMaterial);
  76596. };
  76597. /**
  76598. * Prepare uniforms to send the only one time
  76599. * Loads the appropriate textures
  76600. */
  76601. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  76602. var materialValues = material.values || technique.parameters;
  76603. var techniqueUniforms = technique.uniforms;
  76604. /**
  76605. * Prepare values here (not matrices)
  76606. */
  76607. for (var unif in unTreatedUniforms) {
  76608. var uniform = unTreatedUniforms[unif];
  76609. var type = uniform.type;
  76610. var value = materialValues[techniqueUniforms[unif]];
  76611. if (value === undefined) {
  76612. // In case the value is the same for all materials
  76613. value = uniform.value;
  76614. }
  76615. if (!value) {
  76616. continue;
  76617. }
  76618. var onLoadTexture = function (uniformName) {
  76619. return function (texture) {
  76620. if (uniform.value && uniformName) {
  76621. // Static uniform
  76622. shaderMaterial.setTexture(uniformName, texture);
  76623. delete unTreatedUniforms[uniformName];
  76624. }
  76625. };
  76626. };
  76627. // Texture (sampler2D)
  76628. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  76629. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  76630. }
  76631. else {
  76632. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  76633. // Static uniform
  76634. delete unTreatedUniforms[unif];
  76635. }
  76636. }
  76637. }
  76638. };
  76639. /**
  76640. * Shader compilation failed
  76641. */
  76642. var onShaderCompileError = function (program, shaderMaterial, onError) {
  76643. return function (effect, error) {
  76644. shaderMaterial.dispose(true);
  76645. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  76646. };
  76647. };
  76648. /**
  76649. * Shader compilation success
  76650. */
  76651. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  76652. return function (_) {
  76653. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  76654. shaderMaterial.onBind = function (mesh) {
  76655. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  76656. };
  76657. };
  76658. };
  76659. /**
  76660. * Returns the appropriate uniform if already handled by babylon
  76661. */
  76662. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  76663. for (var unif in technique.uniforms) {
  76664. var uniform = technique.uniforms[unif];
  76665. var uniformParameter = technique.parameters[uniform];
  76666. if (tokenizer.currentIdentifier === unif) {
  76667. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  76668. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76669. if (transformIndex !== -1) {
  76670. delete unTreatedUniforms[unif];
  76671. return babylonTransforms[transformIndex];
  76672. }
  76673. }
  76674. }
  76675. }
  76676. return tokenizer.currentIdentifier;
  76677. };
  76678. /**
  76679. * All shaders loaded. Create materials one by one
  76680. */
  76681. var importMaterials = function (gltfRuntime) {
  76682. // Create materials
  76683. for (var mat in gltfRuntime.materials) {
  76684. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  76685. }
  76686. };
  76687. /**
  76688. * Implementation of the base glTF spec
  76689. */
  76690. var GLTFLoaderBase = /** @class */ (function () {
  76691. function GLTFLoaderBase() {
  76692. }
  76693. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  76694. var gltfRuntime = {
  76695. extensions: {},
  76696. accessors: {},
  76697. buffers: {},
  76698. bufferViews: {},
  76699. meshes: {},
  76700. lights: {},
  76701. cameras: {},
  76702. nodes: {},
  76703. images: {},
  76704. textures: {},
  76705. shaders: {},
  76706. programs: {},
  76707. samplers: {},
  76708. techniques: {},
  76709. materials: {},
  76710. animations: {},
  76711. skins: {},
  76712. extensionsUsed: [],
  76713. scenes: {},
  76714. buffersCount: 0,
  76715. shaderscount: 0,
  76716. scene: scene,
  76717. rootUrl: rootUrl,
  76718. loadedBufferCount: 0,
  76719. loadedBufferViews: {},
  76720. loadedShaderCount: 0,
  76721. importOnlyMeshes: false,
  76722. dummyNodes: []
  76723. };
  76724. // Parse
  76725. if (parsedData.extensions) {
  76726. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  76727. }
  76728. if (parsedData.extensionsUsed) {
  76729. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  76730. }
  76731. if (parsedData.buffers) {
  76732. parseBuffers(parsedData.buffers, gltfRuntime);
  76733. }
  76734. if (parsedData.bufferViews) {
  76735. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  76736. }
  76737. if (parsedData.accessors) {
  76738. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  76739. }
  76740. if (parsedData.meshes) {
  76741. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  76742. }
  76743. if (parsedData.lights) {
  76744. parseObject(parsedData.lights, "lights", gltfRuntime);
  76745. }
  76746. if (parsedData.cameras) {
  76747. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  76748. }
  76749. if (parsedData.nodes) {
  76750. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  76751. }
  76752. if (parsedData.images) {
  76753. parseObject(parsedData.images, "images", gltfRuntime);
  76754. }
  76755. if (parsedData.textures) {
  76756. parseObject(parsedData.textures, "textures", gltfRuntime);
  76757. }
  76758. if (parsedData.shaders) {
  76759. parseShaders(parsedData.shaders, gltfRuntime);
  76760. }
  76761. if (parsedData.programs) {
  76762. parseObject(parsedData.programs, "programs", gltfRuntime);
  76763. }
  76764. if (parsedData.samplers) {
  76765. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  76766. }
  76767. if (parsedData.techniques) {
  76768. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  76769. }
  76770. if (parsedData.materials) {
  76771. parseObject(parsedData.materials, "materials", gltfRuntime);
  76772. }
  76773. if (parsedData.animations) {
  76774. parseObject(parsedData.animations, "animations", gltfRuntime);
  76775. }
  76776. if (parsedData.skins) {
  76777. parseObject(parsedData.skins, "skins", gltfRuntime);
  76778. }
  76779. if (parsedData.scenes) {
  76780. gltfRuntime.scenes = parsedData.scenes;
  76781. }
  76782. if (parsedData.scene && parsedData.scenes) {
  76783. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  76784. }
  76785. return gltfRuntime;
  76786. };
  76787. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  76788. var buffer = gltfRuntime.buffers[id];
  76789. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  76790. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  76791. }
  76792. else {
  76793. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  76794. if (request) {
  76795. onError(request.status + " " + request.statusText);
  76796. }
  76797. });
  76798. }
  76799. };
  76800. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  76801. var texture = gltfRuntime.textures[id];
  76802. if (!texture || !texture.source) {
  76803. onError("");
  76804. return;
  76805. }
  76806. if (texture.babylonTexture) {
  76807. onSuccess(null);
  76808. return;
  76809. }
  76810. var source = gltfRuntime.images[texture.source];
  76811. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  76812. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  76813. }
  76814. else {
  76815. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  76816. if (request) {
  76817. onError(request.status + " " + request.statusText);
  76818. }
  76819. });
  76820. }
  76821. };
  76822. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  76823. var texture = gltfRuntime.textures[id];
  76824. if (texture.babylonTexture) {
  76825. onSuccess(texture.babylonTexture);
  76826. return;
  76827. }
  76828. var sampler = gltfRuntime.samplers[texture.sampler];
  76829. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  76830. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  76831. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  76832. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  76833. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  76834. var blob = new Blob([buffer]);
  76835. var blobURL = URL.createObjectURL(blob);
  76836. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  76837. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  76838. if (sampler.wrapS !== undefined) {
  76839. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  76840. }
  76841. if (sampler.wrapT !== undefined) {
  76842. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  76843. }
  76844. newTexture.name = id;
  76845. texture.babylonTexture = newTexture;
  76846. onSuccess(newTexture);
  76847. };
  76848. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  76849. var shader = gltfRuntime.shaders[id];
  76850. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  76851. var shaderString = atob(shader.uri.split(",")[1]);
  76852. onSuccess(shaderString);
  76853. }
  76854. else {
  76855. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  76856. if (request) {
  76857. onError(request.status + " " + request.statusText);
  76858. }
  76859. });
  76860. }
  76861. };
  76862. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  76863. var material = gltfRuntime.materials[id];
  76864. if (!material.technique) {
  76865. if (onError) {
  76866. onError("No technique found.");
  76867. }
  76868. return;
  76869. }
  76870. var technique = gltfRuntime.techniques[material.technique];
  76871. if (!technique) {
  76872. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  76873. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  76874. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76875. onSuccess(defaultMaterial);
  76876. return;
  76877. }
  76878. var program = gltfRuntime.programs[technique.program];
  76879. var states = technique.states;
  76880. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  76881. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  76882. var newVertexShader = "";
  76883. var newPixelShader = "";
  76884. var vertexTokenizer = new Tokenizer(vertexShader);
  76885. var pixelTokenizer = new Tokenizer(pixelShader);
  76886. var unTreatedUniforms = {};
  76887. var uniforms = [];
  76888. var attributes = [];
  76889. var samplers = [];
  76890. // Fill uniform, sampler2D and attributes
  76891. for (var unif in technique.uniforms) {
  76892. var uniform = technique.uniforms[unif];
  76893. var uniformParameter = technique.parameters[uniform];
  76894. unTreatedUniforms[unif] = uniformParameter;
  76895. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  76896. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  76897. if (transformIndex !== -1) {
  76898. uniforms.push(babylonTransforms[transformIndex]);
  76899. delete unTreatedUniforms[unif];
  76900. }
  76901. else {
  76902. uniforms.push(unif);
  76903. }
  76904. }
  76905. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  76906. samplers.push(unif);
  76907. }
  76908. else {
  76909. uniforms.push(unif);
  76910. }
  76911. }
  76912. for (var attr in technique.attributes) {
  76913. var attribute = technique.attributes[attr];
  76914. var attributeParameter = technique.parameters[attribute];
  76915. if (attributeParameter.semantic) {
  76916. attributes.push(getAttribute(attributeParameter));
  76917. }
  76918. }
  76919. // Configure vertex shader
  76920. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  76921. var tokenType = vertexTokenizer.currentToken;
  76922. if (tokenType !== ETokenType.IDENTIFIER) {
  76923. newVertexShader += vertexTokenizer.currentString;
  76924. continue;
  76925. }
  76926. var foundAttribute = false;
  76927. for (var attr in technique.attributes) {
  76928. var attribute = technique.attributes[attr];
  76929. var attributeParameter = technique.parameters[attribute];
  76930. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  76931. newVertexShader += getAttribute(attributeParameter);
  76932. foundAttribute = true;
  76933. break;
  76934. }
  76935. }
  76936. if (foundAttribute) {
  76937. continue;
  76938. }
  76939. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  76940. }
  76941. // Configure pixel shader
  76942. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  76943. var tokenType = pixelTokenizer.currentToken;
  76944. if (tokenType !== ETokenType.IDENTIFIER) {
  76945. newPixelShader += pixelTokenizer.currentString;
  76946. continue;
  76947. }
  76948. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  76949. }
  76950. // Create shader material
  76951. var shaderPath = {
  76952. vertex: program.vertexShader + id,
  76953. fragment: program.fragmentShader + id
  76954. };
  76955. var options = {
  76956. attributes: attributes,
  76957. uniforms: uniforms,
  76958. samplers: samplers,
  76959. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  76960. };
  76961. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  76962. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  76963. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  76964. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  76965. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  76966. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76967. if (states && states.functions) {
  76968. var functions = states.functions;
  76969. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  76970. shaderMaterial.backFaceCulling = false;
  76971. }
  76972. var blendFunc = functions.blendFuncSeparate;
  76973. if (blendFunc) {
  76974. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76975. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  76976. }
  76977. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76978. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76979. }
  76980. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76981. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  76982. }
  76983. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76984. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  76985. }
  76986. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76987. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  76988. }
  76989. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  76990. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  76991. }
  76992. }
  76993. }
  76994. };
  76995. return GLTFLoaderBase;
  76996. }());
  76997. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  76998. /**
  76999. * glTF V1 Loader
  77000. */
  77001. var GLTFLoader = /** @class */ (function () {
  77002. function GLTFLoader() {
  77003. }
  77004. GLTFLoader.RegisterExtension = function (extension) {
  77005. if (GLTFLoader.Extensions[extension.name]) {
  77006. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  77007. return;
  77008. }
  77009. GLTFLoader.Extensions[extension.name] = extension;
  77010. };
  77011. GLTFLoader.prototype.dispose = function () {
  77012. // do nothing
  77013. };
  77014. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77015. var _this = this;
  77016. scene.useRightHandedSystem = true;
  77017. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77018. gltfRuntime.importOnlyMeshes = true;
  77019. if (meshesNames === "") {
  77020. gltfRuntime.importMeshesNames = [];
  77021. }
  77022. else if (typeof meshesNames === "string") {
  77023. gltfRuntime.importMeshesNames = [meshesNames];
  77024. }
  77025. else if (meshesNames && !(meshesNames instanceof Array)) {
  77026. gltfRuntime.importMeshesNames = [meshesNames];
  77027. }
  77028. else {
  77029. gltfRuntime.importMeshesNames = [];
  77030. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  77031. }
  77032. // Create nodes
  77033. _this._createNodes(gltfRuntime);
  77034. var meshes = new Array();
  77035. var skeletons = new Array();
  77036. // Fill arrays of meshes and skeletons
  77037. for (var nde in gltfRuntime.nodes) {
  77038. var node = gltfRuntime.nodes[nde];
  77039. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  77040. meshes.push(node.babylonNode);
  77041. }
  77042. }
  77043. for (var skl in gltfRuntime.skins) {
  77044. var skin = gltfRuntime.skins[skl];
  77045. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77046. skeletons.push(skin.babylonSkeleton);
  77047. }
  77048. }
  77049. // Load buffers, shaders, materials, etc.
  77050. _this._loadBuffersAsync(gltfRuntime, function () {
  77051. _this._loadShadersAsync(gltfRuntime, function () {
  77052. importMaterials(gltfRuntime);
  77053. postLoad(gltfRuntime);
  77054. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77055. onSuccess(meshes, null, skeletons);
  77056. }
  77057. });
  77058. }, onProgress);
  77059. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  77060. onSuccess(meshes, null, skeletons);
  77061. }
  77062. }, onError);
  77063. return true;
  77064. };
  77065. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77066. var _this = this;
  77067. scene.useRightHandedSystem = true;
  77068. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  77069. // Load runtime extensios
  77070. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  77071. // Create nodes
  77072. _this._createNodes(gltfRuntime);
  77073. // Load buffers, shaders, materials, etc.
  77074. _this._loadBuffersAsync(gltfRuntime, function () {
  77075. _this._loadShadersAsync(gltfRuntime, function () {
  77076. importMaterials(gltfRuntime);
  77077. postLoad(gltfRuntime);
  77078. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  77079. onSuccess();
  77080. }
  77081. });
  77082. });
  77083. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  77084. onSuccess();
  77085. }
  77086. }, onError);
  77087. }, onError);
  77088. };
  77089. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  77090. var hasShaders = false;
  77091. var processShader = function (sha, shader) {
  77092. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  77093. gltfRuntime.loadedShaderCount++;
  77094. if (shaderString) {
  77095. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  77096. }
  77097. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  77098. onload();
  77099. }
  77100. }, function () {
  77101. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  77102. });
  77103. };
  77104. for (var sha in gltfRuntime.shaders) {
  77105. hasShaders = true;
  77106. var shader = gltfRuntime.shaders[sha];
  77107. if (shader) {
  77108. processShader.bind(this, sha, shader)();
  77109. }
  77110. else {
  77111. BABYLON.Tools.Error("No shader named: " + sha);
  77112. }
  77113. }
  77114. if (!hasShaders) {
  77115. onload();
  77116. }
  77117. };
  77118. ;
  77119. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  77120. var hasBuffers = false;
  77121. var processBuffer = function (buf, buffer) {
  77122. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  77123. gltfRuntime.loadedBufferCount++;
  77124. if (bufferView) {
  77125. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  77126. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  77127. }
  77128. gltfRuntime.loadedBufferViews[buf] = bufferView;
  77129. }
  77130. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  77131. onLoad();
  77132. }
  77133. }, function () {
  77134. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  77135. });
  77136. };
  77137. for (var buf in gltfRuntime.buffers) {
  77138. hasBuffers = true;
  77139. var buffer = gltfRuntime.buffers[buf];
  77140. if (buffer) {
  77141. processBuffer.bind(this, buf, buffer)();
  77142. }
  77143. else {
  77144. BABYLON.Tools.Error("No buffer named: " + buf);
  77145. }
  77146. }
  77147. if (!hasBuffers) {
  77148. onLoad();
  77149. }
  77150. };
  77151. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  77152. var currentScene = gltfRuntime.currentScene;
  77153. if (currentScene) {
  77154. // Only one scene even if multiple scenes are defined
  77155. for (var i = 0; i < currentScene.nodes.length; i++) {
  77156. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77157. }
  77158. }
  77159. else {
  77160. // Load all scenes
  77161. for (var thing in gltfRuntime.scenes) {
  77162. currentScene = gltfRuntime.scenes[thing];
  77163. for (var i = 0; i < currentScene.nodes.length; i++) {
  77164. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  77165. }
  77166. }
  77167. }
  77168. };
  77169. GLTFLoader.Extensions = {};
  77170. return GLTFLoader;
  77171. }());
  77172. GLTF1.GLTFLoader = GLTFLoader;
  77173. ;
  77174. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  77175. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77176. })(BABYLON || (BABYLON = {}));
  77177. //# sourceMappingURL=babylon.glTFLoader.js.map
  77178. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77179. var BABYLON;
  77180. (function (BABYLON) {
  77181. var GLTF1;
  77182. (function (GLTF1) {
  77183. /**
  77184. * Utils functions for GLTF
  77185. */
  77186. var GLTFUtils = /** @class */ (function () {
  77187. function GLTFUtils() {
  77188. }
  77189. /**
  77190. * Sets the given "parameter" matrix
  77191. * @param scene: the {BABYLON.Scene} object
  77192. * @param source: the source node where to pick the matrix
  77193. * @param parameter: the GLTF technique parameter
  77194. * @param uniformName: the name of the shader's uniform
  77195. * @param shaderMaterial: the shader material
  77196. */
  77197. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  77198. var mat = null;
  77199. if (parameter.semantic === "MODEL") {
  77200. mat = source.getWorldMatrix();
  77201. }
  77202. else if (parameter.semantic === "PROJECTION") {
  77203. mat = scene.getProjectionMatrix();
  77204. }
  77205. else if (parameter.semantic === "VIEW") {
  77206. mat = scene.getViewMatrix();
  77207. }
  77208. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  77209. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  77210. }
  77211. else if (parameter.semantic === "MODELVIEW") {
  77212. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  77213. }
  77214. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  77215. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  77216. }
  77217. else if (parameter.semantic === "MODELINVERSE") {
  77218. mat = source.getWorldMatrix().invert();
  77219. }
  77220. else if (parameter.semantic === "VIEWINVERSE") {
  77221. mat = scene.getViewMatrix().invert();
  77222. }
  77223. else if (parameter.semantic === "PROJECTIONINVERSE") {
  77224. mat = scene.getProjectionMatrix().invert();
  77225. }
  77226. else if (parameter.semantic === "MODELVIEWINVERSE") {
  77227. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  77228. }
  77229. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  77230. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  77231. }
  77232. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  77233. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  77234. }
  77235. else {
  77236. debugger;
  77237. }
  77238. if (mat) {
  77239. switch (parameter.type) {
  77240. case GLTF1.EParameterType.FLOAT_MAT2:
  77241. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  77242. break;
  77243. case GLTF1.EParameterType.FLOAT_MAT3:
  77244. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  77245. break;
  77246. case GLTF1.EParameterType.FLOAT_MAT4:
  77247. shaderMaterial.setMatrix(uniformName, mat);
  77248. break;
  77249. default: break;
  77250. }
  77251. }
  77252. };
  77253. /**
  77254. * Sets the given "parameter" matrix
  77255. * @param shaderMaterial: the shader material
  77256. * @param uniform: the name of the shader's uniform
  77257. * @param value: the value of the uniform
  77258. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  77259. */
  77260. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  77261. switch (type) {
  77262. case GLTF1.EParameterType.FLOAT:
  77263. shaderMaterial.setFloat(uniform, value);
  77264. return true;
  77265. case GLTF1.EParameterType.FLOAT_VEC2:
  77266. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  77267. return true;
  77268. case GLTF1.EParameterType.FLOAT_VEC3:
  77269. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  77270. return true;
  77271. case GLTF1.EParameterType.FLOAT_VEC4:
  77272. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  77273. return true;
  77274. default: return false;
  77275. }
  77276. };
  77277. /**
  77278. * If the uri is a base64 string
  77279. * @param uri: the uri to test
  77280. */
  77281. GLTFUtils.IsBase64 = function (uri) {
  77282. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  77283. };
  77284. /**
  77285. * Decode the base64 uri
  77286. * @param uri: the uri to decode
  77287. */
  77288. GLTFUtils.DecodeBase64 = function (uri) {
  77289. var decodedString = atob(uri.split(",")[1]);
  77290. var bufferLength = decodedString.length;
  77291. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  77292. for (var i = 0; i < bufferLength; i++) {
  77293. bufferView[i] = decodedString.charCodeAt(i);
  77294. }
  77295. return bufferView.buffer;
  77296. };
  77297. /**
  77298. * Returns the wrap mode of the texture
  77299. * @param mode: the mode value
  77300. */
  77301. GLTFUtils.GetWrapMode = function (mode) {
  77302. switch (mode) {
  77303. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  77304. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  77305. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77306. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  77307. }
  77308. };
  77309. /**
  77310. * Returns the byte stride giving an accessor
  77311. * @param accessor: the GLTF accessor objet
  77312. */
  77313. GLTFUtils.GetByteStrideFromType = function (accessor) {
  77314. // Needs this function since "byteStride" isn't requiered in glTF format
  77315. var type = accessor.type;
  77316. switch (type) {
  77317. case "VEC2": return 2;
  77318. case "VEC3": return 3;
  77319. case "VEC4": return 4;
  77320. case "MAT2": return 4;
  77321. case "MAT3": return 9;
  77322. case "MAT4": return 16;
  77323. default: return 1;
  77324. }
  77325. };
  77326. /**
  77327. * Returns the texture filter mode giving a mode value
  77328. * @param mode: the filter mode value
  77329. */
  77330. GLTFUtils.GetTextureFilterMode = function (mode) {
  77331. switch (mode) {
  77332. case GLTF1.ETextureFilterType.LINEAR:
  77333. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  77334. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  77335. case GLTF1.ETextureFilterType.NEAREST:
  77336. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  77337. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  77338. }
  77339. };
  77340. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  77341. var byteOffset = bufferView.byteOffset + byteOffset;
  77342. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  77343. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  77344. throw new Error("Buffer access is out of range");
  77345. }
  77346. var buffer = loadedBufferView.buffer;
  77347. byteOffset += loadedBufferView.byteOffset;
  77348. switch (componentType) {
  77349. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  77350. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  77351. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  77352. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  77353. default: return new Float32Array(buffer, byteOffset, byteLength);
  77354. }
  77355. };
  77356. /**
  77357. * Returns a buffer from its accessor
  77358. * @param gltfRuntime: the GLTF runtime
  77359. * @param accessor: the GLTF accessor
  77360. */
  77361. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  77362. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  77363. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  77364. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  77365. };
  77366. /**
  77367. * Decodes a buffer view into a string
  77368. * @param view: the buffer view
  77369. */
  77370. GLTFUtils.DecodeBufferToText = function (view) {
  77371. var result = "";
  77372. var length = view.byteLength;
  77373. for (var i = 0; i < length; ++i) {
  77374. result += String.fromCharCode(view[i]);
  77375. }
  77376. return result;
  77377. };
  77378. /**
  77379. * Returns the default material of gltf. Related to
  77380. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  77381. * @param scene: the Babylon.js scene
  77382. */
  77383. GLTFUtils.GetDefaultMaterial = function (scene) {
  77384. if (!GLTFUtils._DefaultMaterial) {
  77385. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  77386. "precision highp float;",
  77387. "",
  77388. "uniform mat4 worldView;",
  77389. "uniform mat4 projection;",
  77390. "",
  77391. "attribute vec3 position;",
  77392. "",
  77393. "void main(void)",
  77394. "{",
  77395. " gl_Position = projection * worldView * vec4(position, 1.0);",
  77396. "}"
  77397. ].join("\n");
  77398. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  77399. "precision highp float;",
  77400. "",
  77401. "uniform vec4 u_emission;",
  77402. "",
  77403. "void main(void)",
  77404. "{",
  77405. " gl_FragColor = u_emission;",
  77406. "}"
  77407. ].join("\n");
  77408. var shaderPath = {
  77409. vertex: "GLTFDefaultMaterial",
  77410. fragment: "GLTFDefaultMaterial"
  77411. };
  77412. var options = {
  77413. attributes: ["position"],
  77414. uniforms: ["worldView", "projection", "u_emission"],
  77415. samplers: new Array(),
  77416. needAlphaBlending: false
  77417. };
  77418. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  77419. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  77420. }
  77421. return GLTFUtils._DefaultMaterial;
  77422. };
  77423. // The GLTF default material
  77424. GLTFUtils._DefaultMaterial = null;
  77425. return GLTFUtils;
  77426. }());
  77427. GLTF1.GLTFUtils = GLTFUtils;
  77428. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77429. })(BABYLON || (BABYLON = {}));
  77430. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  77431. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77432. var BABYLON;
  77433. (function (BABYLON) {
  77434. var GLTF1;
  77435. (function (GLTF1) {
  77436. var GLTFLoaderExtension = /** @class */ (function () {
  77437. function GLTFLoaderExtension(name) {
  77438. this._name = name;
  77439. }
  77440. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  77441. get: function () {
  77442. return this._name;
  77443. },
  77444. enumerable: true,
  77445. configurable: true
  77446. });
  77447. /**
  77448. * Defines an override for loading the runtime
  77449. * Return true to stop further extensions from loading the runtime
  77450. */
  77451. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77452. return false;
  77453. };
  77454. /**
  77455. * Defines an onverride for creating gltf runtime
  77456. * Return true to stop further extensions from creating the runtime
  77457. */
  77458. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77459. return false;
  77460. };
  77461. /**
  77462. * Defines an override for loading buffers
  77463. * Return true to stop further extensions from loading this buffer
  77464. */
  77465. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77466. return false;
  77467. };
  77468. /**
  77469. * Defines an override for loading texture buffers
  77470. * Return true to stop further extensions from loading this texture data
  77471. */
  77472. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77473. return false;
  77474. };
  77475. /**
  77476. * Defines an override for creating textures
  77477. * Return true to stop further extensions from loading this texture
  77478. */
  77479. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77480. return false;
  77481. };
  77482. /**
  77483. * Defines an override for loading shader strings
  77484. * Return true to stop further extensions from loading this shader data
  77485. */
  77486. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77487. return false;
  77488. };
  77489. /**
  77490. * Defines an override for loading materials
  77491. * Return true to stop further extensions from loading this material
  77492. */
  77493. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77494. return false;
  77495. };
  77496. // ---------
  77497. // Utilities
  77498. // ---------
  77499. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77500. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77501. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  77502. }, function () {
  77503. setTimeout(function () {
  77504. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77505. });
  77506. });
  77507. };
  77508. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77509. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77510. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  77511. }, function () {
  77512. setTimeout(function () {
  77513. onSuccess();
  77514. });
  77515. });
  77516. };
  77517. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  77518. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77519. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77520. }, function () {
  77521. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  77522. });
  77523. };
  77524. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  77525. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  77526. };
  77527. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77528. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77529. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77530. }, function () {
  77531. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  77532. });
  77533. };
  77534. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77535. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77536. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77537. }, function () {
  77538. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  77539. });
  77540. };
  77541. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77542. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77543. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77544. }, function () {
  77545. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  77546. });
  77547. };
  77548. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  77549. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  77550. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77551. }, function () {
  77552. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  77553. });
  77554. };
  77555. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  77556. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  77557. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  77558. if (func(loaderExtension)) {
  77559. return;
  77560. }
  77561. }
  77562. defaultFunc();
  77563. };
  77564. return GLTFLoaderExtension;
  77565. }());
  77566. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  77567. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77568. })(BABYLON || (BABYLON = {}));
  77569. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  77570. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77571. var BABYLON;
  77572. (function (BABYLON) {
  77573. var GLTF1;
  77574. (function (GLTF1) {
  77575. var BinaryExtensionBufferName = "binary_glTF";
  77576. ;
  77577. ;
  77578. var GLTFBinaryExtension = /** @class */ (function (_super) {
  77579. __extends(GLTFBinaryExtension, _super);
  77580. function GLTFBinaryExtension() {
  77581. return _super.call(this, "KHR_binary_glTF") || this;
  77582. }
  77583. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  77584. var extensionsUsed = data.json.extensionsUsed;
  77585. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  77586. return false;
  77587. }
  77588. this._bin = data.bin;
  77589. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  77590. return true;
  77591. };
  77592. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77593. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  77594. return false;
  77595. }
  77596. if (id !== BinaryExtensionBufferName) {
  77597. return false;
  77598. }
  77599. onSuccess(this._bin);
  77600. return true;
  77601. };
  77602. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  77603. var texture = gltfRuntime.textures[id];
  77604. var source = gltfRuntime.images[texture.source];
  77605. if (!source.extensions || !(this.name in source.extensions)) {
  77606. return false;
  77607. }
  77608. var sourceExt = source.extensions[this.name];
  77609. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  77610. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77611. onSuccess(buffer);
  77612. return true;
  77613. };
  77614. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  77615. var shader = gltfRuntime.shaders[id];
  77616. if (!shader.extensions || !(this.name in shader.extensions)) {
  77617. return false;
  77618. }
  77619. var binaryExtensionShader = shader.extensions[this.name];
  77620. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  77621. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  77622. setTimeout(function () {
  77623. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  77624. onSuccess(shaderString);
  77625. });
  77626. return true;
  77627. };
  77628. return GLTFBinaryExtension;
  77629. }(GLTF1.GLTFLoaderExtension));
  77630. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  77631. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  77632. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77633. })(BABYLON || (BABYLON = {}));
  77634. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  77635. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77636. var BABYLON;
  77637. (function (BABYLON) {
  77638. var GLTF1;
  77639. (function (GLTF1) {
  77640. ;
  77641. ;
  77642. ;
  77643. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  77644. __extends(GLTFMaterialsCommonExtension, _super);
  77645. function GLTFMaterialsCommonExtension() {
  77646. return _super.call(this, "KHR_materials_common") || this;
  77647. }
  77648. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  77649. if (!gltfRuntime.extensions)
  77650. return false;
  77651. var extension = gltfRuntime.extensions[this.name];
  77652. if (!extension)
  77653. return false;
  77654. // Create lights
  77655. var lights = extension.lights;
  77656. if (lights) {
  77657. for (var thing in lights) {
  77658. var light = lights[thing];
  77659. switch (light.type) {
  77660. case "ambient":
  77661. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  77662. var ambient = light.ambient;
  77663. if (ambient) {
  77664. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  77665. }
  77666. break;
  77667. case "point":
  77668. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  77669. var point = light.point;
  77670. if (point) {
  77671. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  77672. }
  77673. break;
  77674. case "directional":
  77675. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  77676. var directional = light.directional;
  77677. if (directional) {
  77678. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  77679. }
  77680. break;
  77681. case "spot":
  77682. var spot = light.spot;
  77683. if (spot) {
  77684. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  77685. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  77686. }
  77687. break;
  77688. default:
  77689. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  77690. break;
  77691. }
  77692. }
  77693. }
  77694. return false;
  77695. };
  77696. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  77697. var material = gltfRuntime.materials[id];
  77698. if (!material || !material.extensions)
  77699. return false;
  77700. var extension = material.extensions[this.name];
  77701. if (!extension)
  77702. return false;
  77703. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  77704. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  77705. if (extension.technique === "CONSTANT") {
  77706. standardMaterial.disableLighting = true;
  77707. }
  77708. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  77709. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  77710. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  77711. // Ambient
  77712. if (typeof extension.values.ambient === "string") {
  77713. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  77714. }
  77715. else {
  77716. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  77717. }
  77718. // Diffuse
  77719. if (typeof extension.values.diffuse === "string") {
  77720. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  77721. }
  77722. else {
  77723. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  77724. }
  77725. // Emission
  77726. if (typeof extension.values.emission === "string") {
  77727. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  77728. }
  77729. else {
  77730. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  77731. }
  77732. // Specular
  77733. if (typeof extension.values.specular === "string") {
  77734. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  77735. }
  77736. else {
  77737. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  77738. }
  77739. return true;
  77740. };
  77741. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  77742. // Create buffer from texture url
  77743. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  77744. // Create texture from buffer
  77745. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  77746. }, onError);
  77747. };
  77748. return GLTFMaterialsCommonExtension;
  77749. }(GLTF1.GLTFLoaderExtension));
  77750. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  77751. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  77752. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  77753. })(BABYLON || (BABYLON = {}));
  77754. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  77755. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77756. var BABYLON;
  77757. (function (BABYLON) {
  77758. var GLTF2;
  77759. (function (GLTF2) {
  77760. /**
  77761. * Enums
  77762. */
  77763. var EComponentType;
  77764. (function (EComponentType) {
  77765. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  77766. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  77767. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  77768. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  77769. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  77770. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  77771. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  77772. var EMeshPrimitiveMode;
  77773. (function (EMeshPrimitiveMode) {
  77774. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  77775. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  77776. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  77777. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  77778. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  77779. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  77780. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  77781. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  77782. var ETextureMagFilter;
  77783. (function (ETextureMagFilter) {
  77784. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  77785. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  77786. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  77787. var ETextureMinFilter;
  77788. (function (ETextureMinFilter) {
  77789. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  77790. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  77791. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  77792. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  77793. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  77794. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  77795. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  77796. var ETextureWrapMode;
  77797. (function (ETextureWrapMode) {
  77798. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  77799. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  77800. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  77801. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  77802. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  77803. })(BABYLON || (BABYLON = {}));
  77804. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  77805. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  77806. var BABYLON;
  77807. (function (BABYLON) {
  77808. var GLTF2;
  77809. (function (GLTF2) {
  77810. var GLTFLoaderTracker = /** @class */ (function () {
  77811. function GLTFLoaderTracker(onComplete) {
  77812. this._pendingCount = 0;
  77813. this._callback = onComplete;
  77814. }
  77815. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  77816. this._pendingCount++;
  77817. };
  77818. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  77819. if (--this._pendingCount === 0) {
  77820. this._callback();
  77821. }
  77822. };
  77823. return GLTFLoaderTracker;
  77824. }());
  77825. var GLTFLoader = /** @class */ (function () {
  77826. function GLTFLoader(parent) {
  77827. this._disposed = false;
  77828. this._renderReady = false;
  77829. this._requests = new Array();
  77830. this._renderReadyObservable = new BABYLON.Observable();
  77831. // Count of pending work that needs to complete before the asset is rendered.
  77832. this._renderPendingCount = 0;
  77833. // Count of pending work that needs to complete before the loader is disposed.
  77834. this._loaderPendingCount = 0;
  77835. this._loaderTrackers = new Array();
  77836. this._parent = parent;
  77837. }
  77838. GLTFLoader.RegisterExtension = function (extension) {
  77839. if (GLTFLoader.Extensions[extension.name]) {
  77840. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  77841. return;
  77842. }
  77843. GLTFLoader.Extensions[extension.name] = extension;
  77844. // Keep the order of registration so that extensions registered first are called first.
  77845. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  77846. };
  77847. GLTFLoader.prototype.dispose = function () {
  77848. if (this._disposed) {
  77849. return;
  77850. }
  77851. this._disposed = true;
  77852. // Abort requests that are not complete
  77853. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  77854. var request = _a[_i];
  77855. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  77856. request.abort();
  77857. }
  77858. }
  77859. // Revoke object urls created during load
  77860. if (this._gltf.textures) {
  77861. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  77862. var texture = _c[_b];
  77863. if (texture.url) {
  77864. URL.revokeObjectURL(texture.url);
  77865. }
  77866. }
  77867. }
  77868. this._gltf = undefined;
  77869. this._babylonScene = undefined;
  77870. this._parent = undefined;
  77871. this._rootUrl = undefined;
  77872. this._defaultMaterial = undefined;
  77873. this._rootNode = undefined;
  77874. this._successCallback = undefined;
  77875. this._progressCallback = undefined;
  77876. this._errorCallback = undefined;
  77877. this._renderReady = false;
  77878. this._requests = undefined;
  77879. this._renderReadyObservable = undefined;
  77880. this._renderPendingCount = 0;
  77881. this._loaderPendingCount = 0;
  77882. this._loaderTrackers = undefined;
  77883. };
  77884. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77885. var _this = this;
  77886. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  77887. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  77888. }, onProgress, onError);
  77889. };
  77890. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  77891. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  77892. };
  77893. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  77894. var _this = this;
  77895. this._tryCatchOnError(function () {
  77896. _this._loadData(data);
  77897. _this._babylonScene = scene;
  77898. _this._rootUrl = rootUrl;
  77899. _this._successCallback = onSuccess;
  77900. _this._progressCallback = onProgress;
  77901. _this._errorCallback = onError;
  77902. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  77903. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  77904. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  77905. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  77906. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  77907. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  77908. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  77909. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  77910. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  77911. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  77912. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  77913. _this._addPendingData(_this);
  77914. _this._loadDefaultScene(nodeNames);
  77915. _this._loadAnimations();
  77916. _this._removePendingData(_this);
  77917. });
  77918. };
  77919. GLTFLoader.prototype._onError = function (message) {
  77920. if (this._disposed) {
  77921. return;
  77922. }
  77923. BABYLON.Tools.Error("glTF Loader: " + message);
  77924. if (this._errorCallback) {
  77925. this._errorCallback(message);
  77926. }
  77927. this.dispose();
  77928. };
  77929. GLTFLoader.prototype._onProgress = function (event) {
  77930. if (this._disposed) {
  77931. return;
  77932. }
  77933. if (this._progressCallback) {
  77934. this._progressCallback(event);
  77935. }
  77936. };
  77937. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  77938. if (this._renderReady) {
  77939. func();
  77940. }
  77941. else {
  77942. this._renderReadyObservable.add(func);
  77943. }
  77944. };
  77945. GLTFLoader.prototype._onRenderReady = function () {
  77946. if (this._rootNode.babylonMesh) {
  77947. this._rootNode.babylonMesh.setEnabled(true);
  77948. }
  77949. this._startAnimations();
  77950. this._successCallback();
  77951. this._renderReadyObservable.notifyObservers(this);
  77952. };
  77953. GLTFLoader.prototype._onComplete = function () {
  77954. if (this._parent.onComplete) {
  77955. this._parent.onComplete();
  77956. }
  77957. this.dispose();
  77958. };
  77959. GLTFLoader.prototype._loadData = function (data) {
  77960. this._gltf = data.json;
  77961. if (data.bin) {
  77962. var buffers = this._gltf.buffers;
  77963. if (buffers && buffers[0] && !buffers[0].uri) {
  77964. var binaryBuffer = buffers[0];
  77965. if (binaryBuffer.byteLength != data.bin.byteLength) {
  77966. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  77967. }
  77968. binaryBuffer.loadedData = data.bin;
  77969. }
  77970. else {
  77971. BABYLON.Tools.Warn("Unexpected BIN chunk");
  77972. }
  77973. }
  77974. };
  77975. GLTFLoader.prototype._getMeshes = function () {
  77976. var meshes = [this._rootNode.babylonMesh];
  77977. var nodes = this._gltf.nodes;
  77978. if (nodes) {
  77979. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  77980. var node = nodes_1[_i];
  77981. if (node.babylonMesh) {
  77982. meshes.push(node.babylonMesh);
  77983. }
  77984. }
  77985. }
  77986. return meshes;
  77987. };
  77988. GLTFLoader.prototype._getSkeletons = function () {
  77989. var skeletons = new Array();
  77990. var skins = this._gltf.skins;
  77991. if (skins) {
  77992. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  77993. var skin = skins_1[_i];
  77994. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  77995. skeletons.push(skin.babylonSkeleton);
  77996. }
  77997. }
  77998. }
  77999. return skeletons;
  78000. };
  78001. GLTFLoader.prototype._getAnimationTargets = function () {
  78002. var targets = new Array();
  78003. var animations = this._gltf.animations;
  78004. if (animations) {
  78005. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  78006. var animation = animations_1[_i];
  78007. targets.push.apply(targets, animation.targets);
  78008. }
  78009. }
  78010. return targets;
  78011. };
  78012. GLTFLoader.prototype._startAnimations = function () {
  78013. for (var _i = 0, _a = this._getAnimationTargets(); _i < _a.length; _i++) {
  78014. var target = _a[_i];
  78015. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  78016. }
  78017. };
  78018. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  78019. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  78020. if (!scene) {
  78021. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  78022. }
  78023. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  78024. };
  78025. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  78026. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  78027. switch (this._parent.coordinateSystemMode) {
  78028. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  78029. if (!this._babylonScene.useRightHandedSystem && this._rootNode.babylonMesh) {
  78030. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  78031. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  78032. }
  78033. break;
  78034. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  78035. // do nothing
  78036. break;
  78037. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  78038. this._babylonScene.useRightHandedSystem = true;
  78039. break;
  78040. default:
  78041. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  78042. return;
  78043. }
  78044. var nodeIndices = scene.nodes;
  78045. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  78046. node.parent = parentNode;
  78047. return true;
  78048. }, this._rootNode);
  78049. if (nodeNames) {
  78050. if (!(nodeNames instanceof Array)) {
  78051. nodeNames = [nodeNames];
  78052. }
  78053. var filteredNodeIndices_1 = new Array();
  78054. this._traverseNodes(context, nodeIndices, function (node) {
  78055. if (nodeNames.indexOf(node.name) !== -1) {
  78056. filteredNodeIndices_1.push(node.index);
  78057. return false;
  78058. }
  78059. return true;
  78060. }, this._rootNode);
  78061. nodeIndices = filteredNodeIndices_1;
  78062. }
  78063. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  78064. var index = nodeIndices_1[_i];
  78065. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78066. if (!node) {
  78067. throw new Error(context + ": Failed to find node " + index);
  78068. }
  78069. this._loadNode("#/nodes/" + index, node);
  78070. }
  78071. // Disable the root mesh until the asset is ready to render.
  78072. if (this._rootNode.babylonMesh) {
  78073. this._rootNode.babylonMesh.setEnabled(false);
  78074. }
  78075. };
  78076. GLTFLoader.prototype._loadNode = function (context, node) {
  78077. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  78078. return;
  78079. }
  78080. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  78081. this._loadTransform(node);
  78082. if (node.mesh != null) {
  78083. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  78084. if (!mesh) {
  78085. throw new Error(context + ": Failed to find mesh " + node.mesh);
  78086. }
  78087. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  78088. }
  78089. node.babylonMesh.parent = (node.parent ? node.parent.babylonMesh : null);
  78090. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78091. node.babylonAnimationTargets.push(node.babylonMesh);
  78092. if (node.skin != null) {
  78093. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  78094. if (!skin) {
  78095. throw new Error(context + ": Failed to find skin " + node.skin);
  78096. }
  78097. node.babylonMesh.skeleton = this._loadSkin("#/skins/" + node.skin, skin);
  78098. }
  78099. if (node.camera != null) {
  78100. // TODO: handle cameras
  78101. }
  78102. if (node.children) {
  78103. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  78104. var index = _a[_i];
  78105. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78106. if (!childNode) {
  78107. throw new Error(context + ": Failed to find child node " + index);
  78108. }
  78109. this._loadNode("#/nodes/" + index, childNode);
  78110. }
  78111. }
  78112. };
  78113. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  78114. var _this = this;
  78115. if (!node.babylonMesh) {
  78116. return;
  78117. }
  78118. node.babylonMesh.name = node.babylonMesh.name || mesh.name || "";
  78119. var primitives = mesh.primitives;
  78120. if (!primitives || primitives.length === 0) {
  78121. throw new Error(context + ": Primitives are missing");
  78122. }
  78123. this._createMorphTargets(context, node, mesh);
  78124. this._loadAllVertexDataAsync(context, mesh, function () {
  78125. if (!node.babylonMesh) {
  78126. return;
  78127. }
  78128. _this._loadMorphTargets(context, node, mesh);
  78129. var vertexData = new BABYLON.VertexData();
  78130. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  78131. var primitive = primitives_1[_i];
  78132. vertexData.merge(primitive.vertexData);
  78133. }
  78134. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  78135. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  78136. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  78137. node.babylonMesh.subMeshes = [];
  78138. var verticesStart = 0;
  78139. var indicesStart = 0;
  78140. for (var index = 0; index < primitives.length; index++) {
  78141. var vertexData_1 = primitives[index].vertexData;
  78142. var verticesCount = vertexData_1.positions.length;
  78143. var indicesCount = vertexData_1.indices.length;
  78144. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  78145. verticesStart += verticesCount;
  78146. indicesStart += indicesCount;
  78147. }
  78148. ;
  78149. });
  78150. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  78151. node.babylonMesh.material = multiMaterial;
  78152. var subMaterials = multiMaterial.subMaterials;
  78153. var _loop_1 = function (index) {
  78154. var primitive = primitives[index];
  78155. if (primitive.material == null) {
  78156. subMaterials[index] = this_1._getDefaultMaterial();
  78157. }
  78158. else {
  78159. var material_1 = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.materials, primitive.material);
  78160. if (!material_1) {
  78161. throw new Error(context + ": Failed to find material " + primitive.material);
  78162. }
  78163. this_1._loadMaterial("#/materials/" + material_1.index, material_1, function (babylonMaterial, isNew) {
  78164. if (isNew && _this._parent.onMaterialLoaded) {
  78165. _this._parent.onMaterialLoaded(babylonMaterial);
  78166. }
  78167. if (_this._parent.onBeforeMaterialReadyAsync) {
  78168. _this._addLoaderPendingData(material_1);
  78169. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  78170. _this._tryCatchOnError(function () {
  78171. subMaterials[index] = babylonMaterial;
  78172. _this._removeLoaderPendingData(material_1);
  78173. });
  78174. });
  78175. }
  78176. else {
  78177. subMaterials[index] = babylonMaterial;
  78178. }
  78179. });
  78180. }
  78181. };
  78182. var this_1 = this;
  78183. for (var index = 0; index < primitives.length; index++) {
  78184. _loop_1(index);
  78185. }
  78186. ;
  78187. };
  78188. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  78189. var primitives = mesh.primitives;
  78190. var numRemainingPrimitives = primitives.length;
  78191. var _loop_2 = function (index) {
  78192. var primitive = primitives[index];
  78193. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  78194. primitive.vertexData = vertexData;
  78195. if (--numRemainingPrimitives === 0) {
  78196. onSuccess();
  78197. }
  78198. });
  78199. };
  78200. var this_2 = this;
  78201. for (var index = 0; index < primitives.length; index++) {
  78202. _loop_2(index);
  78203. }
  78204. };
  78205. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  78206. var _this = this;
  78207. var attributes = primitive.attributes;
  78208. if (!attributes) {
  78209. throw new Error(context + ": Attributes are missing");
  78210. }
  78211. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  78212. // TODO: handle other primitive modes
  78213. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  78214. }
  78215. var vertexData = new BABYLON.VertexData();
  78216. var numRemainingAttributes = Object.keys(attributes).length;
  78217. var _loop_3 = function (attribute) {
  78218. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_3._gltf.accessors, attributes[attribute]);
  78219. if (!accessor) {
  78220. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78221. }
  78222. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78223. switch (attribute) {
  78224. case "NORMAL":
  78225. vertexData.normals = data;
  78226. break;
  78227. case "POSITION":
  78228. vertexData.positions = data;
  78229. break;
  78230. case "TANGENT":
  78231. vertexData.tangents = data;
  78232. break;
  78233. case "TEXCOORD_0":
  78234. vertexData.uvs = data;
  78235. break;
  78236. case "TEXCOORD_1":
  78237. vertexData.uvs2 = data;
  78238. break;
  78239. case "JOINTS_0":
  78240. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  78241. break;
  78242. case "WEIGHTS_0":
  78243. vertexData.matricesWeights = data;
  78244. break;
  78245. case "COLOR_0":
  78246. vertexData.colors = data;
  78247. break;
  78248. default:
  78249. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78250. break;
  78251. }
  78252. if (--numRemainingAttributes === 0) {
  78253. if (primitive.indices == null) {
  78254. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  78255. for (var i = 0; i < vertexData.indices.length; i++) {
  78256. vertexData.indices[i] = i;
  78257. }
  78258. onSuccess(vertexData);
  78259. }
  78260. else {
  78261. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  78262. if (!indicesAccessor) {
  78263. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  78264. }
  78265. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  78266. vertexData.indices = data;
  78267. onSuccess(vertexData);
  78268. });
  78269. }
  78270. }
  78271. });
  78272. };
  78273. var this_3 = this;
  78274. for (var attribute in attributes) {
  78275. _loop_3(attribute);
  78276. }
  78277. };
  78278. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  78279. var primitives = mesh.primitives;
  78280. var targets = primitives[0].targets;
  78281. if (!targets || !node.babylonMesh) {
  78282. return;
  78283. }
  78284. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  78285. var primitive = primitives_2[_i];
  78286. if (!primitive.targets || primitive.targets.length != targets.length) {
  78287. throw new Error(context + ": All primitives are required to list the same number of targets");
  78288. }
  78289. }
  78290. var morphTargetManager = new BABYLON.MorphTargetManager();
  78291. node.babylonMesh.morphTargetManager = morphTargetManager;
  78292. for (var index = 0; index < targets.length; index++) {
  78293. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  78294. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  78295. }
  78296. };
  78297. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  78298. if (!node.babylonMesh) {
  78299. return;
  78300. }
  78301. var morphTargetManager = node.babylonMesh.morphTargetManager;
  78302. if (!morphTargetManager) {
  78303. return;
  78304. }
  78305. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  78306. var numTargets = morphTargetManager.numTargets;
  78307. for (var index = 0; index < numTargets; index++) {
  78308. var vertexData = new BABYLON.VertexData();
  78309. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78310. var primitive = _a[_i];
  78311. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  78312. }
  78313. var target = morphTargetManager.getTarget(index);
  78314. target.setNormals(vertexData.normals);
  78315. target.setPositions(vertexData.positions);
  78316. target.setTangents(vertexData.tangents);
  78317. }
  78318. });
  78319. };
  78320. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  78321. if (!node.babylonMesh || !node.babylonMesh.morphTargetManager) {
  78322. return;
  78323. }
  78324. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  78325. var _loop_4 = function (primitive) {
  78326. var targets = primitive.targets;
  78327. if (!targets) {
  78328. return "continue";
  78329. }
  78330. primitive.targetsVertexData = new Array(targets.length);
  78331. var _loop_5 = function (index) {
  78332. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  78333. primitive.targetsVertexData[index] = vertexData;
  78334. if (--numRemainingTargets === 0) {
  78335. onSuccess();
  78336. }
  78337. });
  78338. };
  78339. for (var index = 0; index < targets.length; index++) {
  78340. _loop_5(index);
  78341. }
  78342. };
  78343. var this_4 = this;
  78344. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  78345. var primitive = _a[_i];
  78346. _loop_4(primitive);
  78347. }
  78348. };
  78349. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  78350. var targetVertexData = new BABYLON.VertexData();
  78351. var numRemainingAttributes = Object.keys(attributes).length;
  78352. var _loop_6 = function (attribute) {
  78353. var accessor = GLTF2.GLTFUtils.GetArrayItem(this_5._gltf.accessors, attributes[attribute]);
  78354. if (!accessor) {
  78355. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  78356. }
  78357. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78358. // glTF stores morph target information as deltas while babylon.js expects the final data.
  78359. // As a result we have to add the original data to the delta to calculate the final data.
  78360. var values = data;
  78361. switch (attribute) {
  78362. case "NORMAL":
  78363. for (var i = 0; i < values.length; i++) {
  78364. values[i] += vertexData.normals[i];
  78365. }
  78366. targetVertexData.normals = values;
  78367. break;
  78368. case "POSITION":
  78369. for (var i = 0; i < values.length; i++) {
  78370. values[i] += vertexData.positions[i];
  78371. }
  78372. targetVertexData.positions = values;
  78373. break;
  78374. case "TANGENT":
  78375. // Tangent data for morph targets is stored as xyz delta.
  78376. // The vertexData.tangent is stored as xyzw.
  78377. // So we need to skip every fourth vertexData.tangent.
  78378. for (var i = 0, j = 0; i < values.length; i++, j++) {
  78379. values[i] += vertexData.tangents[j];
  78380. if ((i + 1) % 3 == 0) {
  78381. j++;
  78382. }
  78383. }
  78384. targetVertexData.tangents = values;
  78385. break;
  78386. default:
  78387. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  78388. break;
  78389. }
  78390. if (--numRemainingAttributes === 0) {
  78391. onSuccess(targetVertexData);
  78392. }
  78393. });
  78394. };
  78395. var this_5 = this;
  78396. for (var attribute in attributes) {
  78397. _loop_6(attribute);
  78398. }
  78399. };
  78400. GLTFLoader.prototype._loadTransform = function (node) {
  78401. if (!node.babylonMesh) {
  78402. return;
  78403. }
  78404. var position = BABYLON.Vector3.Zero();
  78405. var rotation = BABYLON.Quaternion.Identity();
  78406. var scaling = BABYLON.Vector3.One();
  78407. if (node.matrix) {
  78408. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  78409. matrix.decompose(scaling, rotation, position);
  78410. }
  78411. else {
  78412. if (node.translation)
  78413. position = BABYLON.Vector3.FromArray(node.translation);
  78414. if (node.rotation)
  78415. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  78416. if (node.scale)
  78417. scaling = BABYLON.Vector3.FromArray(node.scale);
  78418. }
  78419. node.babylonMesh.position = position;
  78420. node.babylonMesh.rotationQuaternion = rotation;
  78421. node.babylonMesh.scaling = scaling;
  78422. };
  78423. GLTFLoader.prototype._loadSkin = function (context, skin) {
  78424. var _this = this;
  78425. var skeletonId = "skeleton" + skin.index;
  78426. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  78427. if (skin.inverseBindMatrices == null) {
  78428. this._loadBones(context, skin, null);
  78429. }
  78430. else {
  78431. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  78432. if (!accessor) {
  78433. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  78434. }
  78435. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  78436. _this._loadBones(context, skin, data);
  78437. });
  78438. }
  78439. return skin.babylonSkeleton;
  78440. };
  78441. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  78442. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  78443. node.babylonBones = node.babylonBones || {};
  78444. node.babylonBones[skin.index] = babylonBone;
  78445. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  78446. node.babylonAnimationTargets.push(babylonBone);
  78447. return babylonBone;
  78448. };
  78449. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  78450. var babylonBones = {};
  78451. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  78452. var index = _a[_i];
  78453. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78454. if (!node) {
  78455. throw new Error(context + ": Failed to find joint " + index);
  78456. }
  78457. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  78458. }
  78459. };
  78460. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  78461. var babylonBone = babylonBones[node.index];
  78462. if (babylonBone) {
  78463. return babylonBone;
  78464. }
  78465. var boneIndex = skin.joints.indexOf(node.index);
  78466. var baseMatrix = BABYLON.Matrix.Identity();
  78467. if (inverseBindMatrixData && boneIndex !== -1) {
  78468. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  78469. baseMatrix.invertToRef(baseMatrix);
  78470. }
  78471. var babylonParentBone = null;
  78472. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  78473. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  78474. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  78475. }
  78476. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  78477. babylonBones[node.index] = babylonBone;
  78478. return babylonBone;
  78479. };
  78480. GLTFLoader.prototype._getNodeMatrix = function (node) {
  78481. return node.matrix ?
  78482. BABYLON.Matrix.FromArray(node.matrix) :
  78483. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  78484. };
  78485. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  78486. if (parentNode === void 0) { parentNode = null; }
  78487. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  78488. var index = indices_1[_i];
  78489. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, index);
  78490. if (!node) {
  78491. throw new Error(context + ": Failed to find node " + index);
  78492. }
  78493. this._traverseNode(context, node, action, parentNode);
  78494. }
  78495. };
  78496. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  78497. if (parentNode === void 0) { parentNode = null; }
  78498. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  78499. return;
  78500. }
  78501. if (!action(node, parentNode)) {
  78502. return;
  78503. }
  78504. if (node.children) {
  78505. this._traverseNodes(context, node.children, action, node);
  78506. }
  78507. };
  78508. GLTFLoader.prototype._loadAnimations = function () {
  78509. var animations = this._gltf.animations;
  78510. if (!animations) {
  78511. return;
  78512. }
  78513. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  78514. var animation = animations[animationIndex];
  78515. var context = "#/animations/" + animationIndex;
  78516. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  78517. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  78518. if (!channel) {
  78519. throw new Error(context + ": Failed to find channel " + channelIndex);
  78520. }
  78521. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  78522. if (!sampler) {
  78523. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  78524. }
  78525. this._loadAnimationChannel(animation, context + "/channels/" + channelIndex, channel, context + "/samplers/" + channel.sampler, sampler);
  78526. }
  78527. }
  78528. };
  78529. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  78530. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  78531. if (!targetNode) {
  78532. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  78533. }
  78534. var targetPath;
  78535. var animationType;
  78536. switch (channel.target.path) {
  78537. case "translation":
  78538. targetPath = "position";
  78539. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78540. break;
  78541. case "rotation":
  78542. targetPath = "rotationQuaternion";
  78543. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  78544. break;
  78545. case "scale":
  78546. targetPath = "scaling";
  78547. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  78548. break;
  78549. case "weights":
  78550. targetPath = "influence";
  78551. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  78552. break;
  78553. default:
  78554. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  78555. }
  78556. var inputData;
  78557. var outputData;
  78558. var checkSuccess = function () {
  78559. if (!inputData || !outputData) {
  78560. return;
  78561. }
  78562. var outputBufferOffset = 0;
  78563. var getNextOutputValue;
  78564. switch (targetPath) {
  78565. case "position":
  78566. getNextOutputValue = function () {
  78567. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78568. outputBufferOffset += 3;
  78569. return value;
  78570. };
  78571. break;
  78572. case "rotationQuaternion":
  78573. getNextOutputValue = function () {
  78574. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  78575. outputBufferOffset += 4;
  78576. return value;
  78577. };
  78578. break;
  78579. case "scaling":
  78580. getNextOutputValue = function () {
  78581. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  78582. outputBufferOffset += 3;
  78583. return value;
  78584. };
  78585. break;
  78586. case "influence":
  78587. getNextOutputValue = function () {
  78588. if (!targetNode.babylonMesh || !targetNode.babylonMesh.morphTargetManager) {
  78589. return BABYLON.Vector3.Zero();
  78590. }
  78591. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  78592. var value = new Array(numTargets);
  78593. for (var i = 0; i < numTargets; i++) {
  78594. value[i] = outputData[outputBufferOffset++];
  78595. }
  78596. return value;
  78597. };
  78598. break;
  78599. }
  78600. var getNextKey;
  78601. switch (sampler.interpolation) {
  78602. case "LINEAR":
  78603. getNextKey = function (frameIndex) { return ({
  78604. frame: inputData[frameIndex],
  78605. value: getNextOutputValue()
  78606. }); };
  78607. break;
  78608. case "CUBICSPLINE":
  78609. getNextKey = function (frameIndex) { return ({
  78610. frame: inputData[frameIndex],
  78611. inTangent: getNextOutputValue(),
  78612. value: getNextOutputValue(),
  78613. outTangent: getNextOutputValue()
  78614. }); };
  78615. break;
  78616. default:
  78617. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  78618. }
  78619. ;
  78620. var keys = new Array(inputData.length);
  78621. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  78622. keys[frameIndex] = getNextKey(frameIndex);
  78623. }
  78624. animation.targets = animation.targets || [];
  78625. if (targetPath === "influence" && targetNode.babylonMesh && targetNode.babylonMesh.morphTargetManager) {
  78626. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  78627. var _loop_7 = function (targetIndex) {
  78628. var morphTarget = morphTargetManager.getTarget(targetIndex);
  78629. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  78630. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78631. babylonAnimation.setKeys(keys.map(function (key) { return ({
  78632. frame: key.frame,
  78633. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  78634. value: key.value[targetIndex],
  78635. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  78636. }); }));
  78637. morphTarget.animations.push(babylonAnimation);
  78638. animation.targets.push(morphTarget);
  78639. };
  78640. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  78641. _loop_7(targetIndex);
  78642. }
  78643. }
  78644. else if (targetNode.babylonAnimationTargets) {
  78645. var animationName = animation.name || "anim" + animation.index;
  78646. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  78647. babylonAnimation.setKeys(keys);
  78648. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  78649. var target = _a[_i];
  78650. target.animations.push(babylonAnimation.clone());
  78651. animation.targets.push(target);
  78652. }
  78653. }
  78654. };
  78655. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  78656. if (!inputAccessor) {
  78657. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  78658. }
  78659. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  78660. inputData = data;
  78661. checkSuccess();
  78662. });
  78663. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  78664. if (!outputAccessor) {
  78665. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  78666. }
  78667. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  78668. outputData = data;
  78669. checkSuccess();
  78670. });
  78671. };
  78672. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  78673. var _this = this;
  78674. this._addPendingData(buffer);
  78675. if (buffer.loadedData) {
  78676. onSuccess(buffer.loadedData);
  78677. this._removePendingData(buffer);
  78678. }
  78679. else if (buffer.loadedObservable) {
  78680. buffer.loadedObservable.add(function (buffer) {
  78681. onSuccess(buffer.loadedData);
  78682. _this._removePendingData(buffer);
  78683. });
  78684. }
  78685. else {
  78686. if (!buffer.uri) {
  78687. throw new Error(context + ": Uri is missing");
  78688. }
  78689. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  78690. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  78691. buffer.loadedData = new Uint8Array(data);
  78692. onSuccess(buffer.loadedData);
  78693. this._removePendingData(buffer);
  78694. }
  78695. else {
  78696. buffer.loadedObservable = new BABYLON.Observable();
  78697. buffer.loadedObservable.add(function (buffer) {
  78698. onSuccess(buffer.loadedData);
  78699. _this._removePendingData(buffer);
  78700. });
  78701. this._loadUri(context, buffer.uri, function (data) {
  78702. buffer.loadedData = data;
  78703. if (buffer.loadedObservable) {
  78704. buffer.loadedObservable.notifyObservers(buffer);
  78705. buffer.loadedObservable = undefined;
  78706. }
  78707. });
  78708. }
  78709. }
  78710. };
  78711. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  78712. var _this = this;
  78713. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  78714. if (!buffer) {
  78715. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  78716. }
  78717. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  78718. if (_this._disposed || !bufferData) {
  78719. return;
  78720. }
  78721. var data;
  78722. try {
  78723. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  78724. }
  78725. catch (e) {
  78726. throw new Error(context + ": " + e.message);
  78727. }
  78728. onSuccess(data);
  78729. });
  78730. };
  78731. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  78732. var _this = this;
  78733. if (accessor.sparse) {
  78734. throw new Error(context + ": Sparse accessors are not currently supported");
  78735. }
  78736. if (accessor.normalized) {
  78737. throw new Error(context + ": Normalized accessors are not currently supported");
  78738. }
  78739. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  78740. if (!bufferView) {
  78741. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  78742. }
  78743. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  78744. var numComponents = _this._getNumComponentsOfType(accessor.type);
  78745. if (numComponents === 0) {
  78746. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  78747. }
  78748. var data;
  78749. var byteOffset = accessor.byteOffset;
  78750. var byteStride = bufferView.byteStride;
  78751. try {
  78752. switch (accessor.componentType) {
  78753. case GLTF2.EComponentType.BYTE:
  78754. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78755. break;
  78756. case GLTF2.EComponentType.UNSIGNED_BYTE:
  78757. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78758. break;
  78759. case GLTF2.EComponentType.SHORT:
  78760. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78761. break;
  78762. case GLTF2.EComponentType.UNSIGNED_SHORT:
  78763. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78764. break;
  78765. case GLTF2.EComponentType.UNSIGNED_INT:
  78766. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78767. break;
  78768. case GLTF2.EComponentType.FLOAT:
  78769. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  78770. break;
  78771. default:
  78772. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  78773. }
  78774. }
  78775. catch (e) {
  78776. throw new Error(context + ": " + e);
  78777. }
  78778. onSuccess(data);
  78779. });
  78780. };
  78781. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  78782. switch (type) {
  78783. case "SCALAR": return 1;
  78784. case "VEC2": return 2;
  78785. case "VEC3": return 3;
  78786. case "VEC4": return 4;
  78787. case "MAT2": return 4;
  78788. case "MAT3": return 9;
  78789. case "MAT4": return 16;
  78790. }
  78791. return 0;
  78792. };
  78793. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  78794. byteOffset = data.byteOffset + (byteOffset || 0);
  78795. var targetLength = count * numComponents;
  78796. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  78797. return new typedArray(data.buffer, byteOffset, targetLength);
  78798. }
  78799. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  78800. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  78801. var targetBuffer = new typedArray(targetLength);
  78802. var sourceIndex = 0;
  78803. var targetIndex = 0;
  78804. while (targetIndex < targetLength) {
  78805. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  78806. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  78807. targetIndex++;
  78808. }
  78809. sourceIndex += elementStride;
  78810. }
  78811. return targetBuffer;
  78812. };
  78813. GLTFLoader.prototype._addPendingData = function (data) {
  78814. if (!this._renderReady) {
  78815. this._renderPendingCount++;
  78816. }
  78817. this._addLoaderPendingData(data);
  78818. };
  78819. GLTFLoader.prototype._removePendingData = function (data) {
  78820. if (!this._renderReady) {
  78821. if (--this._renderPendingCount === 0) {
  78822. this._renderReady = true;
  78823. this._onRenderReady();
  78824. }
  78825. }
  78826. this._removeLoaderPendingData(data);
  78827. };
  78828. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  78829. this._loaderPendingCount++;
  78830. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78831. var tracker = _a[_i];
  78832. tracker._addPendingData(data);
  78833. }
  78834. };
  78835. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  78836. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  78837. var tracker = _a[_i];
  78838. tracker._removePendingData(data);
  78839. }
  78840. if (--this._loaderPendingCount === 0) {
  78841. this._onComplete();
  78842. }
  78843. };
  78844. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  78845. var _this = this;
  78846. var tracker = new GLTFLoaderTracker(function () {
  78847. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  78848. onComplete();
  78849. });
  78850. this._loaderTrackers.push(tracker);
  78851. this._addLoaderPendingData(tracker);
  78852. action();
  78853. this._removeLoaderPendingData(tracker);
  78854. };
  78855. GLTFLoader.prototype._getDefaultMaterial = function () {
  78856. if (!this._defaultMaterial) {
  78857. var id = "__gltf_default";
  78858. var material = this._babylonScene.getMaterialByName(id);
  78859. if (!material) {
  78860. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  78861. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78862. material.metallic = 1;
  78863. material.roughness = 1;
  78864. }
  78865. this._defaultMaterial = material;
  78866. }
  78867. return this._defaultMaterial;
  78868. };
  78869. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  78870. var babylonMaterial = material.babylonMaterial;
  78871. // Ensure metallic workflow
  78872. babylonMaterial.metallic = 1;
  78873. babylonMaterial.roughness = 1;
  78874. var properties = material.pbrMetallicRoughness;
  78875. if (!properties) {
  78876. return;
  78877. }
  78878. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  78879. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  78880. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  78881. if (properties.baseColorTexture) {
  78882. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  78883. if (!texture) {
  78884. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  78885. }
  78886. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  78887. }
  78888. if (properties.metallicRoughnessTexture) {
  78889. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  78890. if (!texture) {
  78891. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  78892. }
  78893. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  78894. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  78895. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  78896. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  78897. }
  78898. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  78899. };
  78900. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  78901. if (material.babylonMaterial) {
  78902. assign(material.babylonMaterial, false);
  78903. return;
  78904. }
  78905. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  78906. return;
  78907. }
  78908. this._createPbrMaterial(material);
  78909. this._loadMaterialBaseProperties(context, material);
  78910. this._loadMaterialMetallicRoughnessProperties(context, material);
  78911. if (material.babylonMaterial) {
  78912. assign(material.babylonMaterial, true);
  78913. }
  78914. };
  78915. GLTFLoader.prototype._createPbrMaterial = function (material) {
  78916. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  78917. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  78918. material.babylonMaterial = babylonMaterial;
  78919. };
  78920. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  78921. var babylonMaterial = material.babylonMaterial;
  78922. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  78923. if (material.doubleSided) {
  78924. babylonMaterial.backFaceCulling = false;
  78925. babylonMaterial.twoSidedLighting = true;
  78926. }
  78927. if (material.normalTexture) {
  78928. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  78929. if (!texture) {
  78930. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  78931. }
  78932. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  78933. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  78934. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  78935. if (material.normalTexture.scale != null) {
  78936. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  78937. }
  78938. }
  78939. if (material.occlusionTexture) {
  78940. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  78941. if (!texture) {
  78942. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  78943. }
  78944. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  78945. babylonMaterial.useAmbientInGrayScale = true;
  78946. if (material.occlusionTexture.strength != null) {
  78947. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  78948. }
  78949. }
  78950. if (material.emissiveTexture) {
  78951. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  78952. if (!texture) {
  78953. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  78954. }
  78955. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  78956. }
  78957. };
  78958. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  78959. var babylonMaterial = material.babylonMaterial;
  78960. var alphaMode = material.alphaMode || "OPAQUE";
  78961. switch (alphaMode) {
  78962. case "OPAQUE":
  78963. // default is opaque
  78964. break;
  78965. case "MASK":
  78966. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  78967. if (colorFactor) {
  78968. if (colorFactor[3] == 0) {
  78969. babylonMaterial.alphaCutOff = 1;
  78970. }
  78971. else {
  78972. babylonMaterial.alphaCutOff /= colorFactor[3];
  78973. }
  78974. }
  78975. if (babylonMaterial.albedoTexture) {
  78976. babylonMaterial.albedoTexture.hasAlpha = true;
  78977. }
  78978. break;
  78979. case "BLEND":
  78980. if (colorFactor) {
  78981. babylonMaterial.alpha = colorFactor[3];
  78982. }
  78983. if (babylonMaterial.albedoTexture) {
  78984. babylonMaterial.albedoTexture.hasAlpha = true;
  78985. babylonMaterial.useAlphaFromAlbedoTexture = true;
  78986. }
  78987. break;
  78988. default:
  78989. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  78990. }
  78991. };
  78992. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  78993. var _this = this;
  78994. if (coordinatesIndex === void 0) { coordinatesIndex = 0; }
  78995. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  78996. if (!sampler) {
  78997. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  78998. }
  78999. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  79000. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  79001. this._addPendingData(texture);
  79002. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  79003. _this._tryCatchOnError(function () {
  79004. _this._removePendingData(texture);
  79005. });
  79006. }, function (message) {
  79007. _this._tryCatchOnError(function () {
  79008. throw new Error(context + ": " + message);
  79009. });
  79010. });
  79011. if (texture.url) {
  79012. babylonTexture.updateURL(texture.url);
  79013. }
  79014. else if (texture.dataReadyObservable) {
  79015. texture.dataReadyObservable.add(function (texture) {
  79016. babylonTexture.updateURL(texture.url);
  79017. });
  79018. }
  79019. else {
  79020. texture.dataReadyObservable = new BABYLON.Observable();
  79021. texture.dataReadyObservable.add(function (texture) {
  79022. babylonTexture.updateURL(texture.url);
  79023. });
  79024. var image_1 = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  79025. if (!image_1) {
  79026. throw new Error(context + ": Failed to find source " + texture.source);
  79027. }
  79028. this._loadImage("#/images/" + image_1.index, image_1, function (data) {
  79029. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  79030. if (texture.dataReadyObservable) {
  79031. texture.dataReadyObservable.notifyObservers(texture);
  79032. }
  79033. });
  79034. }
  79035. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  79036. if (sampler.wrapS !== undefined) {
  79037. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  79038. }
  79039. if (sampler.wrapT !== undefined) {
  79040. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  79041. }
  79042. babylonTexture.name = texture.name || "texture" + texture.index;
  79043. if (this._parent.onTextureLoaded) {
  79044. this._parent.onTextureLoaded(babylonTexture);
  79045. }
  79046. return babylonTexture;
  79047. };
  79048. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  79049. if (image.uri) {
  79050. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  79051. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  79052. }
  79053. else {
  79054. this._loadUri(context, image.uri, onSuccess);
  79055. }
  79056. }
  79057. else {
  79058. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  79059. if (!bufferView) {
  79060. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  79061. }
  79062. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  79063. }
  79064. };
  79065. GLTFLoader.prototype._loadUri = function (context, uri, onSuccess) {
  79066. var _this = this;
  79067. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  79068. throw new Error(context + ": Uri '" + uri + "' is invalid");
  79069. }
  79070. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  79071. _this._tryCatchOnError(function () {
  79072. onSuccess(new Uint8Array(data));
  79073. });
  79074. }, function (event) {
  79075. _this._tryCatchOnError(function () {
  79076. _this._onProgress(event);
  79077. });
  79078. }, this._babylonScene.database, true, function (request) {
  79079. _this._tryCatchOnError(function () {
  79080. throw new Error(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  79081. });
  79082. });
  79083. if (request) {
  79084. this._requests.push(request);
  79085. }
  79086. };
  79087. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  79088. try {
  79089. handler();
  79090. }
  79091. catch (e) {
  79092. this._onError(e.message);
  79093. }
  79094. };
  79095. GLTFLoader.Extensions = {};
  79096. return GLTFLoader;
  79097. }());
  79098. GLTF2.GLTFLoader = GLTFLoader;
  79099. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  79100. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79101. })(BABYLON || (BABYLON = {}));
  79102. //# sourceMappingURL=babylon.glTFLoader.js.map
  79103. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79104. var BABYLON;
  79105. (function (BABYLON) {
  79106. var GLTF2;
  79107. (function (GLTF2) {
  79108. /**
  79109. * Utils functions for GLTF
  79110. */
  79111. var GLTFUtils = /** @class */ (function () {
  79112. function GLTFUtils() {
  79113. }
  79114. /**
  79115. * If the uri is a base64 string
  79116. * @param uri: the uri to test
  79117. */
  79118. GLTFUtils.IsBase64 = function (uri) {
  79119. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  79120. };
  79121. /**
  79122. * Decode the base64 uri
  79123. * @param uri: the uri to decode
  79124. */
  79125. GLTFUtils.DecodeBase64 = function (uri) {
  79126. var decodedString = atob(uri.split(",")[1]);
  79127. var bufferLength = decodedString.length;
  79128. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  79129. for (var i = 0; i < bufferLength; i++) {
  79130. bufferView[i] = decodedString.charCodeAt(i);
  79131. }
  79132. return bufferView.buffer;
  79133. };
  79134. GLTFUtils.ValidateUri = function (uri) {
  79135. return (uri.indexOf("..") === -1);
  79136. };
  79137. GLTFUtils.AssignIndices = function (array) {
  79138. if (array) {
  79139. for (var index = 0; index < array.length; index++) {
  79140. array[index].index = index;
  79141. }
  79142. }
  79143. };
  79144. GLTFUtils.GetArrayItem = function (array, index) {
  79145. if (!array || !array[index]) {
  79146. return null;
  79147. }
  79148. return array[index];
  79149. };
  79150. GLTFUtils.GetTextureWrapMode = function (mode) {
  79151. // Set defaults if undefined
  79152. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  79153. switch (mode) {
  79154. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  79155. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  79156. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  79157. default:
  79158. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  79159. return BABYLON.Texture.WRAP_ADDRESSMODE;
  79160. }
  79161. };
  79162. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  79163. // Set defaults if undefined
  79164. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  79165. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  79166. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  79167. switch (minFilter) {
  79168. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  79169. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  79170. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  79171. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  79172. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  79173. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79174. default:
  79175. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79176. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  79177. }
  79178. }
  79179. else {
  79180. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  79181. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  79182. }
  79183. switch (minFilter) {
  79184. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  79185. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  79186. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79187. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  79188. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  79189. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  79190. default:
  79191. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  79192. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  79193. }
  79194. }
  79195. };
  79196. return GLTFUtils;
  79197. }());
  79198. GLTF2.GLTFUtils = GLTFUtils;
  79199. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79200. })(BABYLON || (BABYLON = {}));
  79201. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  79202. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79203. var BABYLON;
  79204. (function (BABYLON) {
  79205. var GLTF2;
  79206. (function (GLTF2) {
  79207. var GLTFLoaderExtension = /** @class */ (function () {
  79208. function GLTFLoaderExtension() {
  79209. this.enabled = true;
  79210. }
  79211. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  79212. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  79213. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  79214. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  79215. var _this = this;
  79216. if (!property.extensions) {
  79217. return false;
  79218. }
  79219. var extension = property.extensions[this.name];
  79220. if (!extension) {
  79221. return false;
  79222. }
  79223. // Clear out the extension before executing the action to avoid recursing into the same property.
  79224. property.extensions[this.name] = undefined;
  79225. action(extension, function () {
  79226. // Restore the extension after completing the action.
  79227. if (property.extensions) {
  79228. property.extensions[_this.name] = extension;
  79229. }
  79230. });
  79231. return true;
  79232. };
  79233. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  79234. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  79235. };
  79236. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  79237. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  79238. };
  79239. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  79240. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  79241. };
  79242. GLTFLoaderExtension._ApplyExtensions = function (action) {
  79243. var extensions = GLTFLoaderExtension._Extensions;
  79244. if (!extensions) {
  79245. return false;
  79246. }
  79247. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  79248. var extension = extensions_1[_i];
  79249. if (extension.enabled && action(extension)) {
  79250. return true;
  79251. }
  79252. }
  79253. return false;
  79254. };
  79255. //
  79256. // Utilities
  79257. //
  79258. GLTFLoaderExtension._Extensions = [];
  79259. return GLTFLoaderExtension;
  79260. }());
  79261. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  79262. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79263. })(BABYLON || (BABYLON = {}));
  79264. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  79265. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79266. var BABYLON;
  79267. (function (BABYLON) {
  79268. var GLTF2;
  79269. (function (GLTF2) {
  79270. var Extensions;
  79271. (function (Extensions) {
  79272. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  79273. var MSFTLOD = /** @class */ (function (_super) {
  79274. __extends(MSFTLOD, _super);
  79275. function MSFTLOD() {
  79276. return _super !== null && _super.apply(this, arguments) || this;
  79277. }
  79278. Object.defineProperty(MSFTLOD.prototype, "name", {
  79279. get: function () {
  79280. return "MSFT_lod";
  79281. },
  79282. enumerable: true,
  79283. configurable: true
  79284. });
  79285. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  79286. return this._loadExtension(node, function (extension, onComplete) {
  79287. if (!loader._gltf.nodes) {
  79288. return;
  79289. }
  79290. for (var i = extension.ids.length - 1; i >= 0; i--) {
  79291. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  79292. if (!lodNode) {
  79293. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  79294. }
  79295. loader._traverseNode(context, lodNode, action, parentNode);
  79296. }
  79297. loader._traverseNode(context, node, action, parentNode);
  79298. onComplete();
  79299. });
  79300. };
  79301. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  79302. var _this = this;
  79303. return this._loadExtension(node, function (extension, onComplete) {
  79304. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  79305. loader._addLoaderPendingData(node);
  79306. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  79307. loader._removeLoaderPendingData(node);
  79308. onComplete();
  79309. });
  79310. });
  79311. };
  79312. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  79313. var _this = this;
  79314. loader._whenAction(function () {
  79315. loader._loadNode(context, nodes[index]);
  79316. }, function () {
  79317. if (index !== nodes.length - 1) {
  79318. var previousNode = nodes[index + 1];
  79319. if (previousNode.babylonMesh) {
  79320. previousNode.babylonMesh.setEnabled(false);
  79321. }
  79322. }
  79323. if (index === 0) {
  79324. onComplete();
  79325. return;
  79326. }
  79327. setTimeout(function () {
  79328. loader._tryCatchOnError(function () {
  79329. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  79330. });
  79331. }, MSFTLOD.MinimalLODDelay);
  79332. });
  79333. };
  79334. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  79335. var _this = this;
  79336. return this._loadExtension(material, function (extension, onComplete) {
  79337. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  79338. loader._addLoaderPendingData(material);
  79339. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  79340. if (material.extensions) {
  79341. material.extensions[_this.name] = extension;
  79342. }
  79343. loader._removeLoaderPendingData(material);
  79344. onComplete();
  79345. });
  79346. });
  79347. };
  79348. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  79349. var _this = this;
  79350. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  79351. assign(babylonMaterial, isNew);
  79352. if (index === 0) {
  79353. onComplete();
  79354. return;
  79355. }
  79356. // Load the next LOD when the loader is ready to render and
  79357. // all active material textures of the current LOD are loaded.
  79358. loader._executeWhenRenderReady(function () {
  79359. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  79360. setTimeout(function () {
  79361. loader._tryCatchOnError(function () {
  79362. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  79363. });
  79364. }, MSFTLOD.MinimalLODDelay);
  79365. });
  79366. });
  79367. });
  79368. };
  79369. /**
  79370. * Specify the minimal delay between LODs in ms (default = 250)
  79371. */
  79372. MSFTLOD.MinimalLODDelay = 250;
  79373. return MSFTLOD;
  79374. }(GLTF2.GLTFLoaderExtension));
  79375. Extensions.MSFTLOD = MSFTLOD;
  79376. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  79377. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79378. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79379. })(BABYLON || (BABYLON = {}));
  79380. //# sourceMappingURL=MSFT_lod.js.map
  79381. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  79382. var BABYLON;
  79383. (function (BABYLON) {
  79384. var GLTF2;
  79385. (function (GLTF2) {
  79386. var Extensions;
  79387. (function (Extensions) {
  79388. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  79389. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  79390. function KHRMaterialsPbrSpecularGlossiness() {
  79391. return _super !== null && _super.apply(this, arguments) || this;
  79392. }
  79393. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  79394. get: function () {
  79395. return "KHR_materials_pbrSpecularGlossiness";
  79396. },
  79397. enumerable: true,
  79398. configurable: true
  79399. });
  79400. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  79401. var _this = this;
  79402. return this._loadExtension(material, function (extension, onComplete) {
  79403. loader._createPbrMaterial(material);
  79404. loader._loadMaterialBaseProperties(context, material);
  79405. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  79406. if (material.babylonMaterial) {
  79407. assign(material.babylonMaterial, true);
  79408. }
  79409. });
  79410. };
  79411. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  79412. var babylonMaterial = material.babylonMaterial;
  79413. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  79414. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  79415. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  79416. if (loader._gltf.textures) {
  79417. if (properties.diffuseTexture) {
  79418. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  79419. if (!texture) {
  79420. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  79421. }
  79422. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  79423. }
  79424. if (properties.specularGlossinessTexture) {
  79425. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  79426. if (!texture) {
  79427. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  79428. }
  79429. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  79430. babylonMaterial.reflectivityTexture.hasAlpha = true;
  79431. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  79432. }
  79433. }
  79434. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  79435. };
  79436. return KHRMaterialsPbrSpecularGlossiness;
  79437. }(GLTF2.GLTFLoaderExtension));
  79438. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  79439. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  79440. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  79441. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  79442. })(BABYLON || (BABYLON = {}));
  79443. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  79444. (function universalModuleDefinition(root, factory) {
  79445. if (root && root["BABYLON"]) {
  79446. return;
  79447. }
  79448. if(typeof exports === 'object' && typeof module === 'object')
  79449. module.exports = factory();
  79450. else if(typeof define === 'function' && define.amd)
  79451. define([], factory);
  79452. else if(typeof exports === 'object')
  79453. exports["BABYLON"] = factory();
  79454. else {
  79455. root["BABYLON"] = factory();
  79456. }
  79457. })(this, function() {
  79458. return BABYLON;
  79459. });