babylon.max.js 3.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * 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.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = new Array();
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = new Array();
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = new Array();
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * 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".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. 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);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * 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".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. 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);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = new Array();
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. 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]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. 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]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. 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);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. 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);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. 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);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. 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);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. 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);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * 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".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * 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".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. 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);
  3659. };
  3660. /**
  3661. * 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".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * 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".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. 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);
  3693. };
  3694. /**
  3695. * 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.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * 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.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. 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);
  3713. };
  3714. /**
  3715. * 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.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * 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.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. 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);
  3735. };
  3736. /**
  3737. * 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.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * 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.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * 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.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. 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);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * 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.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * 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.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. 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);
  3786. };
  3787. /**
  3788. * 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.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * 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.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * 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.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. 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);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4182. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4183. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4184. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4185. frustumPlane.d = transform.m[15] + transform.m[14];
  4186. frustumPlane.normalize();
  4187. };
  4188. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4189. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4190. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4191. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4192. frustumPlane.d = transform.m[15] - transform.m[14];
  4193. frustumPlane.normalize();
  4194. };
  4195. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4196. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4197. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4198. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4199. frustumPlane.d = transform.m[15] + transform.m[12];
  4200. frustumPlane.normalize();
  4201. };
  4202. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4203. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4204. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4205. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4206. frustumPlane.d = transform.m[15] - transform.m[12];
  4207. frustumPlane.normalize();
  4208. };
  4209. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4210. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlane.d = transform.m[15] - transform.m[13];
  4214. frustumPlane.normalize();
  4215. };
  4216. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4217. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4218. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4219. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4220. frustumPlane.d = transform.m[15] + transform.m[13];
  4221. frustumPlane.normalize();
  4222. };
  4223. /**
  4224. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4225. */
  4226. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4227. // Near
  4228. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4229. // Far
  4230. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4231. // Left
  4232. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4233. // Right
  4234. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4235. // Top
  4236. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4237. // Bottom
  4238. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4239. };
  4240. return Frustum;
  4241. }());
  4242. BABYLON.Frustum = Frustum;
  4243. var Space;
  4244. (function (Space) {
  4245. Space[Space["LOCAL"] = 0] = "LOCAL";
  4246. Space[Space["WORLD"] = 1] = "WORLD";
  4247. Space[Space["BONE"] = 2] = "BONE";
  4248. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4249. var Axis = (function () {
  4250. function Axis() {
  4251. }
  4252. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4253. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4254. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4255. return Axis;
  4256. }());
  4257. BABYLON.Axis = Axis;
  4258. ;
  4259. var BezierCurve = (function () {
  4260. function BezierCurve() {
  4261. }
  4262. /**
  4263. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4264. */
  4265. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4266. // Extract X (which is equal to time here)
  4267. var f0 = 1 - 3 * x2 + 3 * x1;
  4268. var f1 = 3 * x2 - 6 * x1;
  4269. var f2 = 3 * x1;
  4270. var refinedT = t;
  4271. for (var i = 0; i < 5; i++) {
  4272. var refinedT2 = refinedT * refinedT;
  4273. var refinedT3 = refinedT2 * refinedT;
  4274. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4275. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4276. refinedT -= (x - t) * slope;
  4277. refinedT = Math.min(1, Math.max(0, refinedT));
  4278. }
  4279. // Resolve cubic bezier for the given x
  4280. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4281. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4282. Math.pow(refinedT, 3);
  4283. };
  4284. return BezierCurve;
  4285. }());
  4286. BABYLON.BezierCurve = BezierCurve;
  4287. var Orientation;
  4288. (function (Orientation) {
  4289. Orientation[Orientation["CW"] = 0] = "CW";
  4290. Orientation[Orientation["CCW"] = 1] = "CCW";
  4291. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4292. var Angle = (function () {
  4293. /**
  4294. * Creates an Angle object of "radians" radians (float).
  4295. */
  4296. function Angle(radians) {
  4297. var _this = this;
  4298. /**
  4299. * Returns the Angle value in degrees (float).
  4300. */
  4301. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4302. /**
  4303. * Returns the Angle value in radians (float).
  4304. */
  4305. this.radians = function () { return _this._radians; };
  4306. this._radians = radians;
  4307. if (this._radians < 0.0)
  4308. this._radians += (2.0 * Math.PI);
  4309. }
  4310. /**
  4311. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4312. */
  4313. Angle.BetweenTwoPoints = function (a, b) {
  4314. var delta = b.subtract(a);
  4315. var theta = Math.atan2(delta.y, delta.x);
  4316. return new Angle(theta);
  4317. };
  4318. /**
  4319. * Returns a new Angle object from the passed float in radians.
  4320. */
  4321. Angle.FromRadians = function (radians) {
  4322. return new Angle(radians);
  4323. };
  4324. /**
  4325. * Returns a new Angle object from the passed float in degrees.
  4326. */
  4327. Angle.FromDegrees = function (degrees) {
  4328. return new Angle(degrees * Math.PI / 180.0);
  4329. };
  4330. return Angle;
  4331. }());
  4332. BABYLON.Angle = Angle;
  4333. var Arc2 = (function () {
  4334. /**
  4335. * Creates an Arc object from the three passed points : start, middle and end.
  4336. */
  4337. function Arc2(startPoint, midPoint, endPoint) {
  4338. this.startPoint = startPoint;
  4339. this.midPoint = midPoint;
  4340. this.endPoint = endPoint;
  4341. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4342. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4343. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4344. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4345. 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);
  4346. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4347. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4348. var a1 = this.startAngle.degrees();
  4349. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4350. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4351. // angles correction
  4352. if (a2 - a1 > +180.0)
  4353. a2 -= 360.0;
  4354. if (a2 - a1 < -180.0)
  4355. a2 += 360.0;
  4356. if (a3 - a2 > +180.0)
  4357. a3 -= 360.0;
  4358. if (a3 - a2 < -180.0)
  4359. a3 += 360.0;
  4360. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4361. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4362. }
  4363. return Arc2;
  4364. }());
  4365. BABYLON.Arc2 = Arc2;
  4366. var Path2 = (function () {
  4367. /**
  4368. * Creates a Path2 object from the starting 2D coordinates x and y.
  4369. */
  4370. function Path2(x, y) {
  4371. this._points = new Array();
  4372. this._length = 0.0;
  4373. this.closed = false;
  4374. this._points.push(new Vector2(x, y));
  4375. }
  4376. /**
  4377. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4378. * Returns the updated Path2.
  4379. */
  4380. Path2.prototype.addLineTo = function (x, y) {
  4381. if (closed) {
  4382. //Tools.Error("cannot add lines to closed paths");
  4383. return this;
  4384. }
  4385. var newPoint = new Vector2(x, y);
  4386. var previousPoint = this._points[this._points.length - 1];
  4387. this._points.push(newPoint);
  4388. this._length += newPoint.subtract(previousPoint).length();
  4389. return this;
  4390. };
  4391. /**
  4392. * 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.
  4393. * Returns the updated Path2.
  4394. */
  4395. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4396. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4397. if (closed) {
  4398. //Tools.Error("cannot add arcs to closed paths");
  4399. return this;
  4400. }
  4401. var startPoint = this._points[this._points.length - 1];
  4402. var midPoint = new Vector2(midX, midY);
  4403. var endPoint = new Vector2(endX, endY);
  4404. var arc = new Arc2(startPoint, midPoint, endPoint);
  4405. var increment = arc.angle.radians() / numberOfSegments;
  4406. if (arc.orientation === Orientation.CW)
  4407. increment *= -1;
  4408. var currentAngle = arc.startAngle.radians() + increment;
  4409. for (var i = 0; i < numberOfSegments; i++) {
  4410. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4411. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4412. this.addLineTo(x, y);
  4413. currentAngle += increment;
  4414. }
  4415. return this;
  4416. };
  4417. /**
  4418. * Closes the Path2.
  4419. * Returns the Path2.
  4420. */
  4421. Path2.prototype.close = function () {
  4422. this.closed = true;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns the Path2 total length (float).
  4427. */
  4428. Path2.prototype.length = function () {
  4429. var result = this._length;
  4430. if (!this.closed) {
  4431. var lastPoint = this._points[this._points.length - 1];
  4432. var firstPoint = this._points[0];
  4433. result += (firstPoint.subtract(lastPoint).length());
  4434. }
  4435. return result;
  4436. };
  4437. /**
  4438. * Returns the Path2 internal array of points.
  4439. */
  4440. Path2.prototype.getPoints = function () {
  4441. return this._points;
  4442. };
  4443. /**
  4444. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4445. */
  4446. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4447. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4448. //Tools.Error("normalized length position should be between 0 and 1.");
  4449. return Vector2.Zero();
  4450. }
  4451. var lengthPosition = normalizedLengthPosition * this.length();
  4452. var previousOffset = 0;
  4453. for (var i = 0; i < this._points.length; i++) {
  4454. var j = (i + 1) % this._points.length;
  4455. var a = this._points[i];
  4456. var b = this._points[j];
  4457. var bToA = b.subtract(a);
  4458. var nextOffset = (bToA.length() + previousOffset);
  4459. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4460. var dir = bToA.normalize();
  4461. var localOffset = lengthPosition - previousOffset;
  4462. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4463. }
  4464. previousOffset = nextOffset;
  4465. }
  4466. //Tools.Error("internal error");
  4467. return Vector2.Zero();
  4468. };
  4469. /**
  4470. * Returns a new Path2 starting at the coordinates (x, y).
  4471. */
  4472. Path2.StartingAt = function (x, y) {
  4473. return new Path2(x, y);
  4474. };
  4475. return Path2;
  4476. }());
  4477. BABYLON.Path2 = Path2;
  4478. var Path3D = (function () {
  4479. /**
  4480. * new Path3D(path, normal, raw)
  4481. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4482. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4483. * path : an array of Vector3, the curve axis of the Path3D
  4484. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4485. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4486. */
  4487. function Path3D(path, firstNormal, raw) {
  4488. this.path = path;
  4489. this._curve = new Array();
  4490. this._distances = new Array();
  4491. this._tangents = new Array();
  4492. this._normals = new Array();
  4493. this._binormals = new Array();
  4494. for (var p = 0; p < path.length; p++) {
  4495. this._curve[p] = path[p].clone(); // hard copy
  4496. }
  4497. this._raw = raw || false;
  4498. this._compute(firstNormal);
  4499. }
  4500. /**
  4501. * Returns the Path3D array of successive Vector3 designing its curve.
  4502. */
  4503. Path3D.prototype.getCurve = function () {
  4504. return this._curve;
  4505. };
  4506. /**
  4507. * Returns an array populated with tangent vectors on each Path3D curve point.
  4508. */
  4509. Path3D.prototype.getTangents = function () {
  4510. return this._tangents;
  4511. };
  4512. /**
  4513. * Returns an array populated with normal vectors on each Path3D curve point.
  4514. */
  4515. Path3D.prototype.getNormals = function () {
  4516. return this._normals;
  4517. };
  4518. /**
  4519. * Returns an array populated with binormal vectors on each Path3D curve point.
  4520. */
  4521. Path3D.prototype.getBinormals = function () {
  4522. return this._binormals;
  4523. };
  4524. /**
  4525. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4526. */
  4527. Path3D.prototype.getDistances = function () {
  4528. return this._distances;
  4529. };
  4530. /**
  4531. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4532. * Returns the same object updated.
  4533. */
  4534. Path3D.prototype.update = function (path, firstNormal) {
  4535. for (var p = 0; p < path.length; p++) {
  4536. this._curve[p].x = path[p].x;
  4537. this._curve[p].y = path[p].y;
  4538. this._curve[p].z = path[p].z;
  4539. }
  4540. this._compute(firstNormal);
  4541. return this;
  4542. };
  4543. // private function compute() : computes tangents, normals and binormals
  4544. Path3D.prototype._compute = function (firstNormal) {
  4545. var l = this._curve.length;
  4546. // first and last tangents
  4547. this._tangents[0] = this._getFirstNonNullVector(0);
  4548. if (!this._raw) {
  4549. this._tangents[0].normalize();
  4550. }
  4551. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4552. if (!this._raw) {
  4553. this._tangents[l - 1].normalize();
  4554. }
  4555. // normals and binormals at first point : arbitrary vector with _normalVector()
  4556. var tg0 = this._tangents[0];
  4557. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4558. this._normals[0] = pp0;
  4559. if (!this._raw) {
  4560. this._normals[0].normalize();
  4561. }
  4562. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4563. if (!this._raw) {
  4564. this._binormals[0].normalize();
  4565. }
  4566. this._distances[0] = 0.0;
  4567. // normals and binormals : next points
  4568. var prev; // previous vector (segment)
  4569. var cur; // current vector (segment)
  4570. var curTang; // current tangent
  4571. // previous normal
  4572. var prevBinor; // previous binormal
  4573. for (var i = 1; i < l; i++) {
  4574. // tangents
  4575. prev = this._getLastNonNullVector(i);
  4576. if (i < l - 1) {
  4577. cur = this._getFirstNonNullVector(i);
  4578. this._tangents[i] = prev.add(cur);
  4579. this._tangents[i].normalize();
  4580. }
  4581. this._distances[i] = this._distances[i - 1] + prev.length();
  4582. // normals and binormals
  4583. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4584. curTang = this._tangents[i];
  4585. prevBinor = this._binormals[i - 1];
  4586. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4587. if (!this._raw) {
  4588. this._normals[i].normalize();
  4589. }
  4590. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4591. if (!this._raw) {
  4592. this._binormals[i].normalize();
  4593. }
  4594. }
  4595. };
  4596. // private function getFirstNonNullVector(index)
  4597. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4598. Path3D.prototype._getFirstNonNullVector = function (index) {
  4599. var i = 1;
  4600. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4601. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4602. i++;
  4603. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4604. }
  4605. return nNVector;
  4606. };
  4607. // private function getLastNonNullVector(index)
  4608. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4609. Path3D.prototype._getLastNonNullVector = function (index) {
  4610. var i = 1;
  4611. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4612. while (nLVector.length() === 0 && index > i + 1) {
  4613. i++;
  4614. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4615. }
  4616. return nLVector;
  4617. };
  4618. // private function normalVector(v0, vt, va) :
  4619. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4620. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4621. Path3D.prototype._normalVector = function (v0, vt, va) {
  4622. var normal0;
  4623. var tgl = vt.length();
  4624. if (tgl === 0.0) {
  4625. tgl = 1.0;
  4626. }
  4627. if (va === undefined || va === null) {
  4628. var point;
  4629. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4630. point = new Vector3(0.0, -1.0, 0.0);
  4631. }
  4632. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4633. point = new Vector3(1.0, 0.0, 0.0);
  4634. }
  4635. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4636. point = new Vector3(0.0, 0.0, 1.0);
  4637. }
  4638. normal0 = Vector3.Cross(vt, point);
  4639. }
  4640. else {
  4641. normal0 = Vector3.Cross(vt, va);
  4642. Vector3.CrossToRef(normal0, vt, normal0);
  4643. }
  4644. normal0.normalize();
  4645. return normal0;
  4646. };
  4647. return Path3D;
  4648. }());
  4649. BABYLON.Path3D = Path3D;
  4650. var Curve3 = (function () {
  4651. /**
  4652. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4653. * A Curve3 is designed from a series of successive Vector3.
  4654. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4655. */
  4656. function Curve3(points) {
  4657. this._length = 0.0;
  4658. this._points = points;
  4659. this._length = this._computeLength(points);
  4660. }
  4661. /**
  4662. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4663. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4664. * @param v1 (Vector3) the control point
  4665. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4666. * @param nbPoints (integer) the wanted number of points in the curve
  4667. */
  4668. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4669. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4670. var bez = new Array();
  4671. var equation = function (t, val0, val1, val2) {
  4672. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4673. return res;
  4674. };
  4675. for (var i = 0; i <= nbPoints; i++) {
  4676. 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)));
  4677. }
  4678. return new Curve3(bez);
  4679. };
  4680. /**
  4681. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4682. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4683. * @param v1 (Vector3) the first control point
  4684. * @param v2 (Vector3) the second control point
  4685. * @param v3 (Vector3) the end point of the Cubic Bezier
  4686. * @param nbPoints (integer) the wanted number of points in the curve
  4687. */
  4688. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4689. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4690. var bez = new Array();
  4691. var equation = function (t, val0, val1, val2, val3) {
  4692. 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;
  4693. return res;
  4694. };
  4695. for (var i = 0; i <= nbPoints; i++) {
  4696. 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)));
  4697. }
  4698. return new Curve3(bez);
  4699. };
  4700. /**
  4701. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4702. * @param p1 (Vector3) the origin point of the Hermite Spline
  4703. * @param t1 (Vector3) the tangent vector at the origin point
  4704. * @param p2 (Vector3) the end point of the Hermite Spline
  4705. * @param t2 (Vector3) the tangent vector at the end point
  4706. * @param nbPoints (integer) the wanted number of points in the curve
  4707. */
  4708. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4709. var hermite = new Array();
  4710. var step = 1.0 / nbPoints;
  4711. for (var i = 0; i <= nbPoints; i++) {
  4712. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4713. }
  4714. return new Curve3(hermite);
  4715. };
  4716. /**
  4717. * Returns a Curve3 object along a CatmullRom Spline curve :
  4718. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4719. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4720. */
  4721. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4722. var totalPoints = new Array();
  4723. totalPoints.push(points[0].clone());
  4724. Array.prototype.push.apply(totalPoints, points);
  4725. totalPoints.push(points[points.length - 1].clone());
  4726. var catmullRom = new Array();
  4727. var step = 1.0 / nbPoints;
  4728. for (var i = 0; i < totalPoints.length - 3; i++) {
  4729. var amount = 0.0;
  4730. for (var c = 0; c < nbPoints; c++) {
  4731. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4732. amount += step;
  4733. }
  4734. }
  4735. i--;
  4736. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4737. return new Curve3(catmullRom);
  4738. };
  4739. /**
  4740. * Returns the Curve3 stored array of successive Vector3
  4741. */
  4742. Curve3.prototype.getPoints = function () {
  4743. return this._points;
  4744. };
  4745. /**
  4746. * Returns the computed length (float) of the curve.
  4747. */
  4748. Curve3.prototype.length = function () {
  4749. return this._length;
  4750. };
  4751. /**
  4752. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4753. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4754. * curveA and curveB keep unchanged.
  4755. */
  4756. Curve3.prototype.continue = function (curve) {
  4757. var lastPoint = this._points[this._points.length - 1];
  4758. var continuedPoints = this._points.slice();
  4759. var curvePoints = curve.getPoints();
  4760. for (var i = 1; i < curvePoints.length; i++) {
  4761. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4762. }
  4763. var continuedCurve = new Curve3(continuedPoints);
  4764. return continuedCurve;
  4765. };
  4766. Curve3.prototype._computeLength = function (path) {
  4767. var l = 0;
  4768. for (var i = 1; i < path.length; i++) {
  4769. l += (path[i].subtract(path[i - 1])).length();
  4770. }
  4771. return l;
  4772. };
  4773. return Curve3;
  4774. }());
  4775. BABYLON.Curve3 = Curve3;
  4776. // Vertex formats
  4777. var PositionNormalVertex = (function () {
  4778. function PositionNormalVertex(position, normal) {
  4779. if (position === void 0) { position = Vector3.Zero(); }
  4780. if (normal === void 0) { normal = Vector3.Up(); }
  4781. this.position = position;
  4782. this.normal = normal;
  4783. }
  4784. PositionNormalVertex.prototype.clone = function () {
  4785. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4786. };
  4787. return PositionNormalVertex;
  4788. }());
  4789. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4790. var PositionNormalTextureVertex = (function () {
  4791. function PositionNormalTextureVertex(position, normal, uv) {
  4792. if (position === void 0) { position = Vector3.Zero(); }
  4793. if (normal === void 0) { normal = Vector3.Up(); }
  4794. if (uv === void 0) { uv = Vector2.Zero(); }
  4795. this.position = position;
  4796. this.normal = normal;
  4797. this.uv = uv;
  4798. }
  4799. PositionNormalTextureVertex.prototype.clone = function () {
  4800. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4801. };
  4802. return PositionNormalTextureVertex;
  4803. }());
  4804. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4805. // Temporary pre-allocated objects for engine internal use
  4806. // usage in any internal function :
  4807. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4808. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4809. var Tmp = (function () {
  4810. function Tmp() {
  4811. }
  4812. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4813. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4814. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4815. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4816. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4817. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4818. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4819. Matrix.Zero(), Matrix.Zero(),
  4820. Matrix.Zero(), Matrix.Zero(),
  4821. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4822. return Tmp;
  4823. }());
  4824. BABYLON.Tmp = Tmp;
  4825. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4826. var MathTmp = (function () {
  4827. function MathTmp() {
  4828. }
  4829. MathTmp.Vector3 = [Vector3.Zero()];
  4830. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4831. MathTmp.Quaternion = [Quaternion.Zero()];
  4832. return MathTmp;
  4833. }());
  4834. })(BABYLON || (BABYLON = {}));
  4835. //# sourceMappingURL=babylon.math.js.map
  4836. var BABYLON;
  4837. (function (BABYLON) {
  4838. var Scalar = (function () {
  4839. function Scalar() {
  4840. }
  4841. /**
  4842. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4843. */
  4844. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4845. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4846. var num = a - b;
  4847. return -epsilon <= num && num <= epsilon;
  4848. };
  4849. /**
  4850. * Returns a string : the upper case translation of the number i to hexadecimal.
  4851. */
  4852. Scalar.ToHex = function (i) {
  4853. var str = i.toString(16);
  4854. if (i <= 15) {
  4855. return ("0" + str).toUpperCase();
  4856. }
  4857. return str.toUpperCase();
  4858. };
  4859. /**
  4860. * Returns -1 if value is negative and +1 is value is positive.
  4861. * Returns the value itself if it's equal to zero.
  4862. */
  4863. Scalar.Sign = function (value) {
  4864. value = +value; // convert to a number
  4865. if (value === 0 || isNaN(value))
  4866. return value;
  4867. return value > 0 ? 1 : -1;
  4868. };
  4869. /**
  4870. * Returns the value itself if it's between min and max.
  4871. * Returns min if the value is lower than min.
  4872. * Returns max if the value is greater than max.
  4873. */
  4874. Scalar.Clamp = function (value, min, max) {
  4875. if (min === void 0) { min = 0; }
  4876. if (max === void 0) { max = 1; }
  4877. return Math.min(max, Math.max(min, value));
  4878. };
  4879. /**
  4880. * Returns the log2 of value.
  4881. */
  4882. Scalar.Log2 = function (value) {
  4883. return Math.log(value) * Math.LOG2E;
  4884. };
  4885. /**
  4886. * Loops the value, so that it is never larger than length and never smaller than 0.
  4887. *
  4888. * This is similar to the modulo operator but it works with floating point numbers.
  4889. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4890. * With t = 5 and length = 2.5, the result would be 0.0.
  4891. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4892. */
  4893. Scalar.Repeat = function (value, length) {
  4894. return value - Math.floor(value / length) * length;
  4895. };
  4896. /**
  4897. * Normalize the value between 0.0 and 1.0 using min and max values
  4898. */
  4899. Scalar.Normalize = function (value, min, max) {
  4900. return (value - min) / (max - min);
  4901. };
  4902. /**
  4903. * Denormalize the value from 0.0 and 1.0 using min and max values
  4904. */
  4905. Scalar.Denormalize = function (normalized, min, max) {
  4906. return (normalized * (max - min) + min);
  4907. };
  4908. /**
  4909. * Calculates the shortest difference between two given angles given in degrees.
  4910. */
  4911. Scalar.DeltaAngle = function (current, target) {
  4912. var num = Scalar.Repeat(target - current, 360.0);
  4913. if (num > 180.0) {
  4914. num -= 360.0;
  4915. }
  4916. return num;
  4917. };
  4918. /**
  4919. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4920. *
  4921. * The returned value will move back and forth between 0 and length
  4922. */
  4923. Scalar.PingPong = function (tx, length) {
  4924. var t = Scalar.Repeat(tx, length * 2.0);
  4925. return length - Math.abs(t - length);
  4926. };
  4927. /**
  4928. * Interpolates between min and max with smoothing at the limits.
  4929. *
  4930. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4931. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4932. */
  4933. Scalar.SmoothStep = function (from, to, tx) {
  4934. var t = Scalar.Clamp(tx);
  4935. t = -2.0 * t * t * t + 3.0 * t * t;
  4936. return to * t + from * (1.0 - t);
  4937. };
  4938. /**
  4939. * Moves a value current towards target.
  4940. *
  4941. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4942. * Negative values of maxDelta pushes the value away from target.
  4943. */
  4944. Scalar.MoveTowards = function (current, target, maxDelta) {
  4945. var result = 0;
  4946. if (Math.abs(target - current) <= maxDelta) {
  4947. result = target;
  4948. }
  4949. else {
  4950. result = current + Scalar.Sign(target - current) * maxDelta;
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4956. *
  4957. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4958. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4959. */
  4960. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4961. var num = Scalar.DeltaAngle(current, target);
  4962. var result = 0;
  4963. if (-maxDelta < num && num < maxDelta) {
  4964. result = target;
  4965. }
  4966. else {
  4967. target = current + num;
  4968. result = Scalar.MoveTowards(current, target, maxDelta);
  4969. }
  4970. return result;
  4971. };
  4972. /**
  4973. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4974. */
  4975. Scalar.Lerp = function (start, end, amount) {
  4976. return start + ((end - start) * amount);
  4977. };
  4978. /**
  4979. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4980. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4981. */
  4982. Scalar.LerpAngle = function (start, end, amount) {
  4983. var num = Scalar.Repeat(end - start, 360.0);
  4984. if (num > 180.0) {
  4985. num -= 360.0;
  4986. }
  4987. return start + num * Scalar.Clamp(amount);
  4988. };
  4989. /**
  4990. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4991. */
  4992. Scalar.InverseLerp = function (a, b, value) {
  4993. var result = 0;
  4994. if (a != b) {
  4995. result = Scalar.Clamp((value - a) / (b - a));
  4996. }
  4997. else {
  4998. result = 0.0;
  4999. }
  5000. return result;
  5001. };
  5002. /**
  5003. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5004. */
  5005. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5006. var squared = amount * amount;
  5007. var cubed = amount * squared;
  5008. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5009. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5010. var part3 = (cubed - (2.0 * squared)) + amount;
  5011. var part4 = cubed - squared;
  5012. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5013. };
  5014. /**
  5015. * Returns a random float number between and min and max values
  5016. */
  5017. Scalar.RandomRange = function (min, max) {
  5018. if (min === max)
  5019. return min;
  5020. return ((Math.random() * (max - min)) + min);
  5021. };
  5022. /**
  5023. * This function returns percentage of a number in a given range.
  5024. *
  5025. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5026. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5027. */
  5028. Scalar.RangeToPercent = function (number, min, max) {
  5029. return ((number - min) / (max - min));
  5030. };
  5031. /**
  5032. * This function returns number that corresponds to the percentage in a given range.
  5033. *
  5034. * PercentToRange(0.34,0,100) will return 34.
  5035. */
  5036. Scalar.PercentToRange = function (percent, min, max) {
  5037. return ((max - min) * percent + min);
  5038. };
  5039. return Scalar;
  5040. }());
  5041. BABYLON.Scalar = Scalar;
  5042. })(BABYLON || (BABYLON = {}));
  5043. //# sourceMappingURL=babylon.math.scalar.js.map
  5044. //# sourceMappingURL=babylon.mixins.js.map
  5045. var BABYLON;
  5046. (function (BABYLON) {
  5047. var __decoratorInitialStore = {};
  5048. var __mergedStore = {};
  5049. var _copySource = function (creationFunction, source, instanciate) {
  5050. var destination = creationFunction();
  5051. // Tags
  5052. if (BABYLON.Tags) {
  5053. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5054. }
  5055. var classStore = getMergedStore(destination);
  5056. // Properties
  5057. for (var property in classStore) {
  5058. var propertyDescriptor = classStore[property];
  5059. var sourceProperty = source[property];
  5060. var propertyType = propertyDescriptor.type;
  5061. if (sourceProperty !== undefined && sourceProperty !== null) {
  5062. switch (propertyType) {
  5063. case 0: // Value
  5064. case 6:// Mesh reference
  5065. destination[property] = sourceProperty;
  5066. break;
  5067. case 1: // Texture
  5068. case 2: // Color3
  5069. case 3: // FresnelParameters
  5070. case 4: // Vector2
  5071. case 5: // Vector3
  5072. case 7:// Color Curves
  5073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5074. break;
  5075. }
  5076. }
  5077. }
  5078. return destination;
  5079. };
  5080. function getDirectStore(target) {
  5081. var classKey = target.getClassName();
  5082. if (!__decoratorInitialStore[classKey]) {
  5083. __decoratorInitialStore[classKey] = {};
  5084. }
  5085. return __decoratorInitialStore[classKey];
  5086. }
  5087. /**
  5088. * Return the list of properties flagged as serializable
  5089. * @param target: host object
  5090. */
  5091. function getMergedStore(target) {
  5092. var classKey = target.getClassName();
  5093. if (__mergedStore[classKey]) {
  5094. return __mergedStore[classKey];
  5095. }
  5096. __mergedStore[classKey] = {};
  5097. var store = __mergedStore[classKey];
  5098. var currentTarget = target;
  5099. var currentKey = classKey;
  5100. while (currentKey) {
  5101. var initialStore = __decoratorInitialStore[currentKey];
  5102. for (var property in initialStore) {
  5103. store[property] = initialStore[property];
  5104. }
  5105. var parent_1 = void 0;
  5106. var done = false;
  5107. do {
  5108. parent_1 = Object.getPrototypeOf(currentTarget);
  5109. if (!parent_1.getClassName) {
  5110. done = true;
  5111. break;
  5112. }
  5113. if (parent_1.getClassName() !== currentKey) {
  5114. break;
  5115. }
  5116. currentTarget = parent_1;
  5117. } while (parent_1);
  5118. if (done) {
  5119. break;
  5120. }
  5121. currentKey = parent_1.getClassName();
  5122. currentTarget = parent_1;
  5123. }
  5124. return store;
  5125. }
  5126. function generateSerializableMember(type, sourceName) {
  5127. return function (target, propertyKey) {
  5128. var classStore = getDirectStore(target);
  5129. if (!classStore[propertyKey]) {
  5130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5131. }
  5132. };
  5133. }
  5134. function generateExpandMember(setCallback, targetKey) {
  5135. return function (target, propertyKey) {
  5136. var key = targetKey || ("_" + propertyKey);
  5137. Object.defineProperty(target, propertyKey, {
  5138. get: function () {
  5139. return this[key];
  5140. },
  5141. set: function (value) {
  5142. if (this[key] === value) {
  5143. return;
  5144. }
  5145. this[key] = value;
  5146. target[setCallback].apply(this);
  5147. },
  5148. enumerable: true,
  5149. configurable: true
  5150. });
  5151. };
  5152. }
  5153. function expandToProperty(callback, targetKey) {
  5154. return generateExpandMember(callback, targetKey);
  5155. }
  5156. BABYLON.expandToProperty = expandToProperty;
  5157. function serialize(sourceName) {
  5158. return generateSerializableMember(0, sourceName); // value member
  5159. }
  5160. BABYLON.serialize = serialize;
  5161. function serializeAsTexture(sourceName) {
  5162. return generateSerializableMember(1, sourceName); // texture member
  5163. }
  5164. BABYLON.serializeAsTexture = serializeAsTexture;
  5165. function serializeAsColor3(sourceName) {
  5166. return generateSerializableMember(2, sourceName); // color3 member
  5167. }
  5168. BABYLON.serializeAsColor3 = serializeAsColor3;
  5169. function serializeAsFresnelParameters(sourceName) {
  5170. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5171. }
  5172. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5173. function serializeAsVector2(sourceName) {
  5174. return generateSerializableMember(4, sourceName); // vector2 member
  5175. }
  5176. BABYLON.serializeAsVector2 = serializeAsVector2;
  5177. function serializeAsVector3(sourceName) {
  5178. return generateSerializableMember(5, sourceName); // vector3 member
  5179. }
  5180. BABYLON.serializeAsVector3 = serializeAsVector3;
  5181. function serializeAsMeshReference(sourceName) {
  5182. return generateSerializableMember(6, sourceName); // mesh reference member
  5183. }
  5184. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5185. function serializeAsColorCurves(sourceName) {
  5186. return generateSerializableMember(7, sourceName); // color curves
  5187. }
  5188. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5189. function serializeAsColor4(sourceName) {
  5190. return generateSerializableMember(8, sourceName); // color 4
  5191. }
  5192. BABYLON.serializeAsColor4 = serializeAsColor4;
  5193. function serializeAsImageProcessingConfiguration(sourceName) {
  5194. return generateSerializableMember(9, sourceName); // image processing
  5195. }
  5196. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5197. var SerializationHelper = (function () {
  5198. function SerializationHelper() {
  5199. }
  5200. SerializationHelper.Serialize = function (entity, serializationObject) {
  5201. if (!serializationObject) {
  5202. serializationObject = {};
  5203. }
  5204. // Tags
  5205. if (BABYLON.Tags) {
  5206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5207. }
  5208. var serializedProperties = getMergedStore(entity);
  5209. // Properties
  5210. for (var property in serializedProperties) {
  5211. var propertyDescriptor = serializedProperties[property];
  5212. var targetPropertyName = propertyDescriptor.sourceName || property;
  5213. var propertyType = propertyDescriptor.type;
  5214. var sourceProperty = entity[property];
  5215. if (sourceProperty !== undefined && sourceProperty !== null) {
  5216. switch (propertyType) {
  5217. case 0:// Value
  5218. serializationObject[targetPropertyName] = sourceProperty;
  5219. break;
  5220. case 1:// Texture
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 2:// Color3
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 3:// FresnelParameters
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. case 4:// Vector2
  5230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5231. break;
  5232. case 5:// Vector3
  5233. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5234. break;
  5235. case 6:// Mesh reference
  5236. serializationObject[targetPropertyName] = sourceProperty.id;
  5237. break;
  5238. case 7:// Color Curves
  5239. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5240. break;
  5241. case 8:// Color 4
  5242. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5243. break;
  5244. case 9:// Image Processing
  5245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5246. break;
  5247. }
  5248. }
  5249. }
  5250. return serializationObject;
  5251. };
  5252. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5253. var destination = creationFunction();
  5254. // Tags
  5255. if (BABYLON.Tags) {
  5256. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5257. }
  5258. var classStore = getMergedStore(destination);
  5259. // Properties
  5260. for (var property in classStore) {
  5261. var propertyDescriptor = classStore[property];
  5262. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5263. var propertyType = propertyDescriptor.type;
  5264. if (sourceProperty !== undefined && sourceProperty !== null) {
  5265. var dest = destination;
  5266. switch (propertyType) {
  5267. case 0:// Value
  5268. dest[property] = sourceProperty;
  5269. break;
  5270. case 1:// Texture
  5271. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5272. break;
  5273. case 2:// Color3
  5274. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5275. break;
  5276. case 3:// FresnelParameters
  5277. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5278. break;
  5279. case 4:// Vector2
  5280. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5281. break;
  5282. case 5:// Vector3
  5283. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5284. break;
  5285. case 6:// Mesh reference
  5286. dest[property] = scene.getLastMeshByID(sourceProperty);
  5287. break;
  5288. case 7:// Color Curves
  5289. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5290. break;
  5291. case 8:// Color 4
  5292. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5293. break;
  5294. case 9:// Image Processing
  5295. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5296. break;
  5297. }
  5298. }
  5299. }
  5300. return destination;
  5301. };
  5302. SerializationHelper.Clone = function (creationFunction, source) {
  5303. return _copySource(creationFunction, source, false);
  5304. };
  5305. SerializationHelper.Instanciate = function (creationFunction, source) {
  5306. return _copySource(creationFunction, source, true);
  5307. };
  5308. return SerializationHelper;
  5309. }());
  5310. BABYLON.SerializationHelper = SerializationHelper;
  5311. })(BABYLON || (BABYLON = {}));
  5312. //# sourceMappingURL=babylon.decorators.js.map
  5313. var BABYLON;
  5314. (function (BABYLON) {
  5315. /**
  5316. * A class serves as a medium between the observable and its observers
  5317. */
  5318. var EventState = (function () {
  5319. /**
  5320. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5321. */
  5322. function EventState(mask, skipNextObservers) {
  5323. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5324. this.initalize(mask, skipNextObservers);
  5325. }
  5326. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5327. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5328. this.mask = mask;
  5329. this.skipNextObservers = skipNextObservers;
  5330. return this;
  5331. };
  5332. return EventState;
  5333. }());
  5334. BABYLON.EventState = EventState;
  5335. /**
  5336. * Represent an Observer registered to a given Observable object.
  5337. */
  5338. var Observer = (function () {
  5339. function Observer(callback, mask, scope) {
  5340. if (scope === void 0) { scope = null; }
  5341. this.callback = callback;
  5342. this.mask = mask;
  5343. this.scope = scope;
  5344. }
  5345. return Observer;
  5346. }());
  5347. BABYLON.Observer = Observer;
  5348. /**
  5349. * Represent a list of observers registered to multiple Observables object.
  5350. */
  5351. var MultiObserver = (function () {
  5352. function MultiObserver() {
  5353. }
  5354. MultiObserver.prototype.dispose = function () {
  5355. for (var index = 0; index < this._observers.length; index++) {
  5356. this._observables[index].remove(this._observers[index]);
  5357. }
  5358. this._observers = null;
  5359. this._observables = null;
  5360. };
  5361. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5362. if (mask === void 0) { mask = -1; }
  5363. if (scope === void 0) { scope = null; }
  5364. var result = new MultiObserver();
  5365. result._observers = new Array();
  5366. result._observables = observables;
  5367. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5368. var observable = observables_1[_i];
  5369. result._observers.push(observable.add(callback, mask, false, scope));
  5370. }
  5371. return result;
  5372. };
  5373. return MultiObserver;
  5374. }());
  5375. BABYLON.MultiObserver = MultiObserver;
  5376. /**
  5377. * The Observable class is a simple implementation of the Observable pattern.
  5378. * 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.
  5379. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5380. * 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).
  5381. * 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.
  5382. */
  5383. var Observable = (function () {
  5384. function Observable(onObserverAdded) {
  5385. this._observers = new Array();
  5386. this._eventState = new EventState(0);
  5387. this._onObserverAdded = onObserverAdded;
  5388. }
  5389. /**
  5390. * Create a new Observer with the specified callback
  5391. * @param callback the callback that will be executed for that Observer
  5392. * @param mask the mask used to filter observers
  5393. * @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.
  5394. * @param scope optional scope for the callback to be called from
  5395. */
  5396. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5397. if (mask === void 0) { mask = -1; }
  5398. if (insertFirst === void 0) { insertFirst = false; }
  5399. if (scope === void 0) { scope = null; }
  5400. if (!callback) {
  5401. return null;
  5402. }
  5403. var observer = new Observer(callback, mask, scope);
  5404. if (insertFirst) {
  5405. this._observers.unshift(observer);
  5406. }
  5407. else {
  5408. this._observers.push(observer);
  5409. }
  5410. if (this._onObserverAdded) {
  5411. this._onObserverAdded(observer);
  5412. }
  5413. return observer;
  5414. };
  5415. /**
  5416. * Remove an Observer from the Observable object
  5417. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5418. */
  5419. Observable.prototype.remove = function (observer) {
  5420. var index = this._observers.indexOf(observer);
  5421. if (index !== -1) {
  5422. this._observers.splice(index, 1);
  5423. return true;
  5424. }
  5425. return false;
  5426. };
  5427. /**
  5428. * Remove a callback from the Observable object
  5429. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5430. */
  5431. Observable.prototype.removeCallback = function (callback) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. if (this._observers[index].callback === callback) {
  5434. this._observers.splice(index, 1);
  5435. return true;
  5436. }
  5437. }
  5438. return false;
  5439. };
  5440. /**
  5441. * Notify all Observers by calling their respective callback with the given data
  5442. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5443. * @param eventData
  5444. * @param mask
  5445. */
  5446. Observable.prototype.notifyObservers = function (eventData, mask) {
  5447. if (mask === void 0) { mask = -1; }
  5448. var state = this._eventState;
  5449. state.mask = mask;
  5450. state.skipNextObservers = false;
  5451. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5452. var obs = _a[_i];
  5453. if (obs.mask & mask) {
  5454. if (obs.scope) {
  5455. obs.callback.apply(obs.scope, [eventData, state]);
  5456. }
  5457. else {
  5458. obs.callback(eventData, state);
  5459. }
  5460. }
  5461. if (state.skipNextObservers) {
  5462. return false;
  5463. }
  5464. }
  5465. return true;
  5466. };
  5467. /**
  5468. * Notify a specific observer
  5469. * @param eventData
  5470. * @param mask
  5471. */
  5472. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5473. if (mask === void 0) { mask = -1; }
  5474. var state = this._eventState;
  5475. state.mask = mask;
  5476. state.skipNextObservers = false;
  5477. observer.callback(eventData, state);
  5478. };
  5479. /**
  5480. * return true is the Observable has at least one Observer registered
  5481. */
  5482. Observable.prototype.hasObservers = function () {
  5483. return this._observers.length > 0;
  5484. };
  5485. /**
  5486. * Clear the list of observers
  5487. */
  5488. Observable.prototype.clear = function () {
  5489. this._observers = new Array();
  5490. this._onObserverAdded = null;
  5491. };
  5492. /**
  5493. * Clone the current observable
  5494. */
  5495. Observable.prototype.clone = function () {
  5496. var result = new Observable();
  5497. result._observers = this._observers.slice(0);
  5498. return result;
  5499. };
  5500. /**
  5501. * Does this observable handles observer registered with a given mask
  5502. * @param {number} trigger - the mask to be tested
  5503. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5504. **/
  5505. Observable.prototype.hasSpecificMask = function (mask) {
  5506. if (mask === void 0) { mask = -1; }
  5507. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5508. var obs = _a[_i];
  5509. if (obs.mask & mask || obs.mask === mask) {
  5510. return true;
  5511. }
  5512. }
  5513. return false;
  5514. };
  5515. return Observable;
  5516. }());
  5517. BABYLON.Observable = Observable;
  5518. })(BABYLON || (BABYLON = {}));
  5519. //# sourceMappingURL=babylon.observable.js.map
  5520. var BABYLON;
  5521. (function (BABYLON) {
  5522. var SmartArray = (function () {
  5523. function SmartArray(capacity) {
  5524. this.length = 0;
  5525. this._duplicateId = 0;
  5526. this.data = new Array(capacity);
  5527. this._id = SmartArray._GlobalId++;
  5528. }
  5529. SmartArray.prototype.push = function (value) {
  5530. this.data[this.length++] = value;
  5531. if (this.length > this.data.length) {
  5532. this.data.length *= 2;
  5533. }
  5534. if (!value.__smartArrayFlags) {
  5535. value.__smartArrayFlags = {};
  5536. }
  5537. value.__smartArrayFlags[this._id] = this._duplicateId;
  5538. };
  5539. SmartArray.prototype.forEach = function (func) {
  5540. for (var index = 0; index < this.length; index++) {
  5541. func(this.data[index]);
  5542. }
  5543. };
  5544. SmartArray.prototype.pushNoDuplicate = function (value) {
  5545. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5546. return false;
  5547. }
  5548. this.push(value);
  5549. return true;
  5550. };
  5551. SmartArray.prototype.sort = function (compareFn) {
  5552. this.data.sort(compareFn);
  5553. };
  5554. SmartArray.prototype.reset = function () {
  5555. this.length = 0;
  5556. this._duplicateId++;
  5557. };
  5558. SmartArray.prototype.dispose = function () {
  5559. this.reset();
  5560. if (this.data) {
  5561. this.data.length = 0;
  5562. this.data = null;
  5563. }
  5564. };
  5565. SmartArray.prototype.concat = function (array) {
  5566. if (array.length === 0) {
  5567. return;
  5568. }
  5569. if (this.length + array.length > this.data.length) {
  5570. this.data.length = (this.length + array.length) * 2;
  5571. }
  5572. for (var index = 0; index < array.length; index++) {
  5573. this.data[this.length++] = (array.data || array)[index];
  5574. }
  5575. };
  5576. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5577. if (array.length === 0) {
  5578. return;
  5579. }
  5580. if (this.length + array.length > this.data.length) {
  5581. this.data.length = (this.length + array.length) * 2;
  5582. }
  5583. for (var index = 0; index < array.length; index++) {
  5584. var item = (array.data || array)[index];
  5585. this.pushNoDuplicate(item);
  5586. }
  5587. };
  5588. SmartArray.prototype.indexOf = function (value) {
  5589. var position = this.data.indexOf(value);
  5590. if (position >= this.length) {
  5591. return -1;
  5592. }
  5593. return position;
  5594. };
  5595. SmartArray.prototype.contains = function (value) {
  5596. return this.data.indexOf(value) !== -1;
  5597. };
  5598. // Statics
  5599. SmartArray._GlobalId = 0;
  5600. return SmartArray;
  5601. }());
  5602. BABYLON.SmartArray = SmartArray;
  5603. })(BABYLON || (BABYLON = {}));
  5604. //# sourceMappingURL=babylon.smartArray.js.map
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. // Screenshots
  5608. var screenshotCanvas;
  5609. var cloneValue = function (source, destinationObject) {
  5610. if (!source)
  5611. return null;
  5612. if (source instanceof BABYLON.Mesh) {
  5613. return null;
  5614. }
  5615. if (source instanceof BABYLON.SubMesh) {
  5616. return source.clone(destinationObject);
  5617. }
  5618. else if (source.clone) {
  5619. return source.clone();
  5620. }
  5621. return null;
  5622. };
  5623. var Tools = (function () {
  5624. function Tools() {
  5625. }
  5626. ;
  5627. /**
  5628. * Interpolates between a and b via alpha
  5629. * @param a The lower value (returned when alpha = 0)
  5630. * @param b The upper value (returned when alpha = 1)
  5631. * @param alpha The interpolation-factor
  5632. * @return The mixed value
  5633. */
  5634. Tools.Mix = function (a, b, alpha) {
  5635. return a * (1 - alpha) + b * alpha;
  5636. };
  5637. Tools.Instantiate = function (className) {
  5638. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5639. return Tools.RegisteredExternalClasses[className];
  5640. }
  5641. var arr = className.split(".");
  5642. var fn = (window || this);
  5643. for (var i = 0, len = arr.length; i < len; i++) {
  5644. fn = fn[arr[i]];
  5645. }
  5646. if (typeof fn !== "function") {
  5647. return null;
  5648. }
  5649. return fn;
  5650. };
  5651. Tools.SetImmediate = function (action) {
  5652. if (window.setImmediate) {
  5653. window.setImmediate(action);
  5654. }
  5655. else {
  5656. setTimeout(action, 1);
  5657. }
  5658. };
  5659. Tools.IsExponentOfTwo = function (value) {
  5660. var count = 1;
  5661. do {
  5662. count *= 2;
  5663. } while (count < value);
  5664. return count === value;
  5665. };
  5666. /**
  5667. * Find the next highest power of two.
  5668. * @param x Number to start search from.
  5669. * @return Next highest power of two.
  5670. */
  5671. Tools.CeilingPOT = function (x) {
  5672. x--;
  5673. x |= x >> 1;
  5674. x |= x >> 2;
  5675. x |= x >> 4;
  5676. x |= x >> 8;
  5677. x |= x >> 16;
  5678. x++;
  5679. return x;
  5680. };
  5681. /**
  5682. * Find the next lowest power of two.
  5683. * @param x Number to start search from.
  5684. * @return Next lowest power of two.
  5685. */
  5686. Tools.FloorPOT = function (x) {
  5687. x = x | (x >> 1);
  5688. x = x | (x >> 2);
  5689. x = x | (x >> 4);
  5690. x = x | (x >> 8);
  5691. x = x | (x >> 16);
  5692. return x - (x >> 1);
  5693. };
  5694. /**
  5695. * Find the nearest power of two.
  5696. * @param x Number to start search from.
  5697. * @return Next nearest power of two.
  5698. */
  5699. Tools.NearestPOT = function (x) {
  5700. var c = Tools.CeilingPOT(x);
  5701. var f = Tools.FloorPOT(x);
  5702. return (c - x) > (x - f) ? f : c;
  5703. };
  5704. Tools.GetExponentOfTwo = function (value, max, mode) {
  5705. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5706. var pot;
  5707. switch (mode) {
  5708. case BABYLON.Engine.SCALEMODE_FLOOR:
  5709. pot = Tools.FloorPOT(value);
  5710. break;
  5711. case BABYLON.Engine.SCALEMODE_NEAREST:
  5712. pot = Tools.NearestPOT(value);
  5713. break;
  5714. case BABYLON.Engine.SCALEMODE_CEILING:
  5715. pot = Tools.CeilingPOT(value);
  5716. break;
  5717. }
  5718. return Math.min(pot, max);
  5719. };
  5720. Tools.GetFilename = function (path) {
  5721. var index = path.lastIndexOf("/");
  5722. if (index < 0)
  5723. return path;
  5724. return path.substring(index + 1);
  5725. };
  5726. Tools.GetDOMTextContent = function (element) {
  5727. var result = "";
  5728. var child = element.firstChild;
  5729. while (child) {
  5730. if (child.nodeType === 3) {
  5731. result += child.textContent;
  5732. }
  5733. child = child.nextSibling;
  5734. }
  5735. return result;
  5736. };
  5737. Tools.ToDegrees = function (angle) {
  5738. return angle * 180 / Math.PI;
  5739. };
  5740. Tools.ToRadians = function (angle) {
  5741. return angle * Math.PI / 180;
  5742. };
  5743. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5744. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5745. var output = "";
  5746. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5747. var i = 0;
  5748. var bytes = new Uint8Array(buffer);
  5749. while (i < bytes.length) {
  5750. chr1 = bytes[i++];
  5751. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5752. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5753. enc1 = chr1 >> 2;
  5754. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5755. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5756. enc4 = chr3 & 63;
  5757. if (isNaN(chr2)) {
  5758. enc3 = enc4 = 64;
  5759. }
  5760. else if (isNaN(chr3)) {
  5761. enc4 = 64;
  5762. }
  5763. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5764. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5765. }
  5766. return "data:image/png;base64," + output;
  5767. };
  5768. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5769. if (bias === void 0) { bias = null; }
  5770. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5771. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5772. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5773. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5774. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5775. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5776. }
  5777. if (bias) {
  5778. minimum.x -= minimum.x * bias.x + bias.y;
  5779. minimum.y -= minimum.y * bias.x + bias.y;
  5780. minimum.z -= minimum.z * bias.x + bias.y;
  5781. maximum.x += maximum.x * bias.x + bias.y;
  5782. maximum.y += maximum.y * bias.x + bias.y;
  5783. maximum.z += maximum.z * bias.x + bias.y;
  5784. }
  5785. return {
  5786. minimum: minimum,
  5787. maximum: maximum
  5788. };
  5789. };
  5790. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5791. if (bias === void 0) { bias = null; }
  5792. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5793. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5794. if (!stride) {
  5795. stride = 3;
  5796. }
  5797. for (var index = start; index < start + count; index++) {
  5798. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5799. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5800. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5801. }
  5802. if (bias) {
  5803. minimum.x -= minimum.x * bias.x + bias.y;
  5804. minimum.y -= minimum.y * bias.x + bias.y;
  5805. minimum.z -= minimum.z * bias.x + bias.y;
  5806. maximum.x += maximum.x * bias.x + bias.y;
  5807. maximum.y += maximum.y * bias.x + bias.y;
  5808. maximum.z += maximum.z * bias.x + bias.y;
  5809. }
  5810. return {
  5811. minimum: minimum,
  5812. maximum: maximum
  5813. };
  5814. };
  5815. Tools.Vector2ArrayFeeder = function (array) {
  5816. return function (index) {
  5817. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5818. var length = isFloatArray ? array.length / 2 : array.length;
  5819. if (index >= length) {
  5820. return null;
  5821. }
  5822. if (isFloatArray) {
  5823. var fa = array;
  5824. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5825. }
  5826. var a = array;
  5827. return a[index];
  5828. };
  5829. };
  5830. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5831. if (bias === void 0) { bias = null; }
  5832. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5833. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5834. var i = 0;
  5835. var cur = feeder(i++);
  5836. while (cur) {
  5837. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5838. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5839. cur = feeder(i++);
  5840. }
  5841. if (bias) {
  5842. minimum.x -= minimum.x * bias.x + bias.y;
  5843. minimum.y -= minimum.y * bias.x + bias.y;
  5844. maximum.x += maximum.x * bias.x + bias.y;
  5845. maximum.y += maximum.y * bias.x + bias.y;
  5846. }
  5847. return {
  5848. minimum: minimum,
  5849. maximum: maximum
  5850. };
  5851. };
  5852. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5853. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5854. return undefined;
  5855. return Array.isArray(obj) ? obj : [obj];
  5856. };
  5857. // Misc.
  5858. Tools.GetPointerPrefix = function () {
  5859. var eventPrefix = "pointer";
  5860. // Check if pointer events are supported
  5861. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5862. eventPrefix = "mouse";
  5863. }
  5864. return eventPrefix;
  5865. };
  5866. /**
  5867. * @param func - the function to be called
  5868. * @param requester - the object that will request the next frame. Falls back to window.
  5869. */
  5870. Tools.QueueNewFrame = function (func, requester) {
  5871. if (!Tools.IsWindowObjectExist()) {
  5872. return setTimeout(func, 16);
  5873. }
  5874. if (!requester) {
  5875. requester = window;
  5876. }
  5877. if (requester.requestAnimationFrame) {
  5878. return requester.requestAnimationFrame(func);
  5879. }
  5880. else if (requester.msRequestAnimationFrame) {
  5881. return requester.msRequestAnimationFrame(func);
  5882. }
  5883. else if (requester.webkitRequestAnimationFrame) {
  5884. return requester.webkitRequestAnimationFrame(func);
  5885. }
  5886. else if (requester.mozRequestAnimationFrame) {
  5887. return requester.mozRequestAnimationFrame(func);
  5888. }
  5889. else if (requester.oRequestAnimationFrame) {
  5890. return requester.oRequestAnimationFrame(func);
  5891. }
  5892. else {
  5893. return window.setTimeout(func, 16);
  5894. }
  5895. };
  5896. Tools.RequestFullscreen = function (element) {
  5897. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5898. if (!requestFunction)
  5899. return;
  5900. requestFunction.call(element);
  5901. };
  5902. Tools.ExitFullscreen = function () {
  5903. if (document.exitFullscreen) {
  5904. document.exitFullscreen();
  5905. }
  5906. else if (document.mozCancelFullScreen) {
  5907. document.mozCancelFullScreen();
  5908. }
  5909. else if (document.webkitCancelFullScreen) {
  5910. document.webkitCancelFullScreen();
  5911. }
  5912. else if (document.msCancelFullScreen) {
  5913. document.msCancelFullScreen();
  5914. }
  5915. };
  5916. Tools.SetCorsBehavior = function (url, img) {
  5917. if (Tools.CorsBehavior) {
  5918. switch (typeof (Tools.CorsBehavior)) {
  5919. case "function":
  5920. var result = Tools.CorsBehavior(url);
  5921. if (result) {
  5922. img.crossOrigin = result;
  5923. }
  5924. break;
  5925. case "string":
  5926. default:
  5927. img.crossOrigin = Tools.CorsBehavior;
  5928. break;
  5929. }
  5930. }
  5931. };
  5932. // External files
  5933. Tools.CleanUrl = function (url) {
  5934. url = url.replace(/#/mg, "%23");
  5935. return url;
  5936. };
  5937. Tools.LoadImage = function (url, onLoad, onError, database) {
  5938. if (url instanceof ArrayBuffer) {
  5939. url = Tools.EncodeArrayBufferTobase64(url);
  5940. }
  5941. url = Tools.CleanUrl(url);
  5942. url = Tools.PreprocessUrl(url);
  5943. var img = new Image();
  5944. if (url.substr(0, 5) !== "data:") {
  5945. Tools.SetCorsBehavior(url, img);
  5946. }
  5947. img.onload = function () {
  5948. onLoad(img);
  5949. };
  5950. img.onerror = function (err) {
  5951. Tools.Error("Error while trying to load image: " + url);
  5952. if (Tools.UseFallbackTexture) {
  5953. img.src = Tools.fallbackTexture;
  5954. onLoad(img);
  5955. }
  5956. else {
  5957. onError("Error while trying to load image: " + url, err);
  5958. }
  5959. };
  5960. var noIndexedDB = function () {
  5961. img.src = url;
  5962. };
  5963. var loadFromIndexedDB = function () {
  5964. database.loadImageFromDB(url, img);
  5965. };
  5966. //ANY database to do!
  5967. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5968. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5969. }
  5970. else {
  5971. if (url.indexOf("file:") !== 0) {
  5972. noIndexedDB();
  5973. }
  5974. else {
  5975. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5976. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5977. try {
  5978. var blobURL;
  5979. try {
  5980. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5981. }
  5982. catch (ex) {
  5983. // Chrome doesn't support oneTimeOnly parameter
  5984. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5985. }
  5986. img.src = blobURL;
  5987. }
  5988. catch (e) {
  5989. img.src = null;
  5990. }
  5991. }
  5992. else {
  5993. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5994. img.src = Tools.fallbackTexture;
  5995. }
  5996. }
  5997. }
  5998. return img;
  5999. };
  6000. //ANY
  6001. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6002. url = Tools.CleanUrl(url);
  6003. url = Tools.PreprocessUrl(url);
  6004. var noIndexedDB = function () {
  6005. var request = new XMLHttpRequest();
  6006. var loadUrl = Tools.BaseUrl + url;
  6007. request.open('GET', loadUrl, true);
  6008. if (useArrayBuffer) {
  6009. request.responseType = "arraybuffer";
  6010. }
  6011. request.onprogress = progressCallBack;
  6012. request.onreadystatechange = function () {
  6013. // In case of undefined state in some browsers.
  6014. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6015. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6016. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6017. callback(!useArrayBuffer ? request.responseText : request.response);
  6018. }
  6019. else {
  6020. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6021. if (onError) {
  6022. onError(request, e);
  6023. }
  6024. else {
  6025. throw e;
  6026. }
  6027. }
  6028. }
  6029. };
  6030. request.send(null);
  6031. };
  6032. var loadFromIndexedDB = function () {
  6033. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6034. };
  6035. if (url.indexOf("file:") !== -1) {
  6036. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6037. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6038. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6039. }
  6040. else {
  6041. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6042. if (onError) {
  6043. var e = new Error(errorMessage);
  6044. onError(undefined, e);
  6045. }
  6046. else {
  6047. Tools.Error(errorMessage);
  6048. }
  6049. }
  6050. }
  6051. else {
  6052. // Caching all files
  6053. if (database && database.enableSceneOffline) {
  6054. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6055. }
  6056. else {
  6057. noIndexedDB();
  6058. }
  6059. }
  6060. };
  6061. /**
  6062. * Load a script (identified by an url). When the url returns, the
  6063. * content of this file is added into a new script element, attached to the DOM (body element)
  6064. */
  6065. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6066. var head = document.getElementsByTagName('head')[0];
  6067. var script = document.createElement('script');
  6068. script.type = 'text/javascript';
  6069. script.src = scriptUrl;
  6070. var self = this;
  6071. script.onload = function () {
  6072. if (onSuccess) {
  6073. onSuccess();
  6074. }
  6075. };
  6076. script.onerror = function (e) {
  6077. if (onError) {
  6078. onError("Unable to load script", e);
  6079. }
  6080. };
  6081. head.appendChild(script);
  6082. };
  6083. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6084. var reader = new FileReader();
  6085. reader.onload = function (e) {
  6086. //target doesn't have result from ts 1.3
  6087. callback(e.target['result']);
  6088. };
  6089. reader.onprogress = progressCallback;
  6090. reader.readAsDataURL(fileToLoad);
  6091. };
  6092. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6093. var reader = new FileReader();
  6094. reader.onerror = function (e) {
  6095. Tools.Log("Error while reading file: " + fileToLoad.name);
  6096. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6097. };
  6098. reader.onload = function (e) {
  6099. //target doesn't have result from ts 1.3
  6100. callback(e.target['result']);
  6101. };
  6102. reader.onprogress = progressCallBack;
  6103. if (!useArrayBuffer) {
  6104. // Asynchronous read
  6105. reader.readAsText(fileToLoad);
  6106. }
  6107. else {
  6108. reader.readAsArrayBuffer(fileToLoad);
  6109. }
  6110. };
  6111. //returns a downloadable url to a file content.
  6112. Tools.FileAsURL = function (content) {
  6113. var fileBlob = new Blob([content]);
  6114. var url = window.URL || window.webkitURL;
  6115. var link = url.createObjectURL(fileBlob);
  6116. return link;
  6117. };
  6118. // Misc.
  6119. Tools.Format = function (value, decimals) {
  6120. if (decimals === void 0) { decimals = 2; }
  6121. return value.toFixed(decimals);
  6122. };
  6123. Tools.CheckExtends = function (v, min, max) {
  6124. if (v.x < min.x)
  6125. min.x = v.x;
  6126. if (v.y < min.y)
  6127. min.y = v.y;
  6128. if (v.z < min.z)
  6129. min.z = v.z;
  6130. if (v.x > max.x)
  6131. max.x = v.x;
  6132. if (v.y > max.y)
  6133. max.y = v.y;
  6134. if (v.z > max.z)
  6135. max.z = v.z;
  6136. };
  6137. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6138. for (var prop in source) {
  6139. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6140. continue;
  6141. }
  6142. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6143. continue;
  6144. }
  6145. var sourceValue = source[prop];
  6146. var typeOfSourceValue = typeof sourceValue;
  6147. if (typeOfSourceValue === "function") {
  6148. continue;
  6149. }
  6150. if (typeOfSourceValue === "object") {
  6151. if (sourceValue instanceof Array) {
  6152. destination[prop] = [];
  6153. if (sourceValue.length > 0) {
  6154. if (typeof sourceValue[0] == "object") {
  6155. for (var index = 0; index < sourceValue.length; index++) {
  6156. var clonedValue = cloneValue(sourceValue[index], destination);
  6157. if (destination[prop].indexOf(clonedValue) === -1) {
  6158. destination[prop].push(clonedValue);
  6159. }
  6160. }
  6161. }
  6162. else {
  6163. destination[prop] = sourceValue.slice(0);
  6164. }
  6165. }
  6166. }
  6167. else {
  6168. destination[prop] = cloneValue(sourceValue, destination);
  6169. }
  6170. }
  6171. else {
  6172. destination[prop] = sourceValue;
  6173. }
  6174. }
  6175. };
  6176. Tools.IsEmpty = function (obj) {
  6177. for (var i in obj) {
  6178. return false;
  6179. }
  6180. return true;
  6181. };
  6182. Tools.RegisterTopRootEvents = function (events) {
  6183. for (var index = 0; index < events.length; index++) {
  6184. var event = events[index];
  6185. window.addEventListener(event.name, event.handler, false);
  6186. try {
  6187. if (window.parent) {
  6188. window.parent.addEventListener(event.name, event.handler, false);
  6189. }
  6190. }
  6191. catch (e) {
  6192. // Silently fails...
  6193. }
  6194. }
  6195. };
  6196. Tools.UnregisterTopRootEvents = function (events) {
  6197. for (var index = 0; index < events.length; index++) {
  6198. var event = events[index];
  6199. window.removeEventListener(event.name, event.handler);
  6200. try {
  6201. if (window.parent) {
  6202. window.parent.removeEventListener(event.name, event.handler);
  6203. }
  6204. }
  6205. catch (e) {
  6206. // Silently fails...
  6207. }
  6208. }
  6209. };
  6210. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6211. if (mimeType === void 0) { mimeType = "image/png"; }
  6212. // Read the contents of the framebuffer
  6213. var numberOfChannelsByLine = width * 4;
  6214. var halfHeight = height / 2;
  6215. //Reading datas from WebGL
  6216. var data = engine.readPixels(0, 0, width, height);
  6217. //To flip image on Y axis.
  6218. for (var i = 0; i < halfHeight; i++) {
  6219. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6220. var currentCell = j + i * numberOfChannelsByLine;
  6221. var targetLine = height - i - 1;
  6222. var targetCell = j + targetLine * numberOfChannelsByLine;
  6223. var temp = data[currentCell];
  6224. data[currentCell] = data[targetCell];
  6225. data[targetCell] = temp;
  6226. }
  6227. }
  6228. // Create a 2D canvas to store the result
  6229. if (!screenshotCanvas) {
  6230. screenshotCanvas = document.createElement('canvas');
  6231. }
  6232. screenshotCanvas.width = width;
  6233. screenshotCanvas.height = height;
  6234. var context = screenshotCanvas.getContext('2d');
  6235. // Copy the pixels to a 2D canvas
  6236. var imageData = context.createImageData(width, height);
  6237. var castData = (imageData.data);
  6238. castData.set(data);
  6239. context.putImageData(imageData, 0, 0);
  6240. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6241. };
  6242. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6243. if (mimeType === void 0) { mimeType = "image/png"; }
  6244. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6245. if (successCallback) {
  6246. successCallback(base64Image);
  6247. }
  6248. else {
  6249. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6250. if (("download" in document.createElement("a"))) {
  6251. var a = window.document.createElement("a");
  6252. a.href = base64Image;
  6253. var date = new Date();
  6254. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6255. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6256. window.document.body.appendChild(a);
  6257. a.addEventListener("click", function () {
  6258. a.parentElement.removeChild(a);
  6259. });
  6260. a.click();
  6261. //Or opening a new tab with the image if it is not possible to automatically start download.
  6262. }
  6263. else {
  6264. var newWindow = window.open("");
  6265. var img = newWindow.document.createElement("img");
  6266. img.src = base64Image;
  6267. newWindow.document.body.appendChild(img);
  6268. }
  6269. }
  6270. };
  6271. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6272. if (mimeType === void 0) { mimeType = "image/png"; }
  6273. var width;
  6274. var height;
  6275. // If a precision value is specified
  6276. if (size.precision) {
  6277. width = Math.round(engine.getRenderWidth() * size.precision);
  6278. height = Math.round(width / engine.getAspectRatio(camera));
  6279. }
  6280. else if (size.width && size.height) {
  6281. width = size.width;
  6282. height = size.height;
  6283. }
  6284. else if (size.width && !size.height) {
  6285. width = size.width;
  6286. height = Math.round(width / engine.getAspectRatio(camera));
  6287. }
  6288. else if (size.height && !size.width) {
  6289. height = size.height;
  6290. width = Math.round(height * engine.getAspectRatio(camera));
  6291. }
  6292. else if (!isNaN(size)) {
  6293. height = size;
  6294. width = size;
  6295. }
  6296. else {
  6297. Tools.Error("Invalid 'size' parameter !");
  6298. return;
  6299. }
  6300. if (!screenshotCanvas) {
  6301. screenshotCanvas = document.createElement('canvas');
  6302. }
  6303. screenshotCanvas.width = width;
  6304. screenshotCanvas.height = height;
  6305. var renderContext = screenshotCanvas.getContext("2d");
  6306. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6307. var newWidth = width;
  6308. var newHeight = newWidth / ratio;
  6309. if (newHeight > height) {
  6310. newHeight = height;
  6311. newWidth = newHeight * ratio;
  6312. }
  6313. var offsetX = Math.max(0, width - newWidth) / 2;
  6314. var offsetY = Math.max(0, height - newHeight) / 2;
  6315. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6316. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6317. };
  6318. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6319. if (mimeType === void 0) { mimeType = "image/png"; }
  6320. if (samples === void 0) { samples = 1; }
  6321. var width;
  6322. var height;
  6323. //If a precision value is specified
  6324. if (size.precision) {
  6325. width = Math.round(engine.getRenderWidth() * size.precision);
  6326. height = Math.round(width / engine.getAspectRatio(camera));
  6327. size = { width: width, height: height };
  6328. }
  6329. else if (size.width && size.height) {
  6330. width = size.width;
  6331. height = size.height;
  6332. }
  6333. else if (size.width && !size.height) {
  6334. width = size.width;
  6335. height = Math.round(width / engine.getAspectRatio(camera));
  6336. size = { width: width, height: height };
  6337. }
  6338. else if (size.height && !size.width) {
  6339. height = size.height;
  6340. width = Math.round(height * engine.getAspectRatio(camera));
  6341. size = { width: width, height: height };
  6342. }
  6343. else if (!isNaN(size)) {
  6344. height = size;
  6345. width = size;
  6346. }
  6347. else {
  6348. Tools.Error("Invalid 'size' parameter !");
  6349. return;
  6350. }
  6351. var scene = camera.getScene();
  6352. var previousCamera = null;
  6353. if (scene.activeCamera !== camera) {
  6354. previousCamera = scene.activeCamera;
  6355. scene.activeCamera = camera;
  6356. }
  6357. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6359. texture.renderList = null;
  6360. texture.samples = samples;
  6361. texture.onAfterRenderObservable.add(function () {
  6362. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6363. });
  6364. scene.incrementRenderId();
  6365. scene.resetCachedMaterial();
  6366. texture.render(true);
  6367. texture.dispose();
  6368. if (previousCamera) {
  6369. scene.activeCamera = previousCamera;
  6370. }
  6371. camera.getProjectionMatrix(true); // Force cache refresh;
  6372. };
  6373. // XHR response validator for local file scenario
  6374. Tools.ValidateXHRData = function (xhr, dataType) {
  6375. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6376. if (dataType === void 0) { dataType = 7; }
  6377. try {
  6378. if (dataType & 1) {
  6379. if (xhr.responseText && xhr.responseText.length > 0) {
  6380. return true;
  6381. }
  6382. else if (dataType === 1) {
  6383. return false;
  6384. }
  6385. }
  6386. if (dataType & 2) {
  6387. // Check header width and height since there is no "TGA" magic number
  6388. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6389. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6390. return true;
  6391. }
  6392. else if (dataType === 2) {
  6393. return false;
  6394. }
  6395. }
  6396. if (dataType & 4) {
  6397. // Check for the "DDS" magic number
  6398. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6399. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6400. return true;
  6401. }
  6402. else {
  6403. return false;
  6404. }
  6405. }
  6406. }
  6407. catch (e) {
  6408. // Global protection
  6409. }
  6410. return false;
  6411. };
  6412. /**
  6413. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6414. * Be aware Math.random() could cause collisions, but:
  6415. * "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"
  6416. */
  6417. Tools.RandomId = function () {
  6418. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6419. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6420. return v.toString(16);
  6421. });
  6422. };
  6423. Object.defineProperty(Tools, "NoneLogLevel", {
  6424. get: function () {
  6425. return Tools._NoneLogLevel;
  6426. },
  6427. enumerable: true,
  6428. configurable: true
  6429. });
  6430. Object.defineProperty(Tools, "MessageLogLevel", {
  6431. get: function () {
  6432. return Tools._MessageLogLevel;
  6433. },
  6434. enumerable: true,
  6435. configurable: true
  6436. });
  6437. Object.defineProperty(Tools, "WarningLogLevel", {
  6438. get: function () {
  6439. return Tools._WarningLogLevel;
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(Tools, "ErrorLogLevel", {
  6445. get: function () {
  6446. return Tools._ErrorLogLevel;
  6447. },
  6448. enumerable: true,
  6449. configurable: true
  6450. });
  6451. Object.defineProperty(Tools, "AllLogLevel", {
  6452. get: function () {
  6453. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. Tools._AddLogEntry = function (entry) {
  6459. Tools._LogCache = entry + Tools._LogCache;
  6460. if (Tools.OnNewCacheEntry) {
  6461. Tools.OnNewCacheEntry(entry);
  6462. }
  6463. };
  6464. Tools._FormatMessage = function (message) {
  6465. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6466. var date = new Date();
  6467. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6468. };
  6469. Tools._LogDisabled = function (message) {
  6470. // nothing to do
  6471. };
  6472. Tools._LogEnabled = function (message) {
  6473. var formattedMessage = Tools._FormatMessage(message);
  6474. console.log("BJS - " + formattedMessage);
  6475. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6476. Tools._AddLogEntry(entry);
  6477. };
  6478. Tools._WarnDisabled = function (message) {
  6479. // nothing to do
  6480. };
  6481. Tools._WarnEnabled = function (message) {
  6482. var formattedMessage = Tools._FormatMessage(message);
  6483. console.warn("BJS - " + formattedMessage);
  6484. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6485. Tools._AddLogEntry(entry);
  6486. };
  6487. Tools._ErrorDisabled = function (message) {
  6488. // nothing to do
  6489. };
  6490. Tools._ErrorEnabled = function (message) {
  6491. Tools.errorsCount++;
  6492. var formattedMessage = Tools._FormatMessage(message);
  6493. console.error("BJS - " + formattedMessage);
  6494. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6495. Tools._AddLogEntry(entry);
  6496. };
  6497. Object.defineProperty(Tools, "LogCache", {
  6498. get: function () {
  6499. return Tools._LogCache;
  6500. },
  6501. enumerable: true,
  6502. configurable: true
  6503. });
  6504. Tools.ClearLogCache = function () {
  6505. Tools._LogCache = "";
  6506. Tools.errorsCount = 0;
  6507. };
  6508. Object.defineProperty(Tools, "LogLevels", {
  6509. set: function (level) {
  6510. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6511. Tools.Log = Tools._LogEnabled;
  6512. }
  6513. else {
  6514. Tools.Log = Tools._LogDisabled;
  6515. }
  6516. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6517. Tools.Warn = Tools._WarnEnabled;
  6518. }
  6519. else {
  6520. Tools.Warn = Tools._WarnDisabled;
  6521. }
  6522. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6523. Tools.Error = Tools._ErrorEnabled;
  6524. }
  6525. else {
  6526. Tools.Error = Tools._ErrorDisabled;
  6527. }
  6528. },
  6529. enumerable: true,
  6530. configurable: true
  6531. });
  6532. Tools.IsWindowObjectExist = function () {
  6533. return (typeof window) !== "undefined";
  6534. };
  6535. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6536. get: function () {
  6537. return Tools._PerformanceNoneLogLevel;
  6538. },
  6539. enumerable: true,
  6540. configurable: true
  6541. });
  6542. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6543. get: function () {
  6544. return Tools._PerformanceUserMarkLogLevel;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6550. get: function () {
  6551. return Tools._PerformanceConsoleLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6557. set: function (level) {
  6558. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6559. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6560. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6561. return;
  6562. }
  6563. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6564. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6565. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6566. return;
  6567. }
  6568. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6569. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6575. };
  6576. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6577. };
  6578. Tools._StartUserMark = function (counterName, condition) {
  6579. if (condition === void 0) { condition = true; }
  6580. if (!Tools._performance) {
  6581. if (!Tools.IsWindowObjectExist()) {
  6582. return;
  6583. }
  6584. Tools._performance = window.performance;
  6585. }
  6586. if (!condition || !Tools._performance.mark) {
  6587. return;
  6588. }
  6589. Tools._performance.mark(counterName + "-Begin");
  6590. };
  6591. Tools._EndUserMark = function (counterName, condition) {
  6592. if (condition === void 0) { condition = true; }
  6593. if (!condition || !Tools._performance.mark) {
  6594. return;
  6595. }
  6596. Tools._performance.mark(counterName + "-End");
  6597. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6598. };
  6599. Tools._StartPerformanceConsole = function (counterName, condition) {
  6600. if (condition === void 0) { condition = true; }
  6601. if (!condition) {
  6602. return;
  6603. }
  6604. Tools._StartUserMark(counterName, condition);
  6605. if (console.time) {
  6606. console.time(counterName);
  6607. }
  6608. };
  6609. Tools._EndPerformanceConsole = function (counterName, condition) {
  6610. if (condition === void 0) { condition = true; }
  6611. if (!condition) {
  6612. return;
  6613. }
  6614. Tools._EndUserMark(counterName, condition);
  6615. if (console.time) {
  6616. console.timeEnd(counterName);
  6617. }
  6618. };
  6619. Object.defineProperty(Tools, "Now", {
  6620. get: function () {
  6621. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6622. return window.performance.now();
  6623. }
  6624. return new Date().getTime();
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. /**
  6630. * This method will return the name of the class used to create the instance of the given object.
  6631. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6632. * @param object the object to get the class name from
  6633. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6634. */
  6635. Tools.GetClassName = function (object, isType) {
  6636. if (isType === void 0) { isType = false; }
  6637. var name = null;
  6638. if (!isType && object.getClassName) {
  6639. name = object.getClassName();
  6640. }
  6641. else {
  6642. if (object instanceof Object) {
  6643. var classObj = isType ? object : Object.getPrototypeOf(object);
  6644. name = classObj.constructor["__bjsclassName__"];
  6645. }
  6646. if (!name) {
  6647. name = typeof object;
  6648. }
  6649. }
  6650. return name;
  6651. };
  6652. Tools.first = function (array, predicate) {
  6653. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6654. var el = array_1[_i];
  6655. if (predicate(el)) {
  6656. return el;
  6657. }
  6658. }
  6659. };
  6660. /**
  6661. * This method will return the name of the full name of the class, including its owning module (if any).
  6662. * 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).
  6663. * @param object the object to get the class name from
  6664. * @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.
  6665. */
  6666. Tools.getFullClassName = function (object, isType) {
  6667. if (isType === void 0) { isType = false; }
  6668. var className = null;
  6669. var moduleName = null;
  6670. if (!isType && object.getClassName) {
  6671. className = object.getClassName();
  6672. }
  6673. else {
  6674. if (object instanceof Object) {
  6675. var classObj = isType ? object : Object.getPrototypeOf(object);
  6676. className = classObj.constructor["__bjsclassName__"];
  6677. moduleName = classObj.constructor["__bjsmoduleName__"];
  6678. }
  6679. if (!className) {
  6680. className = typeof object;
  6681. }
  6682. }
  6683. if (!className) {
  6684. return null;
  6685. }
  6686. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6687. };
  6688. /**
  6689. * 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.
  6690. * @param array
  6691. */
  6692. Tools.arrayOrStringFeeder = function (array) {
  6693. return function (index) {
  6694. if (index >= array.length) {
  6695. return null;
  6696. }
  6697. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6698. if (val && val.getHashCode) {
  6699. val = val.getHashCode();
  6700. }
  6701. if (typeof val === "string") {
  6702. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6703. }
  6704. return val;
  6705. };
  6706. };
  6707. /**
  6708. * Compute the hashCode of a stream of number
  6709. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6710. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6711. * @return the hash code computed
  6712. */
  6713. Tools.hashCodeFromStream = function (feeder) {
  6714. // Based from here: http://stackoverflow.com/a/7616484/802124
  6715. var hash = 0;
  6716. var index = 0;
  6717. var chr = feeder(index++);
  6718. while (chr != null) {
  6719. hash = ((hash << 5) - hash) + chr;
  6720. hash |= 0; // Convert to 32bit integer
  6721. chr = feeder(index++);
  6722. }
  6723. return hash;
  6724. };
  6725. Tools.BaseUrl = "";
  6726. Tools.CorsBehavior = "anonymous";
  6727. Tools.UseFallbackTexture = true;
  6728. /**
  6729. * Use this object to register external classes like custom textures or material
  6730. * to allow the laoders to instantiate them
  6731. */
  6732. Tools.RegisteredExternalClasses = {};
  6733. // Used in case of a texture loading problem
  6734. 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";
  6735. Tools.PreprocessUrl = function (url) {
  6736. return url;
  6737. };
  6738. // Logs
  6739. Tools._NoneLogLevel = 0;
  6740. Tools._MessageLogLevel = 1;
  6741. Tools._WarningLogLevel = 2;
  6742. Tools._ErrorLogLevel = 4;
  6743. Tools._LogCache = "";
  6744. Tools.errorsCount = 0;
  6745. Tools.Log = Tools._LogEnabled;
  6746. Tools.Warn = Tools._WarnEnabled;
  6747. Tools.Error = Tools._ErrorEnabled;
  6748. // Performances
  6749. Tools._PerformanceNoneLogLevel = 0;
  6750. Tools._PerformanceUserMarkLogLevel = 1;
  6751. Tools._PerformanceConsoleLogLevel = 2;
  6752. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6753. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6754. return Tools;
  6755. }());
  6756. BABYLON.Tools = Tools;
  6757. /**
  6758. * This class is used to track a performance counter which is number based.
  6759. * The user has access to many properties which give statistics of different nature
  6760. *
  6761. * The implementer can track two kinds of Performance Counter: time and count
  6762. * 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.
  6763. * 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.
  6764. */
  6765. var PerfCounter = (function () {
  6766. function PerfCounter() {
  6767. this._startMonitoringTime = 0;
  6768. this._min = 0;
  6769. this._max = 0;
  6770. this._average = 0;
  6771. this._lastSecAverage = 0;
  6772. this._current = 0;
  6773. this._totalValueCount = 0;
  6774. this._totalAccumulated = 0;
  6775. this._lastSecAccumulated = 0;
  6776. this._lastSecTime = 0;
  6777. this._lastSecValueCount = 0;
  6778. }
  6779. Object.defineProperty(PerfCounter.prototype, "min", {
  6780. /**
  6781. * Returns the smallest value ever
  6782. */
  6783. get: function () {
  6784. return this._min;
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(PerfCounter.prototype, "max", {
  6790. /**
  6791. * Returns the biggest value ever
  6792. */
  6793. get: function () {
  6794. return this._max;
  6795. },
  6796. enumerable: true,
  6797. configurable: true
  6798. });
  6799. Object.defineProperty(PerfCounter.prototype, "average", {
  6800. /**
  6801. * Returns the average value since the performance counter is running
  6802. */
  6803. get: function () {
  6804. return this._average;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6810. /**
  6811. * Returns the average value of the last second the counter was monitored
  6812. */
  6813. get: function () {
  6814. return this._lastSecAverage;
  6815. },
  6816. enumerable: true,
  6817. configurable: true
  6818. });
  6819. Object.defineProperty(PerfCounter.prototype, "current", {
  6820. /**
  6821. * Returns the current value
  6822. */
  6823. get: function () {
  6824. return this._current;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(PerfCounter.prototype, "total", {
  6830. get: function () {
  6831. return this._totalAccumulated;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. /**
  6837. * Call this method to start monitoring a new frame.
  6838. * 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.
  6839. */
  6840. PerfCounter.prototype.fetchNewFrame = function () {
  6841. this._totalValueCount++;
  6842. this._current = 0;
  6843. this._lastSecValueCount++;
  6844. };
  6845. /**
  6846. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6847. * @param newCount the count value to add to the monitored count
  6848. * @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.
  6849. */
  6850. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6851. if (!PerfCounter.Enabled) {
  6852. return;
  6853. }
  6854. this._current += newCount;
  6855. if (fetchResult) {
  6856. this._fetchResult();
  6857. }
  6858. };
  6859. /**
  6860. * Start monitoring this performance counter
  6861. */
  6862. PerfCounter.prototype.beginMonitoring = function () {
  6863. if (!PerfCounter.Enabled) {
  6864. return;
  6865. }
  6866. this._startMonitoringTime = Tools.Now;
  6867. };
  6868. /**
  6869. * Compute the time lapsed since the previous beginMonitoring() call.
  6870. * @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
  6871. */
  6872. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6873. if (newFrame === void 0) { newFrame = true; }
  6874. if (!PerfCounter.Enabled) {
  6875. return;
  6876. }
  6877. if (newFrame) {
  6878. this.fetchNewFrame();
  6879. }
  6880. var currentTime = Tools.Now;
  6881. this._current = currentTime - this._startMonitoringTime;
  6882. if (newFrame) {
  6883. this._fetchResult();
  6884. }
  6885. };
  6886. PerfCounter.prototype._fetchResult = function () {
  6887. this._totalAccumulated += this._current;
  6888. this._lastSecAccumulated += this._current;
  6889. // Min/Max update
  6890. this._min = Math.min(this._min, this._current);
  6891. this._max = Math.max(this._max, this._current);
  6892. this._average = this._totalAccumulated / this._totalValueCount;
  6893. // Reset last sec?
  6894. var now = Tools.Now;
  6895. if ((now - this._lastSecTime) > 1000) {
  6896. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6897. this._lastSecTime = now;
  6898. this._lastSecAccumulated = 0;
  6899. this._lastSecValueCount = 0;
  6900. }
  6901. };
  6902. PerfCounter.Enabled = true;
  6903. return PerfCounter;
  6904. }());
  6905. BABYLON.PerfCounter = PerfCounter;
  6906. /**
  6907. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6908. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6909. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6910. * @param name The name of the class, case should be preserved
  6911. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6912. */
  6913. function className(name, module) {
  6914. return function (target) {
  6915. target["__bjsclassName__"] = name;
  6916. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6917. };
  6918. }
  6919. BABYLON.className = className;
  6920. /**
  6921. * An implementation of a loop for asynchronous functions.
  6922. */
  6923. var AsyncLoop = (function () {
  6924. /**
  6925. * Constroctor.
  6926. * @param iterations the number of iterations.
  6927. * @param _fn the function to run each iteration
  6928. * @param _successCallback the callback that will be called upon succesful execution
  6929. * @param offset starting offset.
  6930. */
  6931. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6932. if (offset === void 0) { offset = 0; }
  6933. this.iterations = iterations;
  6934. this._fn = _fn;
  6935. this._successCallback = _successCallback;
  6936. this.index = offset - 1;
  6937. this._done = false;
  6938. }
  6939. /**
  6940. * Execute the next iteration. Must be called after the last iteration was finished.
  6941. */
  6942. AsyncLoop.prototype.executeNext = function () {
  6943. if (!this._done) {
  6944. if (this.index + 1 < this.iterations) {
  6945. ++this.index;
  6946. this._fn(this);
  6947. }
  6948. else {
  6949. this.breakLoop();
  6950. }
  6951. }
  6952. };
  6953. /**
  6954. * Break the loop and run the success callback.
  6955. */
  6956. AsyncLoop.prototype.breakLoop = function () {
  6957. this._done = true;
  6958. this._successCallback();
  6959. };
  6960. /**
  6961. * Helper function
  6962. */
  6963. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6964. if (offset === void 0) { offset = 0; }
  6965. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6966. loop.executeNext();
  6967. return loop;
  6968. };
  6969. /**
  6970. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6971. * @param iterations total number of iterations
  6972. * @param syncedIterations number of synchronous iterations in each async iteration.
  6973. * @param fn the function to call each iteration.
  6974. * @param callback a success call back that will be called when iterating stops.
  6975. * @param breakFunction a break condition (optional)
  6976. * @param timeout timeout settings for the setTimeout function. default - 0.
  6977. * @constructor
  6978. */
  6979. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6980. if (timeout === void 0) { timeout = 0; }
  6981. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6982. if (breakFunction && breakFunction())
  6983. loop.breakLoop();
  6984. else {
  6985. setTimeout(function () {
  6986. for (var i = 0; i < syncedIterations; ++i) {
  6987. var iteration = (loop.index * syncedIterations) + i;
  6988. if (iteration >= iterations)
  6989. break;
  6990. fn(iteration);
  6991. if (breakFunction && breakFunction()) {
  6992. loop.breakLoop();
  6993. break;
  6994. }
  6995. }
  6996. loop.executeNext();
  6997. }, timeout);
  6998. }
  6999. }, callback);
  7000. };
  7001. return AsyncLoop;
  7002. }());
  7003. BABYLON.AsyncLoop = AsyncLoop;
  7004. })(BABYLON || (BABYLON = {}));
  7005. //# sourceMappingURL=babylon.tools.js.map
  7006. var BABYLON;
  7007. (function (BABYLON) {
  7008. var Internals;
  7009. (function (Internals) {
  7010. var _AlphaState = (function () {
  7011. /**
  7012. * Initializes the state.
  7013. */
  7014. function _AlphaState() {
  7015. this._isAlphaBlendDirty = false;
  7016. this._isBlendFunctionParametersDirty = false;
  7017. this._isBlendEquationParametersDirty = false;
  7018. this._isBlendConstantsDirty = false;
  7019. this._alphaBlend = false;
  7020. this._blendFunctionParameters = new Array(4);
  7021. this._blendEquationParameters = new Array(2);
  7022. this._blendConstants = new Array(4);
  7023. this.reset();
  7024. }
  7025. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7026. get: function () {
  7027. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7033. get: function () {
  7034. return this._alphaBlend;
  7035. },
  7036. set: function (value) {
  7037. if (this._alphaBlend === value) {
  7038. return;
  7039. }
  7040. this._alphaBlend = value;
  7041. this._isAlphaBlendDirty = true;
  7042. },
  7043. enumerable: true,
  7044. configurable: true
  7045. });
  7046. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7047. if (this._blendConstants[0] === r &&
  7048. this._blendConstants[1] === g &&
  7049. this._blendConstants[2] === b &&
  7050. this._blendConstants[3] === a) {
  7051. return;
  7052. }
  7053. this._blendConstants[0] = r;
  7054. this._blendConstants[1] = g;
  7055. this._blendConstants[2] = b;
  7056. this._blendConstants[3] = a;
  7057. this._isBlendConstantsDirty = true;
  7058. };
  7059. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7060. if (this._blendFunctionParameters[0] === value0 &&
  7061. this._blendFunctionParameters[1] === value1 &&
  7062. this._blendFunctionParameters[2] === value2 &&
  7063. this._blendFunctionParameters[3] === value3) {
  7064. return;
  7065. }
  7066. this._blendFunctionParameters[0] = value0;
  7067. this._blendFunctionParameters[1] = value1;
  7068. this._blendFunctionParameters[2] = value2;
  7069. this._blendFunctionParameters[3] = value3;
  7070. this._isBlendFunctionParametersDirty = true;
  7071. };
  7072. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7073. if (this._blendEquationParameters[0] === rgb &&
  7074. this._blendEquationParameters[1] === alpha) {
  7075. return;
  7076. }
  7077. this._blendEquationParameters[0] = rgb;
  7078. this._blendEquationParameters[1] = alpha;
  7079. this._isBlendEquationParametersDirty = true;
  7080. };
  7081. _AlphaState.prototype.reset = function () {
  7082. this._alphaBlend = false;
  7083. this._blendFunctionParameters[0] = null;
  7084. this._blendFunctionParameters[1] = null;
  7085. this._blendFunctionParameters[2] = null;
  7086. this._blendFunctionParameters[3] = null;
  7087. this._blendEquationParameters[0] = null;
  7088. this._blendEquationParameters[1] = null;
  7089. this._blendConstants[0] = null;
  7090. this._blendConstants[1] = null;
  7091. this._blendConstants[2] = null;
  7092. this._blendConstants[3] = null;
  7093. this._isAlphaBlendDirty = true;
  7094. this._isBlendFunctionParametersDirty = false;
  7095. this._isBlendEquationParametersDirty = false;
  7096. this._isBlendConstantsDirty = false;
  7097. };
  7098. _AlphaState.prototype.apply = function (gl) {
  7099. if (!this.isDirty) {
  7100. return;
  7101. }
  7102. // Alpha blend
  7103. if (this._isAlphaBlendDirty) {
  7104. if (this._alphaBlend) {
  7105. gl.enable(gl.BLEND);
  7106. }
  7107. else {
  7108. gl.disable(gl.BLEND);
  7109. }
  7110. this._isAlphaBlendDirty = false;
  7111. }
  7112. // Alpha function
  7113. if (this._isBlendFunctionParametersDirty) {
  7114. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7115. this._isBlendFunctionParametersDirty = false;
  7116. }
  7117. // Alpha equation
  7118. if (this._isBlendEquationParametersDirty) {
  7119. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7120. this._isBlendEquationParametersDirty = false;
  7121. }
  7122. // Constants
  7123. if (this._isBlendConstantsDirty) {
  7124. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7125. this._isBlendConstantsDirty = false;
  7126. }
  7127. };
  7128. return _AlphaState;
  7129. }());
  7130. Internals._AlphaState = _AlphaState;
  7131. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7132. })(BABYLON || (BABYLON = {}));
  7133. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7134. var BABYLON;
  7135. (function (BABYLON) {
  7136. var Internals;
  7137. (function (Internals) {
  7138. var _DepthCullingState = (function () {
  7139. /**
  7140. * Initializes the state.
  7141. */
  7142. function _DepthCullingState() {
  7143. this._isDepthTestDirty = false;
  7144. this._isDepthMaskDirty = false;
  7145. this._isDepthFuncDirty = false;
  7146. this._isCullFaceDirty = false;
  7147. this._isCullDirty = false;
  7148. this._isZOffsetDirty = false;
  7149. this.reset();
  7150. }
  7151. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7152. get: function () {
  7153. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7154. },
  7155. enumerable: true,
  7156. configurable: true
  7157. });
  7158. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7159. get: function () {
  7160. return this._zOffset;
  7161. },
  7162. set: function (value) {
  7163. if (this._zOffset === value) {
  7164. return;
  7165. }
  7166. this._zOffset = value;
  7167. this._isZOffsetDirty = true;
  7168. },
  7169. enumerable: true,
  7170. configurable: true
  7171. });
  7172. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7173. get: function () {
  7174. return this._cullFace;
  7175. },
  7176. set: function (value) {
  7177. if (this._cullFace === value) {
  7178. return;
  7179. }
  7180. this._cullFace = value;
  7181. this._isCullFaceDirty = true;
  7182. },
  7183. enumerable: true,
  7184. configurable: true
  7185. });
  7186. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7187. get: function () {
  7188. return this._cull;
  7189. },
  7190. set: function (value) {
  7191. if (this._cull === value) {
  7192. return;
  7193. }
  7194. this._cull = value;
  7195. this._isCullDirty = true;
  7196. },
  7197. enumerable: true,
  7198. configurable: true
  7199. });
  7200. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7201. get: function () {
  7202. return this._depthFunc;
  7203. },
  7204. set: function (value) {
  7205. if (this._depthFunc === value) {
  7206. return;
  7207. }
  7208. this._depthFunc = value;
  7209. this._isDepthFuncDirty = true;
  7210. },
  7211. enumerable: true,
  7212. configurable: true
  7213. });
  7214. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7215. get: function () {
  7216. return this._depthMask;
  7217. },
  7218. set: function (value) {
  7219. if (this._depthMask === value) {
  7220. return;
  7221. }
  7222. this._depthMask = value;
  7223. this._isDepthMaskDirty = true;
  7224. },
  7225. enumerable: true,
  7226. configurable: true
  7227. });
  7228. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7229. get: function () {
  7230. return this._depthTest;
  7231. },
  7232. set: function (value) {
  7233. if (this._depthTest === value) {
  7234. return;
  7235. }
  7236. this._depthTest = value;
  7237. this._isDepthTestDirty = true;
  7238. },
  7239. enumerable: true,
  7240. configurable: true
  7241. });
  7242. _DepthCullingState.prototype.reset = function () {
  7243. this._depthMask = true;
  7244. this._depthTest = true;
  7245. this._depthFunc = null;
  7246. this._cullFace = null;
  7247. this._cull = null;
  7248. this._zOffset = 0;
  7249. this._isDepthTestDirty = true;
  7250. this._isDepthMaskDirty = true;
  7251. this._isDepthFuncDirty = false;
  7252. this._isCullFaceDirty = false;
  7253. this._isCullDirty = false;
  7254. this._isZOffsetDirty = false;
  7255. };
  7256. _DepthCullingState.prototype.apply = function (gl) {
  7257. if (!this.isDirty) {
  7258. return;
  7259. }
  7260. // Cull
  7261. if (this._isCullDirty) {
  7262. if (this.cull) {
  7263. gl.enable(gl.CULL_FACE);
  7264. }
  7265. else {
  7266. gl.disable(gl.CULL_FACE);
  7267. }
  7268. this._isCullDirty = false;
  7269. }
  7270. // Cull face
  7271. if (this._isCullFaceDirty) {
  7272. gl.cullFace(this.cullFace);
  7273. this._isCullFaceDirty = false;
  7274. }
  7275. // Depth mask
  7276. if (this._isDepthMaskDirty) {
  7277. gl.depthMask(this.depthMask);
  7278. this._isDepthMaskDirty = false;
  7279. }
  7280. // Depth test
  7281. if (this._isDepthTestDirty) {
  7282. if (this.depthTest) {
  7283. gl.enable(gl.DEPTH_TEST);
  7284. }
  7285. else {
  7286. gl.disable(gl.DEPTH_TEST);
  7287. }
  7288. this._isDepthTestDirty = false;
  7289. }
  7290. // Depth func
  7291. if (this._isDepthFuncDirty) {
  7292. gl.depthFunc(this.depthFunc);
  7293. this._isDepthFuncDirty = false;
  7294. }
  7295. // zOffset
  7296. if (this._isZOffsetDirty) {
  7297. if (this.zOffset) {
  7298. gl.enable(gl.POLYGON_OFFSET_FILL);
  7299. gl.polygonOffset(this.zOffset, 0);
  7300. }
  7301. else {
  7302. gl.disable(gl.POLYGON_OFFSET_FILL);
  7303. }
  7304. this._isZOffsetDirty = false;
  7305. }
  7306. };
  7307. return _DepthCullingState;
  7308. }());
  7309. Internals._DepthCullingState = _DepthCullingState;
  7310. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7311. })(BABYLON || (BABYLON = {}));
  7312. //# sourceMappingURL=babylon.depthCullingState.js.map
  7313. var BABYLON;
  7314. (function (BABYLON) {
  7315. var Internals;
  7316. (function (Internals) {
  7317. var _StencilState = (function () {
  7318. function _StencilState() {
  7319. this._isStencilTestDirty = false;
  7320. this._isStencilMaskDirty = false;
  7321. this._isStencilFuncDirty = false;
  7322. this._isStencilOpDirty = false;
  7323. this.reset();
  7324. }
  7325. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7326. get: function () {
  7327. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7328. },
  7329. enumerable: true,
  7330. configurable: true
  7331. });
  7332. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7333. get: function () {
  7334. return this._stencilFunc;
  7335. },
  7336. set: function (value) {
  7337. if (this._stencilFunc === value) {
  7338. return;
  7339. }
  7340. this._stencilFunc = value;
  7341. this._isStencilFuncDirty = true;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7347. get: function () {
  7348. return this._stencilFuncRef;
  7349. },
  7350. set: function (value) {
  7351. if (this._stencilFuncRef === value) {
  7352. return;
  7353. }
  7354. this._stencilFuncRef = value;
  7355. this._isStencilFuncDirty = true;
  7356. },
  7357. enumerable: true,
  7358. configurable: true
  7359. });
  7360. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7361. get: function () {
  7362. return this._stencilFuncMask;
  7363. },
  7364. set: function (value) {
  7365. if (this._stencilFuncMask === value) {
  7366. return;
  7367. }
  7368. this._stencilFuncMask = value;
  7369. this._isStencilFuncDirty = true;
  7370. },
  7371. enumerable: true,
  7372. configurable: true
  7373. });
  7374. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7375. get: function () {
  7376. return this._stencilOpStencilFail;
  7377. },
  7378. set: function (value) {
  7379. if (this._stencilOpStencilFail === value) {
  7380. return;
  7381. }
  7382. this._stencilOpStencilFail = value;
  7383. this._isStencilOpDirty = true;
  7384. },
  7385. enumerable: true,
  7386. configurable: true
  7387. });
  7388. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7389. get: function () {
  7390. return this._stencilOpDepthFail;
  7391. },
  7392. set: function (value) {
  7393. if (this._stencilOpDepthFail === value) {
  7394. return;
  7395. }
  7396. this._stencilOpDepthFail = value;
  7397. this._isStencilOpDirty = true;
  7398. },
  7399. enumerable: true,
  7400. configurable: true
  7401. });
  7402. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7403. get: function () {
  7404. return this._stencilOpStencilDepthPass;
  7405. },
  7406. set: function (value) {
  7407. if (this._stencilOpStencilDepthPass === value) {
  7408. return;
  7409. }
  7410. this._stencilOpStencilDepthPass = value;
  7411. this._isStencilOpDirty = true;
  7412. },
  7413. enumerable: true,
  7414. configurable: true
  7415. });
  7416. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7417. get: function () {
  7418. return this._stencilMask;
  7419. },
  7420. set: function (value) {
  7421. if (this._stencilMask === value) {
  7422. return;
  7423. }
  7424. this._stencilMask = value;
  7425. this._isStencilMaskDirty = true;
  7426. },
  7427. enumerable: true,
  7428. configurable: true
  7429. });
  7430. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7431. get: function () {
  7432. return this._stencilTest;
  7433. },
  7434. set: function (value) {
  7435. if (this._stencilTest === value) {
  7436. return;
  7437. }
  7438. this._stencilTest = value;
  7439. this._isStencilTestDirty = true;
  7440. },
  7441. enumerable: true,
  7442. configurable: true
  7443. });
  7444. _StencilState.prototype.reset = function () {
  7445. this._stencilTest = false;
  7446. this._stencilMask = 0xFF;
  7447. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7448. this._stencilFuncRef = 1;
  7449. this._stencilFuncMask = 0xFF;
  7450. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7451. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7452. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7453. this._isStencilTestDirty = true;
  7454. this._isStencilMaskDirty = true;
  7455. this._isStencilFuncDirty = true;
  7456. this._isStencilOpDirty = true;
  7457. };
  7458. _StencilState.prototype.apply = function (gl) {
  7459. if (!this.isDirty) {
  7460. return;
  7461. }
  7462. // Stencil test
  7463. if (this._isStencilTestDirty) {
  7464. if (this.stencilTest) {
  7465. gl.enable(gl.STENCIL_TEST);
  7466. }
  7467. else {
  7468. gl.disable(gl.STENCIL_TEST);
  7469. }
  7470. this._isStencilTestDirty = false;
  7471. }
  7472. // Stencil mask
  7473. if (this._isStencilMaskDirty) {
  7474. gl.stencilMask(this.stencilMask);
  7475. this._isStencilMaskDirty = false;
  7476. }
  7477. // Stencil func
  7478. if (this._isStencilFuncDirty) {
  7479. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7480. this._isStencilFuncDirty = false;
  7481. }
  7482. // Stencil op
  7483. if (this._isStencilOpDirty) {
  7484. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7485. this._isStencilOpDirty = false;
  7486. }
  7487. };
  7488. return _StencilState;
  7489. }());
  7490. Internals._StencilState = _StencilState;
  7491. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7492. })(BABYLON || (BABYLON = {}));
  7493. //# sourceMappingURL=babylon.stencilState.js.map
  7494. var BABYLON;
  7495. (function (BABYLON) {
  7496. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7497. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7498. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7499. gl.compileShader(shader);
  7500. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7501. throw new Error(gl.getShaderInfoLog(shader));
  7502. }
  7503. return shader;
  7504. };
  7505. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7506. var magFilter = gl.NEAREST;
  7507. var minFilter = gl.NEAREST;
  7508. switch (samplingMode) {
  7509. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7510. magFilter = gl.LINEAR;
  7511. if (generateMipMaps) {
  7512. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7513. }
  7514. else {
  7515. minFilter = gl.LINEAR;
  7516. }
  7517. break;
  7518. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7519. magFilter = gl.LINEAR;
  7520. if (generateMipMaps) {
  7521. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7522. }
  7523. else {
  7524. minFilter = gl.LINEAR;
  7525. }
  7526. break;
  7527. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7528. magFilter = gl.NEAREST;
  7529. if (generateMipMaps) {
  7530. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7531. }
  7532. else {
  7533. minFilter = gl.NEAREST;
  7534. }
  7535. break;
  7536. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7537. magFilter = gl.NEAREST;
  7538. if (generateMipMaps) {
  7539. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7540. }
  7541. else {
  7542. minFilter = gl.NEAREST;
  7543. }
  7544. break;
  7545. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7546. magFilter = gl.NEAREST;
  7547. if (generateMipMaps) {
  7548. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7549. }
  7550. else {
  7551. minFilter = gl.LINEAR;
  7552. }
  7553. break;
  7554. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7555. magFilter = gl.NEAREST;
  7556. if (generateMipMaps) {
  7557. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7558. }
  7559. else {
  7560. minFilter = gl.LINEAR;
  7561. }
  7562. break;
  7563. case BABYLON.Texture.NEAREST_LINEAR:
  7564. magFilter = gl.NEAREST;
  7565. minFilter = gl.LINEAR;
  7566. break;
  7567. case BABYLON.Texture.NEAREST_NEAREST:
  7568. magFilter = gl.NEAREST;
  7569. minFilter = gl.NEAREST;
  7570. break;
  7571. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7572. magFilter = gl.LINEAR;
  7573. if (generateMipMaps) {
  7574. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7575. }
  7576. else {
  7577. minFilter = gl.NEAREST;
  7578. }
  7579. break;
  7580. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7581. magFilter = gl.LINEAR;
  7582. if (generateMipMaps) {
  7583. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7584. }
  7585. else {
  7586. minFilter = gl.NEAREST;
  7587. }
  7588. break;
  7589. case BABYLON.Texture.LINEAR_LINEAR:
  7590. magFilter = gl.LINEAR;
  7591. minFilter = gl.LINEAR;
  7592. break;
  7593. case BABYLON.Texture.LINEAR_NEAREST:
  7594. magFilter = gl.LINEAR;
  7595. minFilter = gl.NEAREST;
  7596. break;
  7597. }
  7598. return {
  7599. min: minFilter,
  7600. mag: magFilter
  7601. };
  7602. };
  7603. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7604. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7605. var img;
  7606. var onload = function () {
  7607. loadedImages[index] = img;
  7608. loadedImages._internalCount++;
  7609. if (scene) {
  7610. scene._removePendingData(img);
  7611. }
  7612. if (loadedImages._internalCount === 6) {
  7613. onfinish(loadedImages);
  7614. }
  7615. };
  7616. var onerror = function (message, exception) {
  7617. if (scene) {
  7618. scene._removePendingData(img);
  7619. }
  7620. if (onErrorCallBack) {
  7621. onErrorCallBack(message, exception);
  7622. }
  7623. };
  7624. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7625. if (scene) {
  7626. scene._addPendingData(img);
  7627. }
  7628. };
  7629. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7630. if (onError === void 0) { onError = null; }
  7631. var loadedImages = [];
  7632. loadedImages._internalCount = 0;
  7633. for (var index = 0; index < 6; index++) {
  7634. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7635. }
  7636. };
  7637. var BufferPointer = (function () {
  7638. function BufferPointer() {
  7639. }
  7640. return BufferPointer;
  7641. }());
  7642. var InstancingAttributeInfo = (function () {
  7643. function InstancingAttributeInfo() {
  7644. }
  7645. return InstancingAttributeInfo;
  7646. }());
  7647. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7648. /**
  7649. * Define options used to create a render target texture
  7650. */
  7651. var RenderTargetCreationOptions = (function () {
  7652. function RenderTargetCreationOptions() {
  7653. }
  7654. return RenderTargetCreationOptions;
  7655. }());
  7656. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7657. /**
  7658. * Regroup several parameters relative to the browser in use
  7659. */
  7660. var EngineCapabilities = (function () {
  7661. function EngineCapabilities() {
  7662. }
  7663. return EngineCapabilities;
  7664. }());
  7665. BABYLON.EngineCapabilities = EngineCapabilities;
  7666. /**
  7667. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7668. */
  7669. var Engine = (function () {
  7670. /**
  7671. * @constructor
  7672. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7673. * @param {boolean} [antialias] - enable antialias
  7674. * @param options - further options to be sent to the getContext function
  7675. */
  7676. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7677. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7678. var _this = this;
  7679. // Public members
  7680. this.forcePOTTextures = false;
  7681. this.isFullscreen = false;
  7682. this.isPointerLock = false;
  7683. this.cullBackFaces = true;
  7684. this.renderEvenInBackground = true;
  7685. this.preventCacheWipeBetweenFrames = false;
  7686. // To enable/disable IDB support and avoid XHR on .manifest
  7687. this.enableOfflineSupport = false;
  7688. this.scenes = new Array();
  7689. this.postProcesses = new Array();
  7690. // Observables
  7691. /**
  7692. * Observable event triggered each time the rendering canvas is resized
  7693. */
  7694. this.onResizeObservable = new BABYLON.Observable();
  7695. /**
  7696. * Observable event triggered each time the canvas loses focus
  7697. */
  7698. this.onCanvasBlurObservable = new BABYLON.Observable();
  7699. /**
  7700. * Observable event triggered each time the canvas gains focus
  7701. */
  7702. this.onCanvasFocusObservable = new BABYLON.Observable();
  7703. /**
  7704. * Observable event triggered each time the canvas receives pointerout event
  7705. */
  7706. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7707. /**
  7708. * Observable event triggered before each texture is initialized
  7709. */
  7710. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7711. //WebVR
  7712. this._vrDisplay = undefined;
  7713. this._vrSupported = false;
  7714. this._vrExclusivePointerMode = false;
  7715. // Uniform buffers list
  7716. this.disableUniformBuffers = false;
  7717. this._uniformBuffers = new Array();
  7718. this._windowIsBackground = false;
  7719. this._webGLVersion = 1.0;
  7720. this._badOS = false;
  7721. this._badDesktopOS = false;
  7722. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7723. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7724. this.onVRRequestPresentStart = new BABYLON.Observable();
  7725. this._colorWrite = true;
  7726. this._drawCalls = new BABYLON.PerfCounter();
  7727. this._renderingQueueLaunched = false;
  7728. this._activeRenderLoops = new Array();
  7729. // Deterministic lockstepMaxSteps
  7730. this._deterministicLockstep = false;
  7731. this._lockstepMaxSteps = 4;
  7732. // Lost context
  7733. this.onContextLostObservable = new BABYLON.Observable();
  7734. this.onContextRestoredObservable = new BABYLON.Observable();
  7735. this._contextWasLost = false;
  7736. this._doNotHandleContextLost = false;
  7737. // FPS
  7738. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7739. this._fps = 60;
  7740. this._deltaTime = 0;
  7741. /**
  7742. * Turn this value on if you want to pause FPS computation when in background
  7743. */
  7744. this.disablePerformanceMonitorInBackground = false;
  7745. // States
  7746. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7747. this._stencilState = new BABYLON.Internals._StencilState();
  7748. this._alphaState = new BABYLON.Internals._AlphaState();
  7749. this._alphaMode = Engine.ALPHA_DISABLE;
  7750. // Cache
  7751. this._internalTexturesCache = new Array();
  7752. this._maxTextureChannels = 16;
  7753. this._activeTexturesCache = {};
  7754. this._compiledEffects = {};
  7755. this._vertexAttribArraysEnabled = [];
  7756. this._uintIndicesCurrentlySet = false;
  7757. this._currentBoundBuffer = new Array();
  7758. this._currentBufferPointers = new Array();
  7759. this._currentInstanceLocations = new Array();
  7760. this._currentInstanceBuffers = new Array();
  7761. this._vaoRecordInProgress = false;
  7762. this._mustWipeVertexAttributes = false;
  7763. // Hardware supported Compressed Textures
  7764. this._texturesSupported = new Array();
  7765. this._onVRFullScreenTriggered = function () {
  7766. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7767. //get the old size before we change
  7768. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7769. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7770. //get the width and height, change the render size
  7771. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7772. var width, height;
  7773. _this.setHardwareScalingLevel(1);
  7774. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7775. }
  7776. else {
  7777. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7778. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7779. }
  7780. };
  7781. var canvas;
  7782. Engine.Instances.push(this);
  7783. if (!canvasOrContext) {
  7784. return;
  7785. }
  7786. options = options || {};
  7787. if (canvasOrContext.getContext) {
  7788. canvas = canvasOrContext;
  7789. this._renderingCanvas = canvas;
  7790. if (antialias != null) {
  7791. options.antialias = antialias;
  7792. }
  7793. if (options.deterministicLockstep === undefined) {
  7794. options.deterministicLockstep = false;
  7795. }
  7796. if (options.lockstepMaxSteps === undefined) {
  7797. options.lockstepMaxSteps = 4;
  7798. }
  7799. if (options.preserveDrawingBuffer === undefined) {
  7800. options.preserveDrawingBuffer = false;
  7801. }
  7802. if (options.audioEngine === undefined) {
  7803. options.audioEngine = true;
  7804. }
  7805. if (options.stencil === undefined) {
  7806. options.stencil = true;
  7807. }
  7808. this._deterministicLockstep = options.deterministicLockstep;
  7809. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7810. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7811. // GL
  7812. if (!options.disableWebGL2Support) {
  7813. try {
  7814. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7815. if (this._gl) {
  7816. this._webGLVersion = 2.0;
  7817. }
  7818. }
  7819. catch (e) {
  7820. // Do nothing
  7821. }
  7822. }
  7823. if (!this._gl) {
  7824. if (!canvas) {
  7825. throw new Error("The provided canvas is null or undefined.");
  7826. }
  7827. try {
  7828. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7829. }
  7830. catch (e) {
  7831. throw new Error("WebGL not supported");
  7832. }
  7833. }
  7834. if (!this._gl) {
  7835. throw new Error("WebGL not supported");
  7836. }
  7837. this._onCanvasFocus = function () {
  7838. _this.onCanvasFocusObservable.notifyObservers(_this);
  7839. };
  7840. this._onCanvasBlur = function () {
  7841. _this.onCanvasBlurObservable.notifyObservers(_this);
  7842. };
  7843. canvas.addEventListener("focus", this._onCanvasFocus);
  7844. canvas.addEventListener("blur", this._onCanvasBlur);
  7845. this._onBlur = function () {
  7846. if (_this.disablePerformanceMonitorInBackground) {
  7847. _this._performanceMonitor.disable();
  7848. }
  7849. _this._windowIsBackground = true;
  7850. };
  7851. this._onFocus = function () {
  7852. if (_this.disablePerformanceMonitorInBackground) {
  7853. _this._performanceMonitor.enable();
  7854. }
  7855. _this._windowIsBackground = false;
  7856. };
  7857. this._onCanvasPointerOut = function () {
  7858. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7859. };
  7860. window.addEventListener("blur", this._onBlur);
  7861. window.addEventListener("focus", this._onFocus);
  7862. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7863. // Context lost
  7864. if (!this._doNotHandleContextLost) {
  7865. this._onContextLost = function (evt) {
  7866. evt.preventDefault();
  7867. _this._contextWasLost = true;
  7868. BABYLON.Tools.Warn("WebGL context lost.");
  7869. _this.onContextLostObservable.notifyObservers(_this);
  7870. };
  7871. this._onContextRestored = function (evt) {
  7872. // Adding a timeout to avoid race condition at browser level
  7873. setTimeout(function () {
  7874. // Rebuild gl context
  7875. _this._initGLContext();
  7876. // Rebuild effects
  7877. _this._rebuildEffects();
  7878. // Rebuild textures
  7879. _this._rebuildInternalTextures();
  7880. // Rebuild buffers
  7881. _this._rebuildBuffers();
  7882. // Cache
  7883. _this.wipeCaches(true);
  7884. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7885. _this.onContextRestoredObservable.notifyObservers(_this);
  7886. _this._contextWasLost = false;
  7887. }, 0);
  7888. };
  7889. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7890. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7891. }
  7892. }
  7893. else {
  7894. this._gl = canvasOrContext;
  7895. this._renderingCanvas = this._gl.canvas;
  7896. if (this._gl.renderbufferStorageMultisample) {
  7897. this._webGLVersion = 2.0;
  7898. }
  7899. options.stencil = this._gl.getContextAttributes().stencil;
  7900. }
  7901. // Viewport
  7902. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7903. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7904. this.resize();
  7905. this._isStencilEnable = options.stencil;
  7906. this._initGLContext();
  7907. if (canvas) {
  7908. // Fullscreen
  7909. this._onFullscreenChange = function () {
  7910. if (document.fullscreen !== undefined) {
  7911. _this.isFullscreen = document.fullscreen;
  7912. }
  7913. else if (document.mozFullScreen !== undefined) {
  7914. _this.isFullscreen = document.mozFullScreen;
  7915. }
  7916. else if (document.webkitIsFullScreen !== undefined) {
  7917. _this.isFullscreen = document.webkitIsFullScreen;
  7918. }
  7919. else if (document.msIsFullScreen !== undefined) {
  7920. _this.isFullscreen = document.msIsFullScreen;
  7921. }
  7922. // Pointer lock
  7923. if (_this.isFullscreen && _this._pointerLockRequested) {
  7924. canvas.requestPointerLock = canvas.requestPointerLock ||
  7925. canvas.msRequestPointerLock ||
  7926. canvas.mozRequestPointerLock ||
  7927. canvas.webkitRequestPointerLock;
  7928. if (canvas.requestPointerLock) {
  7929. canvas.requestPointerLock();
  7930. }
  7931. }
  7932. };
  7933. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7934. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7935. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7936. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7937. // Pointer lock
  7938. this._onPointerLockChange = function () {
  7939. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7940. document.webkitPointerLockElement === canvas ||
  7941. document.msPointerLockElement === canvas ||
  7942. document.pointerLockElement === canvas);
  7943. };
  7944. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7945. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7946. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7947. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7948. this._onVRDisplayPointerRestricted = function () {
  7949. canvas.requestPointerLock();
  7950. };
  7951. this._onVRDisplayPointerUnrestricted = function () {
  7952. document.exitPointerLock();
  7953. };
  7954. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7955. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7956. }
  7957. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7958. Engine.audioEngine = new BABYLON.AudioEngine();
  7959. }
  7960. // Prepare buffer pointers
  7961. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7962. this._currentBufferPointers[i] = new BufferPointer();
  7963. }
  7964. // Load WebVR Devices
  7965. if (options.autoEnableWebVR) {
  7966. this.initWebVR();
  7967. }
  7968. // Detect if we are running on a faulty buggy OS.
  7969. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7970. // Detect if we are running on a faulty buggy desktop OS.
  7971. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7972. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7973. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7974. }
  7975. Object.defineProperty(Engine, "LastCreatedEngine", {
  7976. get: function () {
  7977. if (Engine.Instances.length === 0) {
  7978. return null;
  7979. }
  7980. return Engine.Instances[Engine.Instances.length - 1];
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Engine, "LastCreatedScene", {
  7986. get: function () {
  7987. var lastCreatedEngine = Engine.LastCreatedEngine;
  7988. if (!lastCreatedEngine) {
  7989. return null;
  7990. }
  7991. if (lastCreatedEngine.scenes.length === 0) {
  7992. return null;
  7993. }
  7994. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. /**
  8000. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8001. */
  8002. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8003. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8004. var engine = Engine.Instances[engineIndex];
  8005. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8006. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8007. }
  8008. }
  8009. };
  8010. Object.defineProperty(Engine, "NEVER", {
  8011. get: function () {
  8012. return Engine._NEVER;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine, "ALWAYS", {
  8018. get: function () {
  8019. return Engine._ALWAYS;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine, "LESS", {
  8025. get: function () {
  8026. return Engine._LESS;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine, "EQUAL", {
  8032. get: function () {
  8033. return Engine._EQUAL;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine, "LEQUAL", {
  8039. get: function () {
  8040. return Engine._LEQUAL;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine, "GREATER", {
  8046. get: function () {
  8047. return Engine._GREATER;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine, "GEQUAL", {
  8053. get: function () {
  8054. return Engine._GEQUAL;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine, "NOTEQUAL", {
  8060. get: function () {
  8061. return Engine._NOTEQUAL;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Engine, "KEEP", {
  8067. get: function () {
  8068. return Engine._KEEP;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Engine, "REPLACE", {
  8074. get: function () {
  8075. return Engine._REPLACE;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Engine, "INCR", {
  8081. get: function () {
  8082. return Engine._INCR;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Engine, "DECR", {
  8088. get: function () {
  8089. return Engine._DECR;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Engine, "INVERT", {
  8095. get: function () {
  8096. return Engine._INVERT;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(Engine, "INCR_WRAP", {
  8102. get: function () {
  8103. return Engine._INCR_WRAP;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine, "DECR_WRAP", {
  8109. get: function () {
  8110. return Engine._DECR_WRAP;
  8111. },
  8112. enumerable: true,
  8113. configurable: true
  8114. });
  8115. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8116. get: function () {
  8117. return Engine._ALPHA_DISABLE;
  8118. },
  8119. enumerable: true,
  8120. configurable: true
  8121. });
  8122. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8123. get: function () {
  8124. return Engine._ALPHA_ONEONE;
  8125. },
  8126. enumerable: true,
  8127. configurable: true
  8128. });
  8129. Object.defineProperty(Engine, "ALPHA_ADD", {
  8130. get: function () {
  8131. return Engine._ALPHA_ADD;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8137. get: function () {
  8138. return Engine._ALPHA_COMBINE;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8144. get: function () {
  8145. return Engine._ALPHA_SUBTRACT;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8151. get: function () {
  8152. return Engine._ALPHA_MULTIPLY;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8158. get: function () {
  8159. return Engine._ALPHA_MAXIMIZED;
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8165. get: function () {
  8166. return Engine._ALPHA_PREMULTIPLIED;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8172. get: function () {
  8173. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8179. get: function () {
  8180. return Engine._ALPHA_INTERPOLATE;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8186. get: function () {
  8187. return Engine._ALPHA_SCREENMODE;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8193. get: function () {
  8194. return Engine._DELAYLOADSTATE_NONE;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8200. get: function () {
  8201. return Engine._DELAYLOADSTATE_LOADED;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8207. get: function () {
  8208. return Engine._DELAYLOADSTATE_LOADING;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8214. get: function () {
  8215. return Engine._DELAYLOADSTATE_NOTLOADED;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8221. get: function () {
  8222. return Engine._TEXTUREFORMAT_ALPHA;
  8223. },
  8224. enumerable: true,
  8225. configurable: true
  8226. });
  8227. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8228. get: function () {
  8229. return Engine._TEXTUREFORMAT_LUMINANCE;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8235. get: function () {
  8236. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8237. },
  8238. enumerable: true,
  8239. configurable: true
  8240. });
  8241. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8242. get: function () {
  8243. return Engine._TEXTUREFORMAT_RGB;
  8244. },
  8245. enumerable: true,
  8246. configurable: true
  8247. });
  8248. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8249. get: function () {
  8250. return Engine._TEXTUREFORMAT_RGBA;
  8251. },
  8252. enumerable: true,
  8253. configurable: true
  8254. });
  8255. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8256. get: function () {
  8257. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8258. },
  8259. enumerable: true,
  8260. configurable: true
  8261. });
  8262. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8263. get: function () {
  8264. return Engine._TEXTURETYPE_FLOAT;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8270. get: function () {
  8271. return Engine._TEXTURETYPE_HALF_FLOAT;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8277. get: function () {
  8278. return Engine._SCALEMODE_FLOOR;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8284. get: function () {
  8285. return Engine._SCALEMODE_NEAREST;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8291. get: function () {
  8292. return Engine._SCALEMODE_CEILING;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(Engine, "Version", {
  8298. get: function () {
  8299. return "3.1-alpha";
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8305. get: function () {
  8306. return this._vrExclusivePointerMode;
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8312. get: function () {
  8313. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8319. get: function () {
  8320. return this._webGLVersion < 2 || this.forcePOTTextures;
  8321. },
  8322. enumerable: true,
  8323. configurable: true
  8324. });
  8325. Object.defineProperty(Engine.prototype, "badOS", {
  8326. get: function () {
  8327. return this._badOS;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8333. get: function () {
  8334. return this._badDesktopOS;
  8335. },
  8336. enumerable: true,
  8337. configurable: true
  8338. });
  8339. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8340. get: function () {
  8341. return this._performanceMonitor;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8347. get: function () {
  8348. return this._texturesSupported;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8354. get: function () {
  8355. return this._textureFormatInUse;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Engine.prototype, "currentViewport", {
  8361. get: function () {
  8362. return this._cachedViewport;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8368. // Empty texture
  8369. get: function () {
  8370. if (!this._emptyTexture) {
  8371. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8372. }
  8373. return this._emptyTexture;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8379. get: function () {
  8380. if (!this._emptyCubeTexture) {
  8381. var faceData = new Uint8Array(4);
  8382. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8383. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8384. }
  8385. return this._emptyCubeTexture;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Engine.prototype._rebuildInternalTextures = function () {
  8391. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8392. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8393. var internalTexture = currentState_1[_i];
  8394. internalTexture._rebuild();
  8395. }
  8396. };
  8397. Engine.prototype._rebuildEffects = function () {
  8398. for (var key in this._compiledEffects) {
  8399. var effect = this._compiledEffects[key];
  8400. effect._prepareEffect();
  8401. }
  8402. BABYLON.Effect.ResetCache();
  8403. };
  8404. Engine.prototype._rebuildBuffers = function () {
  8405. // Index / Vertex
  8406. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8407. var scene = _a[_i];
  8408. scene.resetCachedMaterial();
  8409. scene._rebuildGeometries();
  8410. scene._rebuildTextures();
  8411. }
  8412. // Uniforms
  8413. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8414. var uniformBuffer = _c[_b];
  8415. uniformBuffer._rebuild();
  8416. }
  8417. };
  8418. Engine.prototype._initGLContext = function () {
  8419. // Caps
  8420. this._caps = new EngineCapabilities();
  8421. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8422. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8423. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8424. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8425. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8426. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8427. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8428. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8429. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8430. // Infos
  8431. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8432. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8433. if (rendererInfo != null) {
  8434. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8435. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8436. }
  8437. if (!this._glVendor) {
  8438. this._glVendor = "Unknown vendor";
  8439. }
  8440. if (!this._glRenderer) {
  8441. this._glRenderer = "Unknown renderer";
  8442. }
  8443. // Constants
  8444. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8445. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8446. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8447. this._gl.DEPTH24_STENCIL8 = 35056;
  8448. // Extensions
  8449. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8450. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8451. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8452. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8453. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8454. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8455. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8456. 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');
  8457. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8458. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8459. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8460. this._caps.highPrecisionShaderSupported = true;
  8461. // Checks if some of the format renders first to allow the use of webgl inspector.
  8462. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8463. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8464. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8465. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8466. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8467. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8468. if (this._webGLVersion > 1) {
  8469. this._gl.HALF_FLOAT_OES = 0x140B;
  8470. }
  8471. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8472. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8473. // Draw buffers
  8474. if (this._webGLVersion > 1) {
  8475. this._caps.drawBuffersExtension = true;
  8476. }
  8477. else {
  8478. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8479. if (drawBuffersExtension !== null) {
  8480. this._caps.drawBuffersExtension = true;
  8481. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8482. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8483. for (var i = 0; i < 16; i++) {
  8484. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8485. }
  8486. }
  8487. else {
  8488. this._caps.drawBuffersExtension = false;
  8489. }
  8490. }
  8491. // Depth Texture
  8492. if (this._webGLVersion > 1) {
  8493. this._caps.depthTextureExtension = true;
  8494. }
  8495. else {
  8496. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8497. if (depthTextureExtension != null) {
  8498. this._caps.depthTextureExtension = true;
  8499. }
  8500. }
  8501. // Vertex array object
  8502. if (this._webGLVersion > 1) {
  8503. this._caps.vertexArrayObject = true;
  8504. }
  8505. else {
  8506. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8507. if (vertexArrayObjectExtension != null) {
  8508. this._caps.vertexArrayObject = true;
  8509. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8510. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8511. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8512. }
  8513. else {
  8514. this._caps.vertexArrayObject = false;
  8515. }
  8516. }
  8517. // Instances count
  8518. if (this._webGLVersion > 1) {
  8519. this._caps.instancedArrays = true;
  8520. }
  8521. else {
  8522. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8523. if (instanceExtension != null) {
  8524. this._caps.instancedArrays = true;
  8525. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8526. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8527. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8528. }
  8529. else {
  8530. this._caps.instancedArrays = false;
  8531. }
  8532. }
  8533. // Intelligently add supported compressed formats in order to check for.
  8534. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8535. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8536. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8537. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8538. if (this._caps.astc)
  8539. this.texturesSupported.push('-astc.ktx');
  8540. if (this._caps.s3tc)
  8541. this.texturesSupported.push('-dxt.ktx');
  8542. if (this._caps.pvrtc)
  8543. this.texturesSupported.push('-pvrtc.ktx');
  8544. if (this._caps.etc2)
  8545. this.texturesSupported.push('-etc2.ktx');
  8546. if (this._caps.etc1)
  8547. this.texturesSupported.push('-etc1.ktx');
  8548. if (this._gl.getShaderPrecisionFormat) {
  8549. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8550. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8551. }
  8552. // Depth buffer
  8553. this.setDepthBuffer(true);
  8554. this.setDepthFunctionToLessOrEqual();
  8555. this.setDepthWrite(true);
  8556. };
  8557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8558. get: function () {
  8559. return this._webGLVersion;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8565. /**
  8566. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8567. */
  8568. get: function () {
  8569. return this._isStencilEnable;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Engine.prototype._prepareWorkingCanvas = function () {
  8575. if (this._workingCanvas) {
  8576. return;
  8577. }
  8578. this._workingCanvas = document.createElement("canvas");
  8579. this._workingContext = this._workingCanvas.getContext("2d");
  8580. };
  8581. Engine.prototype.resetTextureCache = function () {
  8582. for (var key in this._activeTexturesCache) {
  8583. this._activeTexturesCache[key] = null;
  8584. }
  8585. };
  8586. Engine.prototype.isDeterministicLockStep = function () {
  8587. return this._deterministicLockstep;
  8588. };
  8589. Engine.prototype.getLockstepMaxSteps = function () {
  8590. return this._lockstepMaxSteps;
  8591. };
  8592. Engine.prototype.getGlInfo = function () {
  8593. return {
  8594. vendor: this._glVendor,
  8595. renderer: this._glRenderer,
  8596. version: this._glVersion
  8597. };
  8598. };
  8599. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8600. if (useScreen === void 0) { useScreen = false; }
  8601. var viewport = camera.viewport;
  8602. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8603. };
  8604. Engine.prototype.getRenderWidth = function (useScreen) {
  8605. if (useScreen === void 0) { useScreen = false; }
  8606. if (!useScreen && this._currentRenderTarget) {
  8607. return this._currentRenderTarget.width;
  8608. }
  8609. return this._gl.drawingBufferWidth;
  8610. };
  8611. Engine.prototype.getRenderHeight = function (useScreen) {
  8612. if (useScreen === void 0) { useScreen = false; }
  8613. if (!useScreen && this._currentRenderTarget) {
  8614. return this._currentRenderTarget.height;
  8615. }
  8616. return this._gl.drawingBufferHeight;
  8617. };
  8618. Engine.prototype.getRenderingCanvas = function () {
  8619. return this._renderingCanvas;
  8620. };
  8621. Engine.prototype.getRenderingCanvasClientRect = function () {
  8622. return this._renderingCanvas.getBoundingClientRect();
  8623. };
  8624. Engine.prototype.setHardwareScalingLevel = function (level) {
  8625. this._hardwareScalingLevel = level;
  8626. this.resize();
  8627. };
  8628. Engine.prototype.getHardwareScalingLevel = function () {
  8629. return this._hardwareScalingLevel;
  8630. };
  8631. Engine.prototype.getLoadedTexturesCache = function () {
  8632. return this._internalTexturesCache;
  8633. };
  8634. Engine.prototype.getCaps = function () {
  8635. return this._caps;
  8636. };
  8637. Object.defineProperty(Engine.prototype, "drawCalls", {
  8638. /** The number of draw calls submitted last frame */
  8639. get: function () {
  8640. return this._drawCalls.current;
  8641. },
  8642. enumerable: true,
  8643. configurable: true
  8644. });
  8645. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8646. get: function () {
  8647. return this._drawCalls;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Engine.prototype.getDepthFunction = function () {
  8653. return this._depthCullingState.depthFunc;
  8654. };
  8655. Engine.prototype.setDepthFunction = function (depthFunc) {
  8656. this._depthCullingState.depthFunc = depthFunc;
  8657. };
  8658. Engine.prototype.setDepthFunctionToGreater = function () {
  8659. this._depthCullingState.depthFunc = this._gl.GREATER;
  8660. };
  8661. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8662. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8663. };
  8664. Engine.prototype.setDepthFunctionToLess = function () {
  8665. this._depthCullingState.depthFunc = this._gl.LESS;
  8666. };
  8667. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8668. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8669. };
  8670. Engine.prototype.getStencilBuffer = function () {
  8671. return this._stencilState.stencilTest;
  8672. };
  8673. Engine.prototype.setStencilBuffer = function (enable) {
  8674. this._stencilState.stencilTest = enable;
  8675. };
  8676. Engine.prototype.getStencilMask = function () {
  8677. return this._stencilState.stencilMask;
  8678. };
  8679. Engine.prototype.setStencilMask = function (mask) {
  8680. this._stencilState.stencilMask = mask;
  8681. };
  8682. Engine.prototype.getStencilFunction = function () {
  8683. return this._stencilState.stencilFunc;
  8684. };
  8685. Engine.prototype.getStencilFunctionReference = function () {
  8686. return this._stencilState.stencilFuncRef;
  8687. };
  8688. Engine.prototype.getStencilFunctionMask = function () {
  8689. return this._stencilState.stencilFuncMask;
  8690. };
  8691. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8692. this._stencilState.stencilFunc = stencilFunc;
  8693. };
  8694. Engine.prototype.setStencilFunctionReference = function (reference) {
  8695. this._stencilState.stencilFuncRef = reference;
  8696. };
  8697. Engine.prototype.setStencilFunctionMask = function (mask) {
  8698. this._stencilState.stencilFuncMask = mask;
  8699. };
  8700. Engine.prototype.getStencilOperationFail = function () {
  8701. return this._stencilState.stencilOpStencilFail;
  8702. };
  8703. Engine.prototype.getStencilOperationDepthFail = function () {
  8704. return this._stencilState.stencilOpDepthFail;
  8705. };
  8706. Engine.prototype.getStencilOperationPass = function () {
  8707. return this._stencilState.stencilOpStencilDepthPass;
  8708. };
  8709. Engine.prototype.setStencilOperationFail = function (operation) {
  8710. this._stencilState.stencilOpStencilFail = operation;
  8711. };
  8712. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8713. this._stencilState.stencilOpDepthFail = operation;
  8714. };
  8715. Engine.prototype.setStencilOperationPass = function (operation) {
  8716. this._stencilState.stencilOpStencilDepthPass = operation;
  8717. };
  8718. Engine.prototype.setDitheringState = function (value) {
  8719. if (value) {
  8720. this._gl.enable(this._gl.DITHER);
  8721. }
  8722. else {
  8723. this._gl.disable(this._gl.DITHER);
  8724. }
  8725. };
  8726. /**
  8727. * stop executing a render loop function and remove it from the execution array
  8728. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8729. */
  8730. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8731. if (!renderFunction) {
  8732. this._activeRenderLoops = [];
  8733. return;
  8734. }
  8735. var index = this._activeRenderLoops.indexOf(renderFunction);
  8736. if (index >= 0) {
  8737. this._activeRenderLoops.splice(index, 1);
  8738. }
  8739. };
  8740. Engine.prototype._renderLoop = function () {
  8741. if (!this._contextWasLost) {
  8742. var shouldRender = true;
  8743. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8744. shouldRender = false;
  8745. }
  8746. if (shouldRender) {
  8747. // Start new frame
  8748. this.beginFrame();
  8749. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8750. var renderFunction = this._activeRenderLoops[index];
  8751. renderFunction();
  8752. }
  8753. // Present
  8754. this.endFrame();
  8755. }
  8756. }
  8757. if (this._activeRenderLoops.length > 0) {
  8758. // Register new frame
  8759. var requester = null;
  8760. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8761. requester = this._vrDisplay;
  8762. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8763. }
  8764. else {
  8765. this._renderingQueueLaunched = false;
  8766. }
  8767. };
  8768. /**
  8769. * Register and execute a render loop. The engine can have more than one render function.
  8770. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8771. * @example
  8772. * engine.runRenderLoop(function () {
  8773. * scene.render()
  8774. * })
  8775. */
  8776. Engine.prototype.runRenderLoop = function (renderFunction) {
  8777. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8778. return;
  8779. }
  8780. this._activeRenderLoops.push(renderFunction);
  8781. if (!this._renderingQueueLaunched) {
  8782. this._renderingQueueLaunched = true;
  8783. this._bindedRenderFunction = this._renderLoop.bind(this);
  8784. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8785. }
  8786. };
  8787. /**
  8788. * Toggle full screen mode.
  8789. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8790. * @param {any} options - an options object to be sent to the requestFullscreen function
  8791. */
  8792. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8793. if (this.isFullscreen) {
  8794. BABYLON.Tools.ExitFullscreen();
  8795. }
  8796. else {
  8797. this._pointerLockRequested = requestPointerLock;
  8798. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8799. }
  8800. };
  8801. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8802. if (stencil === void 0) { stencil = false; }
  8803. this.applyStates();
  8804. var mode = 0;
  8805. if (backBuffer && color) {
  8806. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8807. mode |= this._gl.COLOR_BUFFER_BIT;
  8808. }
  8809. if (depth) {
  8810. this._gl.clearDepth(1.0);
  8811. mode |= this._gl.DEPTH_BUFFER_BIT;
  8812. }
  8813. if (stencil) {
  8814. this._gl.clearStencil(0);
  8815. mode |= this._gl.STENCIL_BUFFER_BIT;
  8816. }
  8817. this._gl.clear(mode);
  8818. };
  8819. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8820. var gl = this._gl;
  8821. // Save state
  8822. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8823. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8824. // Change state
  8825. gl.enable(gl.SCISSOR_TEST);
  8826. gl.scissor(x, y, width, height);
  8827. // Clear
  8828. this.clear(clearColor, true, true, true);
  8829. // Restore state
  8830. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8831. if (curScissor === true) {
  8832. gl.enable(gl.SCISSOR_TEST);
  8833. }
  8834. else {
  8835. gl.disable(gl.SCISSOR_TEST);
  8836. }
  8837. };
  8838. /**
  8839. * Set the WebGL's viewport
  8840. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8841. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8842. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8843. */
  8844. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8845. var width = requiredWidth || this.getRenderWidth();
  8846. var height = requiredHeight || this.getRenderHeight();
  8847. var x = viewport.x || 0;
  8848. var y = viewport.y || 0;
  8849. this._cachedViewport = viewport;
  8850. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8851. };
  8852. /**
  8853. * Directly set the WebGL Viewport
  8854. * The x, y, width & height are directly passed to the WebGL call
  8855. * @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.
  8856. */
  8857. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8858. var currentViewport = this._cachedViewport;
  8859. this._cachedViewport = null;
  8860. this._gl.viewport(x, y, width, height);
  8861. return currentViewport;
  8862. };
  8863. Engine.prototype.beginFrame = function () {
  8864. this._measureFps();
  8865. };
  8866. Engine.prototype.endFrame = function () {
  8867. //force a flush in case we are using a bad OS.
  8868. if (this._badOS) {
  8869. this.flushFramebuffer();
  8870. }
  8871. //submit frame to the vr device, if enabled
  8872. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8873. // TODO: We should only submit the frame if we read frameData successfully.
  8874. this._vrDisplay.submitFrame();
  8875. }
  8876. };
  8877. /**
  8878. * resize the view according to the canvas' size.
  8879. * @example
  8880. * window.addEventListener("resize", function () {
  8881. * engine.resize();
  8882. * });
  8883. */
  8884. Engine.prototype.resize = function () {
  8885. // We're not resizing the size of the canvas while in VR mode & presenting
  8886. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  8887. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8888. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8889. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8890. }
  8891. };
  8892. /**
  8893. * force a specific size of the canvas
  8894. * @param {number} width - the new canvas' width
  8895. * @param {number} height - the new canvas' height
  8896. */
  8897. Engine.prototype.setSize = function (width, height) {
  8898. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8899. return;
  8900. }
  8901. this._renderingCanvas.width = width;
  8902. this._renderingCanvas.height = height;
  8903. for (var index = 0; index < this.scenes.length; index++) {
  8904. var scene = this.scenes[index];
  8905. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8906. var cam = scene.cameras[camIndex];
  8907. cam._currentRenderId = 0;
  8908. }
  8909. }
  8910. if (this.onResizeObservable.hasObservers) {
  8911. this.onResizeObservable.notifyObservers(this);
  8912. }
  8913. };
  8914. // WebVR functions
  8915. Engine.prototype.isVRDevicePresent = function () {
  8916. return !!this._vrDisplay;
  8917. };
  8918. Engine.prototype.getVRDevice = function () {
  8919. return this._vrDisplay;
  8920. };
  8921. Engine.prototype.initWebVR = function () {
  8922. var _this = this;
  8923. var notifyObservers = function () {
  8924. var eventArgs = {
  8925. vrDisplay: _this._vrDisplay,
  8926. vrSupported: _this._vrSupported
  8927. };
  8928. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  8929. };
  8930. if (!this._onVrDisplayConnect) {
  8931. this._onVrDisplayConnect = function (event) {
  8932. _this._vrDisplay = event.display;
  8933. notifyObservers();
  8934. };
  8935. this._onVrDisplayDisconnect = function () {
  8936. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  8937. _this._vrDisplay = undefined;
  8938. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  8939. notifyObservers();
  8940. };
  8941. this._onVrDisplayPresentChange = function () {
  8942. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  8943. };
  8944. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  8945. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  8946. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  8947. }
  8948. this._getVRDisplays(notifyObservers);
  8949. return this.onVRDisplayChangedObservable;
  8950. };
  8951. Engine.prototype.enableVR = function () {
  8952. var _this = this;
  8953. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  8954. var onResolved = function () {
  8955. _this.onVRRequestPresentComplete.notifyObservers(true);
  8956. _this._onVRFullScreenTriggered();
  8957. };
  8958. var onRejected = function () {
  8959. _this.onVRRequestPresentComplete.notifyObservers(false);
  8960. };
  8961. this.onVRRequestPresentStart.notifyObservers(this);
  8962. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  8963. }
  8964. };
  8965. Engine.prototype.disableVR = function () {
  8966. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8967. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  8968. }
  8969. };
  8970. Engine.prototype._getVRDisplays = function (callback) {
  8971. var _this = this;
  8972. var getWebVRDevices = function (devices) {
  8973. _this._vrSupported = true;
  8974. // note that devices may actually be an empty array. This is fine;
  8975. // we expect this._vrDisplay to be undefined in this case.
  8976. return _this._vrDisplay = devices[0];
  8977. };
  8978. if (navigator.getVRDisplays) {
  8979. // TODO: Backwards compatible for 1.0?
  8980. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  8981. // TODO: System CANNOT support WebVR, despite API presence.
  8982. _this._vrSupported = false;
  8983. callback();
  8984. });
  8985. }
  8986. else {
  8987. // TODO: Browser does not support WebVR
  8988. this._vrDisplay = undefined;
  8989. this._vrSupported = false;
  8990. callback();
  8991. }
  8992. };
  8993. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8994. if (this._currentRenderTarget) {
  8995. this.unBindFramebuffer(this._currentRenderTarget);
  8996. }
  8997. this._currentRenderTarget = texture;
  8998. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8999. var gl = this._gl;
  9000. if (texture.isCube) {
  9001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9002. }
  9003. if (this._cachedViewport && !forceFullscreenViewport) {
  9004. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9005. }
  9006. else {
  9007. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9008. }
  9009. this.wipeCaches();
  9010. };
  9011. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9012. if (this._currentFramebuffer !== framebuffer) {
  9013. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9014. this._currentFramebuffer = framebuffer;
  9015. }
  9016. };
  9017. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9018. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9019. this._currentRenderTarget = null;
  9020. // If MSAA, we need to bitblt back to main texture
  9021. var gl = this._gl;
  9022. if (texture._MSAAFramebuffer) {
  9023. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9024. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9025. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9026. }
  9027. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9028. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9029. gl.generateMipmap(gl.TEXTURE_2D);
  9030. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9031. }
  9032. if (onBeforeUnbind) {
  9033. if (texture._MSAAFramebuffer) {
  9034. // Bind the correct framebuffer
  9035. this.bindUnboundFramebuffer(texture._framebuffer);
  9036. }
  9037. onBeforeUnbind();
  9038. }
  9039. this.bindUnboundFramebuffer(null);
  9040. };
  9041. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9042. if (texture.generateMipMaps) {
  9043. var gl = this._gl;
  9044. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9045. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9046. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9047. }
  9048. };
  9049. Engine.prototype.flushFramebuffer = function () {
  9050. this._gl.flush();
  9051. };
  9052. Engine.prototype.restoreDefaultFramebuffer = function () {
  9053. if (this._currentRenderTarget) {
  9054. this.unBindFramebuffer(this._currentRenderTarget);
  9055. }
  9056. else {
  9057. this.bindUnboundFramebuffer(null);
  9058. }
  9059. if (this._cachedViewport) {
  9060. this.setViewport(this._cachedViewport);
  9061. }
  9062. this.wipeCaches();
  9063. };
  9064. // UBOs
  9065. Engine.prototype.createUniformBuffer = function (elements) {
  9066. var ubo = this._gl.createBuffer();
  9067. this.bindUniformBuffer(ubo);
  9068. if (elements instanceof Float32Array) {
  9069. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9070. }
  9071. else {
  9072. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9073. }
  9074. this.bindUniformBuffer(null);
  9075. ubo.references = 1;
  9076. return ubo;
  9077. };
  9078. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9079. var ubo = this._gl.createBuffer();
  9080. this.bindUniformBuffer(ubo);
  9081. if (elements instanceof Float32Array) {
  9082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9083. }
  9084. else {
  9085. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9086. }
  9087. this.bindUniformBuffer(null);
  9088. ubo.references = 1;
  9089. return ubo;
  9090. };
  9091. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9092. this.bindUniformBuffer(uniformBuffer);
  9093. if (offset === undefined) {
  9094. offset = 0;
  9095. }
  9096. if (count === undefined) {
  9097. if (elements instanceof Float32Array) {
  9098. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9099. }
  9100. else {
  9101. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9102. }
  9103. }
  9104. else {
  9105. if (elements instanceof Float32Array) {
  9106. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9107. }
  9108. else {
  9109. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9110. }
  9111. }
  9112. this.bindUniformBuffer(null);
  9113. };
  9114. // VBOs
  9115. Engine.prototype._resetVertexBufferBinding = function () {
  9116. this.bindArrayBuffer(null);
  9117. this._cachedVertexBuffers = null;
  9118. };
  9119. Engine.prototype.createVertexBuffer = function (vertices) {
  9120. var vbo = this._gl.createBuffer();
  9121. this.bindArrayBuffer(vbo);
  9122. if (vertices instanceof Float32Array) {
  9123. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9124. }
  9125. else {
  9126. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9127. }
  9128. this._resetVertexBufferBinding();
  9129. vbo.references = 1;
  9130. return vbo;
  9131. };
  9132. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9133. var vbo = this._gl.createBuffer();
  9134. this.bindArrayBuffer(vbo);
  9135. if (vertices instanceof Float32Array) {
  9136. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9137. }
  9138. else {
  9139. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9140. }
  9141. this._resetVertexBufferBinding();
  9142. vbo.references = 1;
  9143. return vbo;
  9144. };
  9145. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9146. if (offset === void 0) { offset = 0; }
  9147. this.bindIndexBuffer(indexBuffer);
  9148. var arrayBuffer;
  9149. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9150. arrayBuffer = indices;
  9151. }
  9152. else {
  9153. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9154. }
  9155. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9156. this._resetIndexBufferBinding();
  9157. };
  9158. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9159. this.bindArrayBuffer(vertexBuffer);
  9160. if (offset === undefined) {
  9161. offset = 0;
  9162. }
  9163. if (count === undefined) {
  9164. if (vertices instanceof Float32Array) {
  9165. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9166. }
  9167. else {
  9168. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9169. }
  9170. }
  9171. else {
  9172. if (vertices instanceof Float32Array) {
  9173. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9174. }
  9175. else {
  9176. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9177. }
  9178. }
  9179. this._resetVertexBufferBinding();
  9180. };
  9181. Engine.prototype._resetIndexBufferBinding = function () {
  9182. this.bindIndexBuffer(null);
  9183. this._cachedIndexBuffer = null;
  9184. };
  9185. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9186. var vbo = this._gl.createBuffer();
  9187. this.bindIndexBuffer(vbo);
  9188. // Check for 32 bits indices
  9189. var arrayBuffer;
  9190. var need32Bits = false;
  9191. if (indices instanceof Uint16Array) {
  9192. arrayBuffer = indices;
  9193. }
  9194. else {
  9195. //check 32 bit support
  9196. if (this._caps.uintIndices) {
  9197. if (indices instanceof Uint32Array) {
  9198. arrayBuffer = indices;
  9199. need32Bits = true;
  9200. }
  9201. else {
  9202. //number[] or Int32Array, check if 32 bit is necessary
  9203. for (var index = 0; index < indices.length; index++) {
  9204. if (indices[index] > 65535) {
  9205. need32Bits = true;
  9206. break;
  9207. }
  9208. }
  9209. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9210. }
  9211. }
  9212. else {
  9213. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9214. arrayBuffer = new Uint16Array(indices);
  9215. }
  9216. }
  9217. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9218. this._resetIndexBufferBinding();
  9219. vbo.references = 1;
  9220. vbo.is32Bits = need32Bits;
  9221. return vbo;
  9222. };
  9223. Engine.prototype.bindArrayBuffer = function (buffer) {
  9224. if (!this._vaoRecordInProgress) {
  9225. this._unbindVertexArrayObject();
  9226. }
  9227. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9228. };
  9229. Engine.prototype.bindUniformBuffer = function (buffer) {
  9230. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9231. };
  9232. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9233. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9234. };
  9235. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9236. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9237. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9238. };
  9239. ;
  9240. Engine.prototype.bindIndexBuffer = function (buffer) {
  9241. if (!this._vaoRecordInProgress) {
  9242. this._unbindVertexArrayObject();
  9243. }
  9244. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9245. };
  9246. Engine.prototype.bindBuffer = function (buffer, target) {
  9247. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9248. this._gl.bindBuffer(target, buffer);
  9249. this._currentBoundBuffer[target] = buffer;
  9250. }
  9251. };
  9252. Engine.prototype.updateArrayBuffer = function (data) {
  9253. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9254. };
  9255. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9256. var pointer = this._currentBufferPointers[indx];
  9257. var changed = false;
  9258. if (!pointer.active) {
  9259. changed = true;
  9260. pointer.active = true;
  9261. pointer.index = indx;
  9262. pointer.size = size;
  9263. pointer.type = type;
  9264. pointer.normalized = normalized;
  9265. pointer.stride = stride;
  9266. pointer.offset = offset;
  9267. pointer.buffer = buffer;
  9268. }
  9269. else {
  9270. if (pointer.buffer !== buffer) {
  9271. pointer.buffer = buffer;
  9272. changed = true;
  9273. }
  9274. if (pointer.size !== size) {
  9275. pointer.size = size;
  9276. changed = true;
  9277. }
  9278. if (pointer.type !== type) {
  9279. pointer.type = type;
  9280. changed = true;
  9281. }
  9282. if (pointer.normalized !== normalized) {
  9283. pointer.normalized = normalized;
  9284. changed = true;
  9285. }
  9286. if (pointer.stride !== stride) {
  9287. pointer.stride = stride;
  9288. changed = true;
  9289. }
  9290. if (pointer.offset !== offset) {
  9291. pointer.offset = offset;
  9292. changed = true;
  9293. }
  9294. }
  9295. if (changed || this._vaoRecordInProgress) {
  9296. this.bindArrayBuffer(buffer);
  9297. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9298. }
  9299. };
  9300. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9301. if (indexBuffer == null) {
  9302. return;
  9303. }
  9304. if (this._cachedIndexBuffer !== indexBuffer) {
  9305. this._cachedIndexBuffer = indexBuffer;
  9306. this.bindIndexBuffer(indexBuffer);
  9307. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9308. }
  9309. };
  9310. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9311. var attributes = effect.getAttributesNames();
  9312. if (!this._vaoRecordInProgress) {
  9313. this._unbindVertexArrayObject();
  9314. }
  9315. this.unbindAllAttributes();
  9316. for (var index = 0; index < attributes.length; index++) {
  9317. var order = effect.getAttributeLocation(index);
  9318. if (order >= 0) {
  9319. var vertexBuffer = vertexBuffers[attributes[index]];
  9320. if (!vertexBuffer) {
  9321. continue;
  9322. }
  9323. this._gl.enableVertexAttribArray(order);
  9324. if (!this._vaoRecordInProgress) {
  9325. this._vertexAttribArraysEnabled[order] = true;
  9326. }
  9327. var buffer = vertexBuffer.getBuffer();
  9328. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9329. if (vertexBuffer.getIsInstanced()) {
  9330. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9331. if (!this._vaoRecordInProgress) {
  9332. this._currentInstanceLocations.push(order);
  9333. this._currentInstanceBuffers.push(buffer);
  9334. }
  9335. }
  9336. }
  9337. }
  9338. };
  9339. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9340. var vao = this._gl.createVertexArray();
  9341. this._vaoRecordInProgress = true;
  9342. this._gl.bindVertexArray(vao);
  9343. this._mustWipeVertexAttributes = true;
  9344. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9345. this.bindIndexBuffer(indexBuffer);
  9346. this._vaoRecordInProgress = false;
  9347. this._gl.bindVertexArray(null);
  9348. return vao;
  9349. };
  9350. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9351. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9352. this._cachedVertexArrayObject = vertexArrayObject;
  9353. this._gl.bindVertexArray(vertexArrayObject);
  9354. this._cachedVertexBuffers = null;
  9355. this._cachedIndexBuffer = null;
  9356. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9357. this._mustWipeVertexAttributes = true;
  9358. }
  9359. };
  9360. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9361. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9362. this._cachedVertexBuffers = vertexBuffer;
  9363. this._cachedEffectForVertexBuffers = effect;
  9364. var attributesCount = effect.getAttributesCount();
  9365. this._unbindVertexArrayObject();
  9366. this.unbindAllAttributes();
  9367. var offset = 0;
  9368. for (var index = 0; index < attributesCount; index++) {
  9369. if (index < vertexDeclaration.length) {
  9370. var order = effect.getAttributeLocation(index);
  9371. if (order >= 0) {
  9372. this._gl.enableVertexAttribArray(order);
  9373. this._vertexAttribArraysEnabled[order] = true;
  9374. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9375. }
  9376. offset += vertexDeclaration[index] * 4;
  9377. }
  9378. }
  9379. }
  9380. this._bindIndexBufferWithCache(indexBuffer);
  9381. };
  9382. Engine.prototype._unbindVertexArrayObject = function () {
  9383. if (!this._cachedVertexArrayObject) {
  9384. return;
  9385. }
  9386. this._cachedVertexArrayObject = null;
  9387. this._gl.bindVertexArray(null);
  9388. };
  9389. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9390. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9391. this._cachedVertexBuffers = vertexBuffers;
  9392. this._cachedEffectForVertexBuffers = effect;
  9393. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9394. }
  9395. this._bindIndexBufferWithCache(indexBuffer);
  9396. };
  9397. Engine.prototype.unbindInstanceAttributes = function () {
  9398. var boundBuffer;
  9399. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9400. var instancesBuffer = this._currentInstanceBuffers[i];
  9401. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9402. boundBuffer = instancesBuffer;
  9403. this.bindArrayBuffer(instancesBuffer);
  9404. }
  9405. var offsetLocation = this._currentInstanceLocations[i];
  9406. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9407. }
  9408. this._currentInstanceBuffers.length = 0;
  9409. this._currentInstanceLocations.length = 0;
  9410. };
  9411. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9412. this._gl.deleteVertexArray(vao);
  9413. };
  9414. Engine.prototype._releaseBuffer = function (buffer) {
  9415. buffer.references--;
  9416. if (buffer.references === 0) {
  9417. this._gl.deleteBuffer(buffer);
  9418. return true;
  9419. }
  9420. return false;
  9421. };
  9422. Engine.prototype.createInstancesBuffer = function (capacity) {
  9423. var buffer = this._gl.createBuffer();
  9424. buffer.capacity = capacity;
  9425. this.bindArrayBuffer(buffer);
  9426. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9427. return buffer;
  9428. };
  9429. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9430. this._gl.deleteBuffer(buffer);
  9431. };
  9432. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9433. this.bindArrayBuffer(instancesBuffer);
  9434. if (data) {
  9435. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9436. }
  9437. if (offsetLocations[0].index !== undefined) {
  9438. var stride = 0;
  9439. for (var i = 0; i < offsetLocations.length; i++) {
  9440. var ai = offsetLocations[i];
  9441. stride += ai.attributeSize * 4;
  9442. }
  9443. for (var i = 0; i < offsetLocations.length; i++) {
  9444. var ai = offsetLocations[i];
  9445. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9446. this._gl.enableVertexAttribArray(ai.index);
  9447. this._vertexAttribArraysEnabled[ai.index] = true;
  9448. }
  9449. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9450. this._gl.vertexAttribDivisor(ai.index, 1);
  9451. this._currentInstanceLocations.push(ai.index);
  9452. this._currentInstanceBuffers.push(instancesBuffer);
  9453. }
  9454. }
  9455. else {
  9456. for (var index = 0; index < 4; index++) {
  9457. var offsetLocation = offsetLocations[index];
  9458. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9459. this._gl.enableVertexAttribArray(offsetLocation);
  9460. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9461. }
  9462. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9463. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9464. this._currentInstanceLocations.push(offsetLocation);
  9465. this._currentInstanceBuffers.push(instancesBuffer);
  9466. }
  9467. }
  9468. };
  9469. Engine.prototype.applyStates = function () {
  9470. this._depthCullingState.apply(this._gl);
  9471. this._stencilState.apply(this._gl);
  9472. this._alphaState.apply(this._gl);
  9473. };
  9474. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9475. // Apply states
  9476. this.applyStates();
  9477. this._drawCalls.addCount(1, false);
  9478. // Render
  9479. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9480. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9481. if (instancesCount) {
  9482. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9483. return;
  9484. }
  9485. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9486. };
  9487. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9488. // Apply states
  9489. this.applyStates();
  9490. this._drawCalls.addCount(1, false);
  9491. if (instancesCount) {
  9492. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9493. return;
  9494. }
  9495. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9496. };
  9497. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9498. // Apply states
  9499. this.applyStates();
  9500. this._drawCalls.addCount(1, false);
  9501. if (instancesCount) {
  9502. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9503. return;
  9504. }
  9505. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9506. };
  9507. // Shaders
  9508. Engine.prototype._releaseEffect = function (effect) {
  9509. if (this._compiledEffects[effect._key]) {
  9510. delete this._compiledEffects[effect._key];
  9511. if (effect.getProgram()) {
  9512. this._gl.deleteProgram(effect.getProgram());
  9513. }
  9514. }
  9515. };
  9516. /**
  9517. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9518. * @param samplers An array of string used to represent textures
  9519. */
  9520. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9521. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9522. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9523. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9524. if (this._compiledEffects[name]) {
  9525. var compiledEffect = this._compiledEffects[name];
  9526. if (onCompiled && compiledEffect.isReady()) {
  9527. onCompiled(compiledEffect);
  9528. }
  9529. return compiledEffect;
  9530. }
  9531. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9532. effect._key = name;
  9533. this._compiledEffects[name] = effect;
  9534. return effect;
  9535. };
  9536. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9537. if (uniformsNames === void 0) { uniformsNames = []; }
  9538. if (samplers === void 0) { samplers = []; }
  9539. if (defines === void 0) { defines = ""; }
  9540. return this.createEffect({
  9541. vertex: "particles",
  9542. fragmentElement: fragmentName
  9543. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9544. };
  9545. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9546. context = context || this._gl;
  9547. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9548. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9549. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9550. var shaderProgram = context.createProgram();
  9551. context.attachShader(shaderProgram, vertexShader);
  9552. context.attachShader(shaderProgram, fragmentShader);
  9553. context.linkProgram(shaderProgram);
  9554. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9555. if (!linked) {
  9556. context.validateProgram(shaderProgram);
  9557. var error = context.getProgramInfoLog(shaderProgram);
  9558. if (error) {
  9559. throw new Error(error);
  9560. }
  9561. }
  9562. context.deleteShader(vertexShader);
  9563. context.deleteShader(fragmentShader);
  9564. return shaderProgram;
  9565. };
  9566. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9567. var results = [];
  9568. for (var index = 0; index < uniformsNames.length; index++) {
  9569. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9570. }
  9571. return results;
  9572. };
  9573. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9574. var results = [];
  9575. for (var index = 0; index < attributesNames.length; index++) {
  9576. try {
  9577. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9578. }
  9579. catch (e) {
  9580. results.push(-1);
  9581. }
  9582. }
  9583. return results;
  9584. };
  9585. Engine.prototype.enableEffect = function (effect) {
  9586. // Use program
  9587. this.setProgram(effect.getProgram());
  9588. this._currentEffect = effect;
  9589. if (effect.onBind) {
  9590. effect.onBind(effect);
  9591. }
  9592. effect.onBindObservable.notifyObservers(effect);
  9593. };
  9594. Engine.prototype.setIntArray = function (uniform, array) {
  9595. if (!uniform)
  9596. return;
  9597. this._gl.uniform1iv(uniform, array);
  9598. };
  9599. Engine.prototype.setIntArray2 = function (uniform, array) {
  9600. if (!uniform || array.length % 2 !== 0)
  9601. return;
  9602. this._gl.uniform2iv(uniform, array);
  9603. };
  9604. Engine.prototype.setIntArray3 = function (uniform, array) {
  9605. if (!uniform || array.length % 3 !== 0)
  9606. return;
  9607. this._gl.uniform3iv(uniform, array);
  9608. };
  9609. Engine.prototype.setIntArray4 = function (uniform, array) {
  9610. if (!uniform || array.length % 4 !== 0)
  9611. return;
  9612. this._gl.uniform4iv(uniform, array);
  9613. };
  9614. Engine.prototype.setFloatArray = function (uniform, array) {
  9615. if (!uniform)
  9616. return;
  9617. this._gl.uniform1fv(uniform, array);
  9618. };
  9619. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9620. if (!uniform || array.length % 2 !== 0)
  9621. return;
  9622. this._gl.uniform2fv(uniform, array);
  9623. };
  9624. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9625. if (!uniform || array.length % 3 !== 0)
  9626. return;
  9627. this._gl.uniform3fv(uniform, array);
  9628. };
  9629. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9630. if (!uniform || array.length % 4 !== 0)
  9631. return;
  9632. this._gl.uniform4fv(uniform, array);
  9633. };
  9634. Engine.prototype.setArray = function (uniform, array) {
  9635. if (!uniform)
  9636. return;
  9637. this._gl.uniform1fv(uniform, array);
  9638. };
  9639. Engine.prototype.setArray2 = function (uniform, array) {
  9640. if (!uniform || array.length % 2 !== 0)
  9641. return;
  9642. this._gl.uniform2fv(uniform, array);
  9643. };
  9644. Engine.prototype.setArray3 = function (uniform, array) {
  9645. if (!uniform || array.length % 3 !== 0)
  9646. return;
  9647. this._gl.uniform3fv(uniform, array);
  9648. };
  9649. Engine.prototype.setArray4 = function (uniform, array) {
  9650. if (!uniform || array.length % 4 !== 0)
  9651. return;
  9652. this._gl.uniform4fv(uniform, array);
  9653. };
  9654. Engine.prototype.setMatrices = function (uniform, matrices) {
  9655. if (!uniform)
  9656. return;
  9657. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9658. };
  9659. Engine.prototype.setMatrix = function (uniform, matrix) {
  9660. if (!uniform)
  9661. return;
  9662. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9663. };
  9664. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9665. if (!uniform)
  9666. return;
  9667. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9668. };
  9669. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9670. if (!uniform)
  9671. return;
  9672. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9673. };
  9674. Engine.prototype.setFloat = function (uniform, value) {
  9675. if (!uniform)
  9676. return;
  9677. this._gl.uniform1f(uniform, value);
  9678. };
  9679. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9680. if (!uniform)
  9681. return;
  9682. this._gl.uniform2f(uniform, x, y);
  9683. };
  9684. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9685. if (!uniform)
  9686. return;
  9687. this._gl.uniform3f(uniform, x, y, z);
  9688. };
  9689. Engine.prototype.setBool = function (uniform, bool) {
  9690. if (!uniform)
  9691. return;
  9692. this._gl.uniform1i(uniform, bool);
  9693. };
  9694. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9695. if (!uniform)
  9696. return;
  9697. this._gl.uniform4f(uniform, x, y, z, w);
  9698. };
  9699. Engine.prototype.setColor3 = function (uniform, color3) {
  9700. if (!uniform)
  9701. return;
  9702. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9703. };
  9704. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9705. if (!uniform)
  9706. return;
  9707. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9708. };
  9709. // States
  9710. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9711. if (zOffset === void 0) { zOffset = 0; }
  9712. if (reverseSide === void 0) { reverseSide = false; }
  9713. // Culling
  9714. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9715. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9716. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9717. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9718. if (culling) {
  9719. this._depthCullingState.cullFace = cullFace;
  9720. this._depthCullingState.cull = true;
  9721. }
  9722. else {
  9723. this._depthCullingState.cull = false;
  9724. }
  9725. }
  9726. // Z offset
  9727. this.setZOffset(zOffset);
  9728. };
  9729. Engine.prototype.setZOffset = function (value) {
  9730. this._depthCullingState.zOffset = value;
  9731. };
  9732. Engine.prototype.getZOffset = function () {
  9733. return this._depthCullingState.zOffset;
  9734. };
  9735. Engine.prototype.setDepthBuffer = function (enable) {
  9736. this._depthCullingState.depthTest = enable;
  9737. };
  9738. Engine.prototype.getDepthWrite = function () {
  9739. return this._depthCullingState.depthMask;
  9740. };
  9741. Engine.prototype.setDepthWrite = function (enable) {
  9742. this._depthCullingState.depthMask = enable;
  9743. };
  9744. Engine.prototype.setColorWrite = function (enable) {
  9745. this._gl.colorMask(enable, enable, enable, enable);
  9746. this._colorWrite = enable;
  9747. };
  9748. Engine.prototype.getColorWrite = function () {
  9749. return this._colorWrite;
  9750. };
  9751. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9752. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9753. };
  9754. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9755. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9756. if (this._alphaMode === mode) {
  9757. return;
  9758. }
  9759. switch (mode) {
  9760. case Engine.ALPHA_DISABLE:
  9761. this._alphaState.alphaBlend = false;
  9762. break;
  9763. case Engine.ALPHA_PREMULTIPLIED:
  9764. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9765. this._alphaState.alphaBlend = true;
  9766. break;
  9767. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9768. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9769. this._alphaState.alphaBlend = true;
  9770. break;
  9771. case Engine.ALPHA_COMBINE:
  9772. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9773. this._alphaState.alphaBlend = true;
  9774. break;
  9775. case Engine.ALPHA_ONEONE:
  9776. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9777. this._alphaState.alphaBlend = true;
  9778. break;
  9779. case Engine.ALPHA_ADD:
  9780. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9781. this._alphaState.alphaBlend = true;
  9782. break;
  9783. case Engine.ALPHA_SUBTRACT:
  9784. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9785. this._alphaState.alphaBlend = true;
  9786. break;
  9787. case Engine.ALPHA_MULTIPLY:
  9788. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9789. this._alphaState.alphaBlend = true;
  9790. break;
  9791. case Engine.ALPHA_MAXIMIZED:
  9792. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9793. this._alphaState.alphaBlend = true;
  9794. break;
  9795. case Engine.ALPHA_INTERPOLATE:
  9796. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9797. this._alphaState.alphaBlend = true;
  9798. break;
  9799. case Engine.ALPHA_SCREENMODE:
  9800. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9801. this._alphaState.alphaBlend = true;
  9802. break;
  9803. }
  9804. if (!noDepthWriteChange) {
  9805. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9806. }
  9807. this._alphaMode = mode;
  9808. };
  9809. Engine.prototype.getAlphaMode = function () {
  9810. return this._alphaMode;
  9811. };
  9812. Engine.prototype.setAlphaTesting = function (enable) {
  9813. this._alphaTest = enable;
  9814. };
  9815. Engine.prototype.getAlphaTesting = function () {
  9816. return !!this._alphaTest;
  9817. };
  9818. // Textures
  9819. Engine.prototype.wipeCaches = function (bruteForce) {
  9820. if (this.preventCacheWipeBetweenFrames) {
  9821. return;
  9822. }
  9823. this.resetTextureCache();
  9824. this._currentEffect = null;
  9825. // 6/8/2017: deltakosh: Should not be required anymore.
  9826. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9827. if (bruteForce) {
  9828. this._currentProgram = null;
  9829. this._stencilState.reset();
  9830. this._depthCullingState.reset();
  9831. this.setDepthFunctionToLessOrEqual();
  9832. this._alphaState.reset();
  9833. }
  9834. this._cachedVertexBuffers = null;
  9835. this._cachedIndexBuffer = null;
  9836. this._cachedEffectForVertexBuffers = null;
  9837. this._unbindVertexArrayObject();
  9838. this.bindIndexBuffer(null);
  9839. this.bindArrayBuffer(null);
  9840. };
  9841. /**
  9842. * Set the compressed texture format to use, based on the formats you have, and the formats
  9843. * supported by the hardware / browser.
  9844. *
  9845. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9846. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9847. * to API arguments needed to compressed textures. This puts the burden on the container
  9848. * generator to house the arcane code for determining these for current & future formats.
  9849. *
  9850. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9851. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9852. *
  9853. * Note: The result of this call is not taken into account when a texture is base64.
  9854. *
  9855. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9856. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9857. *
  9858. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9859. * @returns The extension selected.
  9860. */
  9861. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9862. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9863. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9864. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9865. return this._textureFormatInUse = this._texturesSupported[i];
  9866. }
  9867. }
  9868. }
  9869. // actively set format to nothing, to allow this to be called more than once
  9870. // and possibly fail the 2nd time
  9871. return this._textureFormatInUse = null;
  9872. };
  9873. Engine.prototype._createTexture = function () {
  9874. return this._gl.createTexture();
  9875. };
  9876. /**
  9877. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9878. * @param {string} urlArg- This contains one of the following:
  9879. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9880. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9881. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9882. *
  9883. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9884. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9885. * @param {Scene} scene- Needed for loading to the correct scene.
  9886. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9887. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9888. * @param {callback} onError- Optional callback to be called upon failure.
  9889. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9890. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9891. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9892. *
  9893. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9894. */
  9895. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9896. var _this = this;
  9897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9898. if (onLoad === void 0) { onLoad = null; }
  9899. if (onError === void 0) { onError = null; }
  9900. if (buffer === void 0) { buffer = null; }
  9901. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9902. var fromData = url.substr(0, 5) === "data:";
  9903. var fromBlob = url.substr(0, 5) === "blob:";
  9904. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9905. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9906. // establish the file extension, if possible
  9907. var lastDot = url.lastIndexOf('.');
  9908. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9909. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9910. var isTGA = (extension === ".tga");
  9911. // determine if a ktx file should be substituted
  9912. var isKTX = false;
  9913. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9914. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9915. isKTX = true;
  9916. }
  9917. if (scene) {
  9918. scene._addPendingData(texture);
  9919. }
  9920. texture.url = url;
  9921. texture.generateMipMaps = !noMipmap;
  9922. texture.samplingMode = samplingMode;
  9923. texture.invertY = invertY;
  9924. if (!this._doNotHandleContextLost) {
  9925. // Keep a link to the buffer only if we plan to handle context lost
  9926. texture._buffer = buffer;
  9927. }
  9928. if (onLoad) {
  9929. texture.onLoadedObservable.add(onLoad);
  9930. }
  9931. if (!fallBack)
  9932. this._internalTexturesCache.push(texture);
  9933. var onerror = function () {
  9934. if (scene) {
  9935. scene._removePendingData(texture);
  9936. }
  9937. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9938. if (isKTX) {
  9939. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9940. }
  9941. else if (onError) {
  9942. onError();
  9943. }
  9944. };
  9945. var callback;
  9946. // processing for non-image formats
  9947. if (isKTX || isTGA || isDDS) {
  9948. if (isKTX) {
  9949. callback = function (data) {
  9950. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9951. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9952. ktx.uploadLevels(_this._gl, !noMipmap);
  9953. return false;
  9954. }, samplingMode);
  9955. };
  9956. }
  9957. else if (isTGA) {
  9958. callback = function (arrayBuffer) {
  9959. var data = new Uint8Array(arrayBuffer);
  9960. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9961. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9962. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9963. return false;
  9964. }, samplingMode);
  9965. };
  9966. }
  9967. else if (isDDS) {
  9968. callback = function (data) {
  9969. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9970. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9971. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9972. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9973. return false;
  9974. }, samplingMode);
  9975. };
  9976. }
  9977. if (!buffer) {
  9978. BABYLON.Tools.LoadFile(url, function (data) {
  9979. callback(data);
  9980. }, null, scene ? scene.database : null, true, onerror);
  9981. }
  9982. else {
  9983. callback(buffer);
  9984. }
  9985. // image format processing
  9986. }
  9987. else {
  9988. var onload = function (img) {
  9989. if (fromBlob && !_this._doNotHandleContextLost) {
  9990. // We need to store the image if we need to rebuild the texture
  9991. // in case of a webgl context lost
  9992. texture._buffer = img;
  9993. }
  9994. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9995. var gl = _this._gl;
  9996. var isPot = (img.width === potWidth && img.height === potHeight);
  9997. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9998. if (isPot) {
  9999. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10000. return false;
  10001. }
  10002. // Using shaders to rescale because canvas.drawImage is lossy
  10003. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10004. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10005. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10010. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10011. _this._releaseTexture(source);
  10012. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10013. continuationCallback();
  10014. });
  10015. return true;
  10016. }, samplingMode);
  10017. };
  10018. if (!fromData || isBase64)
  10019. if (buffer instanceof HTMLImageElement) {
  10020. onload(buffer);
  10021. }
  10022. else {
  10023. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10024. }
  10025. else if (buffer instanceof Array || typeof buffer === "string")
  10026. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10027. else
  10028. onload(buffer);
  10029. }
  10030. return texture;
  10031. };
  10032. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10033. var _this = this;
  10034. var rtt = this.createRenderTargetTexture({
  10035. width: destination.width,
  10036. height: destination.height,
  10037. }, {
  10038. generateMipMaps: false,
  10039. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10040. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10041. generateDepthBuffer: false,
  10042. generateStencilBuffer: false
  10043. });
  10044. if (!this._rescalePostProcess) {
  10045. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10046. }
  10047. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10048. _this._rescalePostProcess.onApply = function (effect) {
  10049. effect._bindTexture("textureSampler", source);
  10050. };
  10051. var hostingScene = scene;
  10052. if (!hostingScene) {
  10053. hostingScene = _this.scenes[_this.scenes.length - 1];
  10054. }
  10055. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10056. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10057. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10058. _this.unBindFramebuffer(rtt);
  10059. _this._releaseTexture(rtt);
  10060. if (onComplete) {
  10061. onComplete();
  10062. }
  10063. });
  10064. };
  10065. Engine.prototype._getInternalFormat = function (format) {
  10066. var internalFormat = this._gl.RGBA;
  10067. switch (format) {
  10068. case Engine.TEXTUREFORMAT_ALPHA:
  10069. internalFormat = this._gl.ALPHA;
  10070. break;
  10071. case Engine.TEXTUREFORMAT_LUMINANCE:
  10072. internalFormat = this._gl.LUMINANCE;
  10073. break;
  10074. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10075. internalFormat = this._gl.LUMINANCE_ALPHA;
  10076. break;
  10077. case Engine.TEXTUREFORMAT_RGB:
  10078. internalFormat = this._gl.RGB;
  10079. break;
  10080. case Engine.TEXTUREFORMAT_RGBA:
  10081. internalFormat = this._gl.RGBA;
  10082. break;
  10083. }
  10084. return internalFormat;
  10085. };
  10086. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10087. if (compression === void 0) { compression = null; }
  10088. var internalFormat = this._getInternalFormat(format);
  10089. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10090. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10091. if (!this._doNotHandleContextLost) {
  10092. texture._bufferView = data;
  10093. texture.format = format;
  10094. texture.invertY = invertY;
  10095. texture._compression = compression;
  10096. }
  10097. if (texture.width % 4 !== 0) {
  10098. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10099. }
  10100. if (compression) {
  10101. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10102. }
  10103. else {
  10104. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10105. }
  10106. if (texture.generateMipMaps) {
  10107. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10108. }
  10109. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10110. this.resetTextureCache();
  10111. texture.isReady = true;
  10112. };
  10113. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10114. if (compression === void 0) { compression = null; }
  10115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10116. texture.baseWidth = width;
  10117. texture.baseHeight = height;
  10118. texture.width = width;
  10119. texture.height = height;
  10120. texture.format = format;
  10121. texture.generateMipMaps = generateMipMaps;
  10122. texture.samplingMode = samplingMode;
  10123. texture.invertY = invertY;
  10124. texture._compression = compression;
  10125. if (!this._doNotHandleContextLost) {
  10126. texture._bufferView = data;
  10127. }
  10128. this.updateRawTexture(texture, data, format, invertY, compression);
  10129. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10130. // Filters
  10131. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10132. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10133. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10134. if (generateMipMaps) {
  10135. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10136. }
  10137. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10138. this._internalTexturesCache.push(texture);
  10139. return texture;
  10140. };
  10141. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10142. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10143. texture.baseWidth = width;
  10144. texture.baseHeight = height;
  10145. if (generateMipMaps) {
  10146. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10147. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10148. }
  10149. this.resetTextureCache();
  10150. texture.width = width;
  10151. texture.height = height;
  10152. texture.isReady = false;
  10153. texture.generateMipMaps = generateMipMaps;
  10154. texture.samplingMode = samplingMode;
  10155. this.updateTextureSamplingMode(samplingMode, texture);
  10156. this._internalTexturesCache.push(texture);
  10157. return texture;
  10158. };
  10159. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10160. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10161. if (texture.isCube) {
  10162. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10163. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10164. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10165. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10166. }
  10167. else {
  10168. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10169. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10170. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10171. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10172. }
  10173. texture.samplingMode = samplingMode;
  10174. };
  10175. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10176. if (premulAlpha === void 0) { premulAlpha = false; }
  10177. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10178. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10179. if (premulAlpha) {
  10180. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10181. }
  10182. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10183. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10184. if (texture.generateMipMaps) {
  10185. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10186. }
  10187. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10188. if (premulAlpha) {
  10189. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10190. }
  10191. this.resetTextureCache();
  10192. texture.isReady = true;
  10193. };
  10194. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10195. if (texture._isDisabled) {
  10196. return;
  10197. }
  10198. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10199. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10200. try {
  10201. // Testing video texture support
  10202. if (this._videoTextureSupported === undefined) {
  10203. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10204. if (this._gl.getError() !== 0) {
  10205. this._videoTextureSupported = false;
  10206. }
  10207. else {
  10208. this._videoTextureSupported = true;
  10209. }
  10210. }
  10211. // Copy video through the current working canvas if video texture is not supported
  10212. if (!this._videoTextureSupported) {
  10213. if (!texture._workingCanvas) {
  10214. texture._workingCanvas = document.createElement("canvas");
  10215. texture._workingContext = texture._workingCanvas.getContext("2d");
  10216. texture._workingCanvas.width = texture.width;
  10217. texture._workingCanvas.height = texture.height;
  10218. }
  10219. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10220. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10221. }
  10222. else {
  10223. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10224. }
  10225. if (texture.generateMipMaps) {
  10226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10227. }
  10228. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10229. this.resetTextureCache();
  10230. texture.isReady = true;
  10231. }
  10232. catch (ex) {
  10233. // Something unexpected
  10234. // Let's disable the texture
  10235. texture._isDisabled = true;
  10236. }
  10237. };
  10238. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10239. var fullOptions = new RenderTargetCreationOptions();
  10240. if (options !== undefined && typeof options === "object") {
  10241. fullOptions.generateMipMaps = options.generateMipMaps;
  10242. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10243. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10244. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10245. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10246. }
  10247. else {
  10248. fullOptions.generateMipMaps = options;
  10249. fullOptions.generateDepthBuffer = true;
  10250. fullOptions.generateStencilBuffer = false;
  10251. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10252. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10253. }
  10254. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10255. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10256. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10257. }
  10258. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10259. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10260. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10261. }
  10262. var gl = this._gl;
  10263. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10264. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10265. var width = size.width || size;
  10266. var height = size.height || size;
  10267. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10268. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10269. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10270. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10271. }
  10272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10276. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10277. // Create the framebuffer
  10278. var framebuffer = gl.createFramebuffer();
  10279. this.bindUnboundFramebuffer(framebuffer);
  10280. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10281. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10282. if (fullOptions.generateMipMaps) {
  10283. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10284. }
  10285. // Unbind
  10286. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10287. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10288. this.bindUnboundFramebuffer(null);
  10289. texture._framebuffer = framebuffer;
  10290. texture.baseWidth = width;
  10291. texture.baseHeight = height;
  10292. texture.width = width;
  10293. texture.height = height;
  10294. texture.isReady = true;
  10295. texture.samples = 1;
  10296. texture.generateMipMaps = fullOptions.generateMipMaps;
  10297. texture.samplingMode = fullOptions.samplingMode;
  10298. texture.type = fullOptions.type;
  10299. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10300. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10301. this.resetTextureCache();
  10302. this._internalTexturesCache.push(texture);
  10303. return texture;
  10304. };
  10305. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10306. var generateMipMaps = false;
  10307. var generateDepthBuffer = true;
  10308. var generateStencilBuffer = false;
  10309. var generateDepthTexture = false;
  10310. var textureCount = 1;
  10311. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10312. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10313. var types = [], samplingModes = [];
  10314. if (options !== undefined) {
  10315. generateMipMaps = options.generateMipMaps;
  10316. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10317. generateStencilBuffer = options.generateStencilBuffer;
  10318. generateDepthTexture = options.generateDepthTexture;
  10319. textureCount = options.textureCount || 1;
  10320. if (options.types) {
  10321. types = options.types;
  10322. }
  10323. if (options.samplingModes) {
  10324. samplingModes = options.samplingModes;
  10325. }
  10326. }
  10327. var gl = this._gl;
  10328. // Create the framebuffer
  10329. var framebuffer = gl.createFramebuffer();
  10330. this.bindUnboundFramebuffer(framebuffer);
  10331. var width = size.width || size;
  10332. var height = size.height || size;
  10333. var textures = [];
  10334. var attachments = [];
  10335. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10336. for (var i = 0; i < textureCount; i++) {
  10337. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10338. var type = types[i] || defaultType;
  10339. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10340. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10341. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10342. }
  10343. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10344. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10345. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10346. }
  10347. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10348. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10349. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10350. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10351. }
  10352. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10353. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10354. textures.push(texture);
  10355. attachments.push(attachment);
  10356. gl.activeTexture(gl["TEXTURE" + i]);
  10357. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10358. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10359. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10360. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10361. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10362. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10363. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10364. if (generateMipMaps) {
  10365. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10366. }
  10367. // Unbind
  10368. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10369. texture._framebuffer = framebuffer;
  10370. texture._depthStencilBuffer = depthStencilBuffer;
  10371. texture.baseWidth = width;
  10372. texture.baseHeight = height;
  10373. texture.width = width;
  10374. texture.height = height;
  10375. texture.isReady = true;
  10376. texture.samples = 1;
  10377. texture.generateMipMaps = generateMipMaps;
  10378. texture.samplingMode = samplingMode;
  10379. texture.type = type;
  10380. texture._generateDepthBuffer = generateDepthBuffer;
  10381. texture._generateStencilBuffer = generateStencilBuffer;
  10382. this._internalTexturesCache.push(texture);
  10383. }
  10384. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10385. // Depth texture
  10386. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10387. gl.activeTexture(gl.TEXTURE0);
  10388. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10393. 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);
  10394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10395. depthTexture._framebuffer = framebuffer;
  10396. depthTexture.baseWidth = width;
  10397. depthTexture.baseHeight = height;
  10398. depthTexture.width = width;
  10399. depthTexture.height = height;
  10400. depthTexture.isReady = true;
  10401. depthTexture.samples = 1;
  10402. depthTexture.generateMipMaps = generateMipMaps;
  10403. depthTexture.samplingMode = gl.NEAREST;
  10404. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10405. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10406. textures.push(depthTexture);
  10407. this._internalTexturesCache.push(depthTexture);
  10408. }
  10409. gl.drawBuffers(attachments);
  10410. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10411. this.bindUnboundFramebuffer(null);
  10412. this.resetTextureCache();
  10413. return textures;
  10414. };
  10415. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10416. if (samples === void 0) { samples = 1; }
  10417. var depthStencilBuffer = null;
  10418. var gl = this._gl;
  10419. // Create the depth/stencil buffer
  10420. if (generateStencilBuffer) {
  10421. depthStencilBuffer = gl.createRenderbuffer();
  10422. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10423. if (samples > 1) {
  10424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10425. }
  10426. else {
  10427. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10428. }
  10429. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10430. }
  10431. else if (generateDepthBuffer) {
  10432. depthStencilBuffer = gl.createRenderbuffer();
  10433. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10434. if (samples > 1) {
  10435. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10436. }
  10437. else {
  10438. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10439. }
  10440. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10441. }
  10442. return depthStencilBuffer;
  10443. };
  10444. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10445. if (this.webGLVersion < 2) {
  10446. return 1;
  10447. }
  10448. if (texture.samples === samples) {
  10449. return samples;
  10450. }
  10451. var gl = this._gl;
  10452. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10453. // Dispose previous render buffers
  10454. if (texture._depthStencilBuffer) {
  10455. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10456. }
  10457. if (texture._MSAAFramebuffer) {
  10458. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10459. }
  10460. if (texture._MSAARenderBuffer) {
  10461. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10462. }
  10463. if (samples > 1) {
  10464. texture._MSAAFramebuffer = gl.createFramebuffer();
  10465. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10466. var colorRenderbuffer = gl.createRenderbuffer();
  10467. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10468. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10469. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10470. texture._MSAARenderBuffer = colorRenderbuffer;
  10471. }
  10472. else {
  10473. this.bindUnboundFramebuffer(texture._framebuffer);
  10474. }
  10475. texture.samples = samples;
  10476. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10477. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10478. this.bindUnboundFramebuffer(null);
  10479. return samples;
  10480. };
  10481. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10482. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10483. };
  10484. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10485. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10486. };
  10487. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10488. var gl = this._gl;
  10489. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10490. var generateMipMaps = true;
  10491. var generateDepthBuffer = true;
  10492. var generateStencilBuffer = false;
  10493. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10494. if (options !== undefined) {
  10495. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10496. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10497. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10498. if (options.samplingMode !== undefined) {
  10499. samplingMode = options.samplingMode;
  10500. }
  10501. }
  10502. texture.isCube = true;
  10503. texture.generateMipMaps = generateMipMaps;
  10504. texture.samples = 1;
  10505. texture.samplingMode = samplingMode;
  10506. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10507. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10508. for (var face = 0; face < 6; face++) {
  10509. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10510. }
  10511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10515. // Create the framebuffer
  10516. var framebuffer = gl.createFramebuffer();
  10517. this.bindUnboundFramebuffer(framebuffer);
  10518. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10519. // Mipmaps
  10520. if (texture.generateMipMaps) {
  10521. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10522. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10523. }
  10524. // Unbind
  10525. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10526. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10527. this.bindUnboundFramebuffer(null);
  10528. texture._framebuffer = framebuffer;
  10529. texture.width = size;
  10530. texture.height = size;
  10531. texture.isReady = true;
  10532. this.resetTextureCache();
  10533. this._internalTexturesCache.push(texture);
  10534. return texture;
  10535. };
  10536. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10537. var _this = this;
  10538. if (onError === void 0) { onError = null; }
  10539. if (forcedExtension === void 0) { forcedExtension = null; }
  10540. var callback = function (loadData) {
  10541. if (!loadData) {
  10542. if (onLoad) {
  10543. onLoad(null);
  10544. }
  10545. return;
  10546. }
  10547. var texture = loadData.texture;
  10548. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10549. texture._lodGenerationScale = scale;
  10550. texture._lodGenerationOffset = offset;
  10551. if (_this._caps.textureLOD) {
  10552. // Do not add extra process if texture lod is supported.
  10553. if (onLoad) {
  10554. onLoad(texture);
  10555. }
  10556. return;
  10557. }
  10558. var mipSlices = 3;
  10559. var gl = _this._gl;
  10560. var width = loadData.width;
  10561. if (!width) {
  10562. return;
  10563. }
  10564. var textures = [];
  10565. for (var i = 0; i < mipSlices; i++) {
  10566. //compute LOD from even spacing in smoothness (matching shader calculation)
  10567. var smoothness = i / (mipSlices - 1);
  10568. var roughness = 1 - smoothness;
  10569. var minLODIndex = offset; // roughness = 0
  10570. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10571. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10572. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10573. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10574. glTextureFromLod.isCube = true;
  10575. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10578. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10579. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10580. if (loadData.isDDS) {
  10581. var info = loadData.info;
  10582. var data = loadData.data;
  10583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10584. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10585. }
  10586. else {
  10587. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10588. }
  10589. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10590. // Wrap in a base texture for easy binding.
  10591. var lodTexture = new BABYLON.BaseTexture(scene);
  10592. lodTexture.isCube = true;
  10593. lodTexture._texture = glTextureFromLod;
  10594. glTextureFromLod.isReady = true;
  10595. textures.push(lodTexture);
  10596. }
  10597. texture._lodTextureHigh = textures[2];
  10598. texture._lodTextureMid = textures[1];
  10599. texture._lodTextureLow = textures[0];
  10600. if (onLoad) {
  10601. onLoad(texture);
  10602. }
  10603. };
  10604. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10605. };
  10606. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10607. var _this = this;
  10608. if (onLoad === void 0) { onLoad = null; }
  10609. if (onError === void 0) { onError = null; }
  10610. if (forcedExtension === void 0) { forcedExtension = null; }
  10611. var gl = this._gl;
  10612. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10613. texture.isCube = true;
  10614. texture.url = rootUrl;
  10615. texture.generateMipMaps = !noMipmap;
  10616. if (!this._doNotHandleContextLost) {
  10617. texture._extension = forcedExtension;
  10618. texture._files = files;
  10619. }
  10620. var isKTX = false;
  10621. var isDDS = false;
  10622. var lastDot = rootUrl.lastIndexOf('.');
  10623. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10624. if (this._textureFormatInUse) {
  10625. extension = this._textureFormatInUse;
  10626. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10627. isKTX = true;
  10628. }
  10629. else {
  10630. isDDS = (extension === ".dds");
  10631. }
  10632. var onerror = function (request, exception) {
  10633. if (onError) {
  10634. onError(request.status + " " + request.statusText, exception);
  10635. }
  10636. };
  10637. if (isKTX) {
  10638. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10639. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10640. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10642. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10643. ktx.uploadLevels(_this._gl, !noMipmap);
  10644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10648. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10649. _this.resetTextureCache();
  10650. texture.width = ktx.pixelWidth;
  10651. texture.height = ktx.pixelHeight;
  10652. texture.isReady = true;
  10653. }, null, null, true, onerror);
  10654. }
  10655. else if (isDDS) {
  10656. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10657. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10658. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10659. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10660. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10661. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10662. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10663. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10664. }
  10665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10669. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10670. _this.resetTextureCache();
  10671. texture.width = info.width;
  10672. texture.height = info.height;
  10673. texture.isReady = true;
  10674. texture.type = info.textureType;
  10675. if (onLoad) {
  10676. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10677. }
  10678. }, null, null, true, onerror);
  10679. }
  10680. else {
  10681. cascadeLoad(rootUrl, scene, function (imgs) {
  10682. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10683. var height = width;
  10684. _this._prepareWorkingCanvas();
  10685. _this._workingCanvas.width = width;
  10686. _this._workingCanvas.height = height;
  10687. var faces = [
  10688. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10689. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10690. ];
  10691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10693. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10694. for (var index = 0; index < faces.length; index++) {
  10695. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10696. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10697. }
  10698. if (!noMipmap) {
  10699. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10700. }
  10701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10706. _this.resetTextureCache();
  10707. texture.width = width;
  10708. texture.height = height;
  10709. texture.isReady = true;
  10710. texture.format = format;
  10711. texture.onLoadedObservable.notifyObservers(texture);
  10712. texture.onLoadedObservable.clear();
  10713. if (onLoad) {
  10714. onLoad();
  10715. }
  10716. }, files, onError);
  10717. }
  10718. this._internalTexturesCache.push(texture);
  10719. return texture;
  10720. };
  10721. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10722. if (compression === void 0) { compression = null; }
  10723. if (level === void 0) { level = 0; }
  10724. texture._bufferViewArray = data;
  10725. texture.format = format;
  10726. texture.type = type;
  10727. texture.invertY = invertY;
  10728. texture._compression = compression;
  10729. var gl = this._gl;
  10730. var textureType = this._getWebGLTextureType(type);
  10731. var internalFormat = this._getInternalFormat(format);
  10732. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10733. var needConversion = false;
  10734. if (internalFormat === gl.RGB) {
  10735. internalFormat = gl.RGBA;
  10736. needConversion = true;
  10737. }
  10738. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10740. if (texture.width % 4 !== 0) {
  10741. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10742. }
  10743. // Data are known to be in +X +Y +Z -X -Y -Z
  10744. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10745. var faceData = data[faceIndex];
  10746. if (compression) {
  10747. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  10748. }
  10749. else {
  10750. if (needConversion) {
  10751. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10752. }
  10753. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10754. }
  10755. }
  10756. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10757. if (isPot && texture.generateMipMaps && level === 0) {
  10758. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10759. }
  10760. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10761. this.resetTextureCache();
  10762. texture.isReady = true;
  10763. };
  10764. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10765. if (compression === void 0) { compression = null; }
  10766. var gl = this._gl;
  10767. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10768. texture.isCube = true;
  10769. texture.generateMipMaps = generateMipMaps;
  10770. texture.format = format;
  10771. texture.type = type;
  10772. if (!this._doNotHandleContextLost) {
  10773. texture._bufferViewArray = data;
  10774. }
  10775. var textureType = this._getWebGLTextureType(type);
  10776. var internalFormat = this._getInternalFormat(format);
  10777. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10778. var needConversion = false;
  10779. if (internalFormat === gl.RGB) {
  10780. internalFormat = gl.RGBA;
  10781. needConversion = true;
  10782. }
  10783. var width = size;
  10784. var height = width;
  10785. texture.width = width;
  10786. texture.height = height;
  10787. // Double check on POT to generate Mips.
  10788. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10789. if (!isPot) {
  10790. generateMipMaps = false;
  10791. }
  10792. // Upload data if needed. The texture won't be ready until then.
  10793. if (data) {
  10794. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10795. }
  10796. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10797. // Filters
  10798. if (data && generateMipMaps) {
  10799. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10800. }
  10801. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10804. }
  10805. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10808. }
  10809. else {
  10810. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10811. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10812. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10813. }
  10814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10816. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10817. return texture;
  10818. };
  10819. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10820. var _this = this;
  10821. if (onLoad === void 0) { onLoad = null; }
  10822. if (onError === void 0) { onError = null; }
  10823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10824. if (invertY === void 0) { invertY = false; }
  10825. var gl = this._gl;
  10826. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10827. scene._addPendingData(texture);
  10828. texture.url = url;
  10829. this._internalTexturesCache.push(texture);
  10830. var onerror = function (request, exception) {
  10831. scene._removePendingData(texture);
  10832. if (onError) {
  10833. onError(request.status + " " + request.statusText, exception);
  10834. }
  10835. };
  10836. var internalCallback = function (data) {
  10837. var width = texture.width;
  10838. var height = texture.height;
  10839. var faceDataArrays = callback(data);
  10840. if (mipmmapGenerator) {
  10841. var textureType = _this._getWebGLTextureType(type);
  10842. var internalFormat = _this._getInternalFormat(format);
  10843. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10844. var needConversion = false;
  10845. if (internalFormat === gl.RGB) {
  10846. internalFormat = gl.RGBA;
  10847. needConversion = true;
  10848. }
  10849. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10850. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10851. var mipData = mipmmapGenerator(faceDataArrays);
  10852. for (var level = 0; level < mipData.length; level++) {
  10853. var mipSize = width >> level;
  10854. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10855. var mipFaceData = mipData[level][faceIndex];
  10856. if (needConversion) {
  10857. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10858. }
  10859. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10860. }
  10861. }
  10862. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10863. }
  10864. else {
  10865. texture.generateMipMaps = !noMipmap;
  10866. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10867. }
  10868. texture.isReady = true;
  10869. _this.resetTextureCache();
  10870. scene._removePendingData(texture);
  10871. if (onLoad) {
  10872. onLoad();
  10873. }
  10874. };
  10875. BABYLON.Tools.LoadFile(url, function (data) {
  10876. internalCallback(data);
  10877. }, undefined, scene.database, true, onerror);
  10878. return texture;
  10879. };
  10880. ;
  10881. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10882. var gl = this._gl;
  10883. if (!gl) {
  10884. return;
  10885. }
  10886. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10889. if (!noMipmap && !isCompressed) {
  10890. gl.generateMipmap(gl.TEXTURE_2D);
  10891. }
  10892. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10893. this.resetTextureCache();
  10894. if (scene) {
  10895. scene._removePendingData(texture);
  10896. }
  10897. texture.onLoadedObservable.notifyObservers(texture);
  10898. texture.onLoadedObservable.clear();
  10899. };
  10900. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10901. var _this = this;
  10902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10903. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10904. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10905. var gl = this._gl;
  10906. if (!gl) {
  10907. return;
  10908. }
  10909. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10910. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10911. texture.baseWidth = width;
  10912. texture.baseHeight = height;
  10913. texture.width = potWidth;
  10914. texture.height = potHeight;
  10915. texture.isReady = true;
  10916. if (processFunction(potWidth, potHeight, function () {
  10917. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10918. })) {
  10919. // Returning as texture needs extra async steps
  10920. return;
  10921. }
  10922. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10923. };
  10924. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10925. // Create new RGBA data container.
  10926. var rgbaData;
  10927. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10928. rgbaData = new Float32Array(width * height * 4);
  10929. }
  10930. else {
  10931. rgbaData = new Uint32Array(width * height * 4);
  10932. }
  10933. // Convert each pixel.
  10934. for (var x = 0; x < width; x++) {
  10935. for (var y = 0; y < height; y++) {
  10936. var index = (y * width + x) * 3;
  10937. var newIndex = (y * width + x) * 4;
  10938. // Map Old Value to new value.
  10939. rgbaData[newIndex + 0] = rgbData[index + 0];
  10940. rgbaData[newIndex + 1] = rgbData[index + 1];
  10941. rgbaData[newIndex + 2] = rgbData[index + 2];
  10942. // Add fully opaque alpha channel.
  10943. rgbaData[newIndex + 3] = 1;
  10944. }
  10945. }
  10946. return rgbaData;
  10947. };
  10948. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10949. var gl = this._gl;
  10950. if (texture._framebuffer) {
  10951. gl.deleteFramebuffer(texture._framebuffer);
  10952. texture._framebuffer = null;
  10953. }
  10954. if (texture._depthStencilBuffer) {
  10955. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10956. texture._depthStencilBuffer = null;
  10957. }
  10958. if (texture._MSAAFramebuffer) {
  10959. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10960. texture._MSAAFramebuffer = null;
  10961. }
  10962. if (texture._MSAARenderBuffer) {
  10963. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10964. texture._MSAARenderBuffer = null;
  10965. }
  10966. };
  10967. Engine.prototype._releaseTexture = function (texture) {
  10968. var gl = this._gl;
  10969. this._releaseFramebufferObjects(texture);
  10970. gl.deleteTexture(texture._webGLTexture);
  10971. // Unbind channels
  10972. this.unbindAllTextures();
  10973. var index = this._internalTexturesCache.indexOf(texture);
  10974. if (index !== -1) {
  10975. this._internalTexturesCache.splice(index, 1);
  10976. }
  10977. // Integrated fixed lod samplers.
  10978. if (texture._lodTextureHigh) {
  10979. texture._lodTextureHigh.dispose();
  10980. }
  10981. if (texture._lodTextureMid) {
  10982. texture._lodTextureMid.dispose();
  10983. }
  10984. if (texture._lodTextureLow) {
  10985. texture._lodTextureLow.dispose();
  10986. }
  10987. };
  10988. Engine.prototype.setProgram = function (program) {
  10989. if (this._currentProgram !== program) {
  10990. this._gl.useProgram(program);
  10991. this._currentProgram = program;
  10992. }
  10993. };
  10994. Engine.prototype.bindSamplers = function (effect) {
  10995. this.setProgram(effect.getProgram());
  10996. var samplers = effect.getSamplers();
  10997. for (var index = 0; index < samplers.length; index++) {
  10998. var uniform = effect.getUniform(samplers[index]);
  10999. this._gl.uniform1i(uniform, index);
  11000. }
  11001. this._currentEffect = null;
  11002. };
  11003. Engine.prototype.activateTexture = function (texture) {
  11004. if (this._activeTexture !== texture) {
  11005. this._gl.activeTexture(texture);
  11006. this._activeTexture = texture;
  11007. }
  11008. };
  11009. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11010. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  11011. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11012. this._activeTexturesCache[this._activeTexture] = texture;
  11013. }
  11014. };
  11015. Engine.prototype._bindTexture = function (channel, texture) {
  11016. if (channel < 0) {
  11017. return;
  11018. }
  11019. this.activateTexture(this._gl.TEXTURE0 + channel);
  11020. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11021. };
  11022. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11023. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  11024. };
  11025. Engine.prototype.unbindAllTextures = function () {
  11026. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11027. this.activateTexture(this._gl["TEXTURE" + channel]);
  11028. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11029. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11030. }
  11031. };
  11032. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11033. if (channel < 0) {
  11034. return;
  11035. }
  11036. this._gl.uniform1i(uniform, channel);
  11037. this._setTexture(channel, texture);
  11038. };
  11039. Engine.prototype._setTexture = function (channel, texture) {
  11040. // Not ready?
  11041. if (!texture) {
  11042. if (this._activeTexturesCache[channel] != null) {
  11043. this.activateTexture(this._gl["TEXTURE" + channel]);
  11044. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11045. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11046. }
  11047. return;
  11048. }
  11049. // Video
  11050. var alreadyActivated = false;
  11051. if (texture.video) {
  11052. this.activateTexture(this._gl["TEXTURE" + channel]);
  11053. alreadyActivated = true;
  11054. texture.update();
  11055. }
  11056. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11057. texture.delayLoad();
  11058. return;
  11059. }
  11060. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  11061. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  11062. if (this._activeTexturesCache[channel] === internalTexture) {
  11063. return;
  11064. }
  11065. if (!alreadyActivated) {
  11066. this.activateTexture(this._gl["TEXTURE" + channel]);
  11067. }
  11068. if (internalTexture.isCube) {
  11069. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11070. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11071. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11072. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11073. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11074. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11075. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11076. }
  11077. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11078. }
  11079. else {
  11080. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11081. if (internalTexture._cachedWrapU !== texture.wrapU) {
  11082. internalTexture._cachedWrapU = texture.wrapU;
  11083. switch (texture.wrapU) {
  11084. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11085. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11086. break;
  11087. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11088. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11089. break;
  11090. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11091. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11092. break;
  11093. }
  11094. }
  11095. if (internalTexture._cachedWrapV !== texture.wrapV) {
  11096. internalTexture._cachedWrapV = texture.wrapV;
  11097. switch (texture.wrapV) {
  11098. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11099. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11100. break;
  11101. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11102. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11103. break;
  11104. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11105. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11106. break;
  11107. }
  11108. }
  11109. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11110. }
  11111. };
  11112. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11113. if (channel < 0) {
  11114. return;
  11115. }
  11116. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11117. this._textureUnits = new Int32Array(textures.length);
  11118. }
  11119. for (var i = 0; i < textures.length; i++) {
  11120. this._textureUnits[i] = channel + i;
  11121. }
  11122. this._gl.uniform1iv(uniform, this._textureUnits);
  11123. for (var index = 0; index < textures.length; index++) {
  11124. this._setTexture(channel + index, textures[index]);
  11125. }
  11126. };
  11127. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11128. var internalTexture = texture.getInternalTexture();
  11129. if (!internalTexture) {
  11130. return;
  11131. }
  11132. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11133. var value = texture.anisotropicFilteringLevel;
  11134. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11135. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11136. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11137. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11138. }
  11139. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11140. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11141. internalTexture._cachedAnisotropicFilteringLevel = value;
  11142. }
  11143. };
  11144. Engine.prototype.readPixels = function (x, y, width, height) {
  11145. var data = new Uint8Array(height * width * 4);
  11146. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11147. return data;
  11148. };
  11149. /**
  11150. * Add an externaly attached data from its key.
  11151. * This method call will fail and return false, if such key already exists.
  11152. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11153. * @param key the unique key that identifies the data
  11154. * @param data the data object to associate to the key for this Engine instance
  11155. * @return true if no such key were already present and the data was added successfully, false otherwise
  11156. */
  11157. Engine.prototype.addExternalData = function (key, data) {
  11158. if (!this._externalData) {
  11159. this._externalData = new BABYLON.StringDictionary();
  11160. }
  11161. return this._externalData.add(key, data);
  11162. };
  11163. /**
  11164. * Get an externaly attached data from its key
  11165. * @param key the unique key that identifies the data
  11166. * @return the associated data, if present (can be null), or undefined if not present
  11167. */
  11168. Engine.prototype.getExternalData = function (key) {
  11169. if (!this._externalData) {
  11170. this._externalData = new BABYLON.StringDictionary();
  11171. }
  11172. return this._externalData.get(key);
  11173. };
  11174. /**
  11175. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11176. * @param key the unique key that identifies the data
  11177. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11178. * @return the associated data, can be null if the factory returned null.
  11179. */
  11180. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11181. if (!this._externalData) {
  11182. this._externalData = new BABYLON.StringDictionary();
  11183. }
  11184. return this._externalData.getOrAddWithFactory(key, factory);
  11185. };
  11186. /**
  11187. * Remove an externaly attached data from the Engine instance
  11188. * @param key the unique key that identifies the data
  11189. * @return true if the data was successfully removed, false if it doesn't exist
  11190. */
  11191. Engine.prototype.removeExternalData = function (key) {
  11192. if (!this._externalData) {
  11193. this._externalData = new BABYLON.StringDictionary();
  11194. }
  11195. return this._externalData.remove(key);
  11196. };
  11197. Engine.prototype.unbindAllAttributes = function () {
  11198. if (this._mustWipeVertexAttributes) {
  11199. this._mustWipeVertexAttributes = false;
  11200. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11201. this._gl.disableVertexAttribArray(i);
  11202. this._vertexAttribArraysEnabled[i] = false;
  11203. this._currentBufferPointers[i].active = false;
  11204. }
  11205. return;
  11206. }
  11207. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11208. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11209. continue;
  11210. }
  11211. this._gl.disableVertexAttribArray(i);
  11212. this._vertexAttribArraysEnabled[i] = false;
  11213. this._currentBufferPointers[i].active = false;
  11214. }
  11215. };
  11216. Engine.prototype.releaseEffects = function () {
  11217. for (var name in this._compiledEffects) {
  11218. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11219. }
  11220. this._compiledEffects = {};
  11221. };
  11222. // Dispose
  11223. Engine.prototype.dispose = function () {
  11224. this.hideLoadingUI();
  11225. this.stopRenderLoop();
  11226. // Release postProcesses
  11227. while (this.postProcesses.length) {
  11228. this.postProcesses[0].dispose();
  11229. }
  11230. // Empty texture
  11231. if (this._emptyTexture) {
  11232. this._releaseTexture(this._emptyTexture);
  11233. this._emptyTexture = null;
  11234. }
  11235. if (this._emptyCubeTexture) {
  11236. this._releaseTexture(this._emptyCubeTexture);
  11237. this._emptyCubeTexture = null;
  11238. }
  11239. // Rescale PP
  11240. if (this._rescalePostProcess) {
  11241. this._rescalePostProcess.dispose();
  11242. }
  11243. // Release scenes
  11244. while (this.scenes.length) {
  11245. this.scenes[0].dispose();
  11246. }
  11247. // Release audio engine
  11248. if (Engine.audioEngine) {
  11249. Engine.audioEngine.dispose();
  11250. }
  11251. // Release effects
  11252. this.releaseEffects();
  11253. // Unbind
  11254. this.unbindAllAttributes();
  11255. if (this._dummyFramebuffer) {
  11256. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11257. }
  11258. this._gl = null;
  11259. //WebVR
  11260. this.disableVR();
  11261. // Events
  11262. window.removeEventListener("blur", this._onBlur);
  11263. window.removeEventListener("focus", this._onFocus);
  11264. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11265. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11266. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11267. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11268. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11269. if (!this._doNotHandleContextLost) {
  11270. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11271. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11272. }
  11273. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11274. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11275. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11276. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11277. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11278. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11279. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11280. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11281. if (this._onVrDisplayConnect) {
  11282. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11283. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11284. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11285. this._onVrDisplayConnect = undefined;
  11286. this._onVrDisplayDisconnect = undefined;
  11287. }
  11288. // Remove from Instances
  11289. var index = Engine.Instances.indexOf(this);
  11290. if (index >= 0) {
  11291. Engine.Instances.splice(index, 1);
  11292. }
  11293. this._workingCanvas = null;
  11294. this._workingContext = null;
  11295. this._currentBufferPointers = null;
  11296. this._renderingCanvas = null;
  11297. this._currentProgram = null;
  11298. this.onResizeObservable.clear();
  11299. this.onCanvasBlurObservable.clear();
  11300. this.onCanvasFocusObservable.clear();
  11301. this.onCanvasPointerOutObservable.clear();
  11302. BABYLON.Effect.ResetCache();
  11303. };
  11304. // Loading screen
  11305. Engine.prototype.displayLoadingUI = function () {
  11306. var loadingScreen = this.loadingScreen;
  11307. if (loadingScreen) {
  11308. loadingScreen.displayLoadingUI();
  11309. }
  11310. };
  11311. Engine.prototype.hideLoadingUI = function () {
  11312. var loadingScreen = this.loadingScreen;
  11313. if (loadingScreen) {
  11314. loadingScreen.hideLoadingUI();
  11315. }
  11316. };
  11317. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11318. get: function () {
  11319. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11320. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11321. return this._loadingScreen;
  11322. },
  11323. set: function (loadingScreen) {
  11324. this._loadingScreen = loadingScreen;
  11325. },
  11326. enumerable: true,
  11327. configurable: true
  11328. });
  11329. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11330. set: function (text) {
  11331. this.loadingScreen.loadingUIText = text;
  11332. },
  11333. enumerable: true,
  11334. configurable: true
  11335. });
  11336. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11337. set: function (color) {
  11338. this.loadingScreen.loadingUIBackgroundColor = color;
  11339. },
  11340. enumerable: true,
  11341. configurable: true
  11342. });
  11343. Engine.prototype.attachContextLostEvent = function (callback) {
  11344. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11345. };
  11346. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11347. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11348. };
  11349. Engine.prototype.getVertexShaderSource = function (program) {
  11350. var shaders = this._gl.getAttachedShaders(program);
  11351. return this._gl.getShaderSource(shaders[0]);
  11352. };
  11353. Engine.prototype.getFragmentShaderSource = function (program) {
  11354. var shaders = this._gl.getAttachedShaders(program);
  11355. return this._gl.getShaderSource(shaders[1]);
  11356. };
  11357. Engine.prototype.getError = function () {
  11358. return this._gl.getError();
  11359. };
  11360. // FPS
  11361. Engine.prototype.getFps = function () {
  11362. return this._fps;
  11363. };
  11364. Engine.prototype.getDeltaTime = function () {
  11365. return this._deltaTime;
  11366. };
  11367. Engine.prototype._measureFps = function () {
  11368. this._performanceMonitor.sampleFrame();
  11369. this._fps = this._performanceMonitor.averageFPS;
  11370. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11371. };
  11372. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11373. if (faceIndex === void 0) { faceIndex = -1; }
  11374. var gl = this._gl;
  11375. if (!this._dummyFramebuffer) {
  11376. this._dummyFramebuffer = gl.createFramebuffer();
  11377. }
  11378. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11379. if (faceIndex > -1) {
  11380. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11381. }
  11382. else {
  11383. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11384. }
  11385. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11386. var buffer;
  11387. switch (readType) {
  11388. case gl.UNSIGNED_BYTE:
  11389. buffer = new Uint8Array(4 * width * height);
  11390. readType = gl.UNSIGNED_BYTE;
  11391. break;
  11392. default:
  11393. buffer = new Float32Array(4 * width * height);
  11394. readType = gl.FLOAT;
  11395. break;
  11396. }
  11397. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11398. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11399. return buffer;
  11400. };
  11401. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11402. if (this._webGLVersion > 1) {
  11403. return this._caps.colorBufferFloat;
  11404. }
  11405. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11406. };
  11407. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11408. if (this._webGLVersion > 1) {
  11409. return this._caps.colorBufferFloat;
  11410. }
  11411. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11412. };
  11413. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11414. Engine.prototype._canRenderToFramebuffer = function (type) {
  11415. var gl = this._gl;
  11416. //clear existing errors
  11417. while (gl.getError() !== gl.NO_ERROR) { }
  11418. var successful = true;
  11419. var texture = gl.createTexture();
  11420. gl.bindTexture(gl.TEXTURE_2D, texture);
  11421. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11424. var fb = gl.createFramebuffer();
  11425. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11426. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11427. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11428. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11429. successful = successful && (gl.getError() === gl.NO_ERROR);
  11430. //try render by clearing frame buffer's color buffer
  11431. if (successful) {
  11432. gl.clear(gl.COLOR_BUFFER_BIT);
  11433. successful = successful && (gl.getError() === gl.NO_ERROR);
  11434. }
  11435. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11436. if (successful) {
  11437. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11438. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11439. var readFormat = gl.RGBA;
  11440. var readType = gl.UNSIGNED_BYTE;
  11441. var buffer = new Uint8Array(4);
  11442. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11443. successful = successful && (gl.getError() === gl.NO_ERROR);
  11444. }
  11445. //clean up
  11446. gl.deleteTexture(texture);
  11447. gl.deleteFramebuffer(fb);
  11448. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11449. //clear accumulated errors
  11450. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11451. return successful;
  11452. };
  11453. Engine.prototype._getWebGLTextureType = function (type) {
  11454. if (type === Engine.TEXTURETYPE_FLOAT) {
  11455. return this._gl.FLOAT;
  11456. }
  11457. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11458. // Add Half Float Constant.
  11459. return this._gl.HALF_FLOAT_OES;
  11460. }
  11461. return this._gl.UNSIGNED_BYTE;
  11462. };
  11463. ;
  11464. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11465. if (this._webGLVersion === 1) {
  11466. return this._gl.RGBA;
  11467. }
  11468. if (type === Engine.TEXTURETYPE_FLOAT) {
  11469. return this._gl.RGBA32F;
  11470. }
  11471. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11472. return this._gl.RGBA16F;
  11473. }
  11474. return this._gl.RGBA;
  11475. };
  11476. ;
  11477. Engine.prototype.createQuery = function () {
  11478. return this._gl.createQuery();
  11479. };
  11480. Engine.prototype.deleteQuery = function (query) {
  11481. this._gl.deleteQuery(query);
  11482. return this;
  11483. };
  11484. Engine.prototype.isQueryResultAvailable = function (query) {
  11485. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11486. };
  11487. Engine.prototype.getQueryResult = function (query) {
  11488. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11489. };
  11490. Engine.prototype.beginQuery = function (algorithmType, query) {
  11491. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11492. this._gl.beginQuery(glAlgorithm, query);
  11493. };
  11494. Engine.prototype.endQuery = function (algorithmType) {
  11495. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11496. this._gl.endQuery(glAlgorithm);
  11497. return this;
  11498. };
  11499. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11500. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11501. };
  11502. // Statics
  11503. Engine.isSupported = function () {
  11504. try {
  11505. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11506. if (navigator.isCocoonJS) {
  11507. return true;
  11508. }
  11509. var tempcanvas = document.createElement("canvas");
  11510. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11511. return gl != null && !!window.WebGLRenderingContext;
  11512. }
  11513. catch (e) {
  11514. return false;
  11515. }
  11516. };
  11517. Engine.Instances = new Array();
  11518. // Const statics
  11519. Engine._ALPHA_DISABLE = 0;
  11520. Engine._ALPHA_ADD = 1;
  11521. Engine._ALPHA_COMBINE = 2;
  11522. Engine._ALPHA_SUBTRACT = 3;
  11523. Engine._ALPHA_MULTIPLY = 4;
  11524. Engine._ALPHA_MAXIMIZED = 5;
  11525. Engine._ALPHA_ONEONE = 6;
  11526. Engine._ALPHA_PREMULTIPLIED = 7;
  11527. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11528. Engine._ALPHA_INTERPOLATE = 9;
  11529. Engine._ALPHA_SCREENMODE = 10;
  11530. Engine._DELAYLOADSTATE_NONE = 0;
  11531. Engine._DELAYLOADSTATE_LOADED = 1;
  11532. Engine._DELAYLOADSTATE_LOADING = 2;
  11533. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11534. Engine._TEXTUREFORMAT_ALPHA = 0;
  11535. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11536. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11537. Engine._TEXTUREFORMAT_RGB = 4;
  11538. Engine._TEXTUREFORMAT_RGBA = 5;
  11539. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11540. Engine._TEXTURETYPE_FLOAT = 1;
  11541. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11542. // Depht or Stencil test Constants.
  11543. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11544. 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.
  11545. 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.
  11546. 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.
  11547. 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.
  11548. 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.
  11549. 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.
  11550. 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.
  11551. // Stencil Actions Constants.
  11552. Engine._KEEP = 0x1E00;
  11553. Engine._REPLACE = 0x1E01;
  11554. Engine._INCR = 0x1E02;
  11555. Engine._DECR = 0x1E03;
  11556. Engine._INVERT = 0x150A;
  11557. Engine._INCR_WRAP = 0x8507;
  11558. Engine._DECR_WRAP = 0x8508;
  11559. // Texture rescaling mode
  11560. Engine._SCALEMODE_FLOOR = 1;
  11561. Engine._SCALEMODE_NEAREST = 2;
  11562. Engine._SCALEMODE_CEILING = 3;
  11563. // Updatable statics so stick with vars here
  11564. Engine.CollisionsEpsilon = 0.001;
  11565. Engine.CodeRepository = "src/";
  11566. Engine.ShadersRepository = "src/Shaders/";
  11567. return Engine;
  11568. }());
  11569. BABYLON.Engine = Engine;
  11570. })(BABYLON || (BABYLON = {}));
  11571. //# sourceMappingURL=babylon.engine.js.map
  11572. /// <reference path="Tools\babylon.decorators.ts" />
  11573. var BABYLON;
  11574. (function (BABYLON) {
  11575. /**
  11576. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11577. */
  11578. var Node = (function () {
  11579. /**
  11580. * @constructor
  11581. * @param {string} name - the name and id to be given to this node
  11582. * @param {BABYLON.Scene} the scene this node will be added to
  11583. */
  11584. function Node(name, scene) {
  11585. this.state = "";
  11586. this.metadata = null;
  11587. this.doNotSerialize = false;
  11588. this.animations = new Array();
  11589. this._ranges = {};
  11590. this._childrenFlag = -1;
  11591. this._isEnabled = true;
  11592. this._isReady = true;
  11593. this._currentRenderId = -1;
  11594. this._parentRenderId = -1;
  11595. /**
  11596. * An event triggered when the mesh is disposed.
  11597. * @type {BABYLON.Observable}
  11598. */
  11599. this.onDisposeObservable = new BABYLON.Observable();
  11600. // Behaviors
  11601. this._behaviors = new Array();
  11602. this.name = name;
  11603. this.id = name;
  11604. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11605. this.uniqueId = this._scene.getUniqueId();
  11606. this._initCache();
  11607. }
  11608. Object.defineProperty(Node.prototype, "parent", {
  11609. get: function () {
  11610. return this._parentNode;
  11611. },
  11612. set: function (parent) {
  11613. if (this._parentNode === parent) {
  11614. return;
  11615. }
  11616. if (this._parentNode) {
  11617. var index = this._parentNode._children.indexOf(this);
  11618. if (index !== -1) {
  11619. this._parentNode._children.splice(index, 1);
  11620. }
  11621. }
  11622. this._parentNode = parent;
  11623. if (this._parentNode) {
  11624. if (!this._parentNode._children) {
  11625. this._parentNode._children = new Array();
  11626. }
  11627. this._parentNode._children.push(this);
  11628. }
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Node.prototype.getClassName = function () {
  11634. return "Node";
  11635. };
  11636. Object.defineProperty(Node.prototype, "onDispose", {
  11637. set: function (callback) {
  11638. if (this._onDisposeObserver) {
  11639. this.onDisposeObservable.remove(this._onDisposeObserver);
  11640. }
  11641. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Node.prototype.getScene = function () {
  11647. return this._scene;
  11648. };
  11649. Node.prototype.getEngine = function () {
  11650. return this._scene.getEngine();
  11651. };
  11652. Node.prototype.addBehavior = function (behavior) {
  11653. var index = this._behaviors.indexOf(behavior);
  11654. if (index !== -1) {
  11655. return;
  11656. }
  11657. behavior.attach(this);
  11658. this._behaviors.push(behavior);
  11659. return this;
  11660. };
  11661. Node.prototype.removeBehavior = function (behavior) {
  11662. var index = this._behaviors.indexOf(behavior);
  11663. if (index === -1) {
  11664. return;
  11665. }
  11666. this._behaviors[index].detach();
  11667. this._behaviors.splice(index, 1);
  11668. return this;
  11669. };
  11670. Object.defineProperty(Node.prototype, "behaviors", {
  11671. get: function () {
  11672. return this._behaviors;
  11673. },
  11674. enumerable: true,
  11675. configurable: true
  11676. });
  11677. Node.prototype.getBehaviorByName = function (name) {
  11678. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11679. var behavior = _a[_i];
  11680. if (behavior.name === name) {
  11681. return behavior;
  11682. }
  11683. }
  11684. return null;
  11685. };
  11686. // override it in derived class
  11687. Node.prototype.getWorldMatrix = function () {
  11688. return BABYLON.Matrix.Identity();
  11689. };
  11690. // override it in derived class if you add new variables to the cache
  11691. // and call the parent class method
  11692. Node.prototype._initCache = function () {
  11693. this._cache = {};
  11694. this._cache.parent = undefined;
  11695. };
  11696. Node.prototype.updateCache = function (force) {
  11697. if (!force && this.isSynchronized())
  11698. return;
  11699. this._cache.parent = this.parent;
  11700. this._updateCache();
  11701. };
  11702. // override it in derived class if you add new variables to the cache
  11703. // and call the parent class method if !ignoreParentClass
  11704. Node.prototype._updateCache = function (ignoreParentClass) {
  11705. };
  11706. // override it in derived class if you add new variables to the cache
  11707. Node.prototype._isSynchronized = function () {
  11708. return true;
  11709. };
  11710. Node.prototype._markSyncedWithParent = function () {
  11711. this._parentRenderId = this.parent._currentRenderId;
  11712. };
  11713. Node.prototype.isSynchronizedWithParent = function () {
  11714. if (!this.parent) {
  11715. return true;
  11716. }
  11717. if (this._parentRenderId !== this.parent._currentRenderId) {
  11718. return false;
  11719. }
  11720. return this.parent.isSynchronized();
  11721. };
  11722. Node.prototype.isSynchronized = function (updateCache) {
  11723. var check = this.hasNewParent();
  11724. check = check || !this.isSynchronizedWithParent();
  11725. check = check || !this._isSynchronized();
  11726. if (updateCache)
  11727. this.updateCache(true);
  11728. return !check;
  11729. };
  11730. Node.prototype.hasNewParent = function (update) {
  11731. if (this._cache.parent === this.parent)
  11732. return false;
  11733. if (update)
  11734. this._cache.parent = this.parent;
  11735. return true;
  11736. };
  11737. /**
  11738. * Is this node ready to be used/rendered
  11739. * @return {boolean} is it ready
  11740. */
  11741. Node.prototype.isReady = function () {
  11742. return this._isReady;
  11743. };
  11744. /**
  11745. * Is this node enabled.
  11746. * If the node has a parent and is enabled, the parent will be inspected as well.
  11747. * @return {boolean} whether this node (and its parent) is enabled.
  11748. * @see setEnabled
  11749. */
  11750. Node.prototype.isEnabled = function () {
  11751. if (!this._isEnabled) {
  11752. return false;
  11753. }
  11754. if (this.parent) {
  11755. return this.parent.isEnabled();
  11756. }
  11757. return true;
  11758. };
  11759. /**
  11760. * Set the enabled state of this node.
  11761. * @param {boolean} value - the new enabled state
  11762. * @see isEnabled
  11763. */
  11764. Node.prototype.setEnabled = function (value) {
  11765. this._isEnabled = value;
  11766. };
  11767. /**
  11768. * Is this node a descendant of the given node.
  11769. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11770. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11771. * @see parent
  11772. */
  11773. Node.prototype.isDescendantOf = function (ancestor) {
  11774. if (this.parent) {
  11775. if (this.parent === ancestor) {
  11776. return true;
  11777. }
  11778. return this.parent.isDescendantOf(ancestor);
  11779. }
  11780. return false;
  11781. };
  11782. /**
  11783. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11784. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11785. * @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.
  11786. * @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.
  11787. */
  11788. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11789. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11790. if (!this._children) {
  11791. return;
  11792. }
  11793. for (var index = 0; index < this._children.length; index++) {
  11794. var item = this._children[index];
  11795. if (!predicate || predicate(item)) {
  11796. results.push(item);
  11797. }
  11798. if (!directDescendantsOnly) {
  11799. item._getDescendants(results, false, predicate);
  11800. }
  11801. }
  11802. };
  11803. /**
  11804. * Will return all nodes that have this node as ascendant.
  11805. * @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.
  11806. * @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.
  11807. * @return {BABYLON.Node[]} all children nodes of all types.
  11808. */
  11809. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11810. var results = new Array();
  11811. this._getDescendants(results, directDescendantsOnly, predicate);
  11812. return results;
  11813. };
  11814. /**
  11815. * Get all child-meshes of this node.
  11816. */
  11817. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11818. var results = [];
  11819. this._getDescendants(results, directDecendantsOnly, function (node) {
  11820. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11821. });
  11822. return results;
  11823. };
  11824. /**
  11825. * Get all direct children of this node.
  11826. */
  11827. Node.prototype.getChildren = function (predicate) {
  11828. return this.getDescendants(true, predicate);
  11829. };
  11830. Node.prototype._setReady = function (state) {
  11831. if (state === this._isReady) {
  11832. return;
  11833. }
  11834. if (!state) {
  11835. this._isReady = false;
  11836. return;
  11837. }
  11838. this._isReady = true;
  11839. if (this.onReady) {
  11840. this.onReady(this);
  11841. }
  11842. };
  11843. Node.prototype.getAnimationByName = function (name) {
  11844. for (var i = 0; i < this.animations.length; i++) {
  11845. var animation = this.animations[i];
  11846. if (animation.name === name) {
  11847. return animation;
  11848. }
  11849. }
  11850. return null;
  11851. };
  11852. Node.prototype.createAnimationRange = function (name, from, to) {
  11853. // check name not already in use
  11854. if (!this._ranges[name]) {
  11855. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11856. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11857. if (this.animations[i]) {
  11858. this.animations[i].createRange(name, from, to);
  11859. }
  11860. }
  11861. }
  11862. };
  11863. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11864. if (deleteFrames === void 0) { deleteFrames = true; }
  11865. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11866. if (this.animations[i]) {
  11867. this.animations[i].deleteRange(name, deleteFrames);
  11868. }
  11869. }
  11870. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11871. };
  11872. Node.prototype.getAnimationRange = function (name) {
  11873. return this._ranges[name];
  11874. };
  11875. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11876. var range = this.getAnimationRange(name);
  11877. if (!range) {
  11878. return null;
  11879. }
  11880. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11881. };
  11882. Node.prototype.serializeAnimationRanges = function () {
  11883. var serializationRanges = [];
  11884. for (var name in this._ranges) {
  11885. var range = {};
  11886. range.name = name;
  11887. range.from = this._ranges[name].from;
  11888. range.to = this._ranges[name].to;
  11889. serializationRanges.push(range);
  11890. }
  11891. return serializationRanges;
  11892. };
  11893. Node.prototype.dispose = function () {
  11894. this.parent = null;
  11895. // Callback
  11896. this.onDisposeObservable.notifyObservers(this);
  11897. this.onDisposeObservable.clear();
  11898. // Behaviors
  11899. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11900. var behavior = _a[_i];
  11901. behavior.detach();
  11902. }
  11903. this._behaviors = [];
  11904. };
  11905. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11906. if (parsedNode.ranges) {
  11907. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11908. var data = parsedNode.ranges[index];
  11909. node.createAnimationRange(data.name, data.from, data.to);
  11910. }
  11911. }
  11912. };
  11913. __decorate([
  11914. BABYLON.serialize()
  11915. ], Node.prototype, "name", void 0);
  11916. __decorate([
  11917. BABYLON.serialize()
  11918. ], Node.prototype, "id", void 0);
  11919. __decorate([
  11920. BABYLON.serialize()
  11921. ], Node.prototype, "uniqueId", void 0);
  11922. __decorate([
  11923. BABYLON.serialize()
  11924. ], Node.prototype, "state", void 0);
  11925. __decorate([
  11926. BABYLON.serialize()
  11927. ], Node.prototype, "metadata", void 0);
  11928. return Node;
  11929. }());
  11930. BABYLON.Node = Node;
  11931. })(BABYLON || (BABYLON = {}));
  11932. //# sourceMappingURL=babylon.node.js.map
  11933. var BABYLON;
  11934. (function (BABYLON) {
  11935. var BoundingSphere = (function () {
  11936. function BoundingSphere(minimum, maximum) {
  11937. this.minimum = minimum;
  11938. this.maximum = maximum;
  11939. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11940. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11941. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11942. this.radius = distance * 0.5;
  11943. this.centerWorld = BABYLON.Vector3.Zero();
  11944. this._update(BABYLON.Matrix.Identity());
  11945. }
  11946. // Methods
  11947. BoundingSphere.prototype._update = function (world) {
  11948. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11949. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11950. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11951. };
  11952. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11953. for (var i = 0; i < 6; i++) {
  11954. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11955. return false;
  11956. }
  11957. return true;
  11958. };
  11959. BoundingSphere.prototype.intersectsPoint = function (point) {
  11960. var x = this.centerWorld.x - point.x;
  11961. var y = this.centerWorld.y - point.y;
  11962. var z = this.centerWorld.z - point.z;
  11963. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11964. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11965. return false;
  11966. return true;
  11967. };
  11968. // Statics
  11969. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11970. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11971. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11972. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11973. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11974. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11975. return false;
  11976. return true;
  11977. };
  11978. return BoundingSphere;
  11979. }());
  11980. BABYLON.BoundingSphere = BoundingSphere;
  11981. })(BABYLON || (BABYLON = {}));
  11982. //# sourceMappingURL=babylon.boundingSphere.js.map
  11983. var BABYLON;
  11984. (function (BABYLON) {
  11985. var BoundingBox = (function () {
  11986. function BoundingBox(minimum, maximum) {
  11987. this.minimum = minimum;
  11988. this.maximum = maximum;
  11989. this.vectors = new Array();
  11990. this.vectorsWorld = new Array();
  11991. // Bounding vectors
  11992. this.vectors.push(this.minimum.clone());
  11993. this.vectors.push(this.maximum.clone());
  11994. this.vectors.push(this.minimum.clone());
  11995. this.vectors[2].x = this.maximum.x;
  11996. this.vectors.push(this.minimum.clone());
  11997. this.vectors[3].y = this.maximum.y;
  11998. this.vectors.push(this.minimum.clone());
  11999. this.vectors[4].z = this.maximum.z;
  12000. this.vectors.push(this.maximum.clone());
  12001. this.vectors[5].z = this.minimum.z;
  12002. this.vectors.push(this.maximum.clone());
  12003. this.vectors[6].x = this.minimum.x;
  12004. this.vectors.push(this.maximum.clone());
  12005. this.vectors[7].y = this.minimum.y;
  12006. // OBB
  12007. this.center = this.maximum.add(this.minimum).scale(0.5);
  12008. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12009. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12010. // World
  12011. for (var index = 0; index < this.vectors.length; index++) {
  12012. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12013. }
  12014. this.minimumWorld = BABYLON.Vector3.Zero();
  12015. this.maximumWorld = BABYLON.Vector3.Zero();
  12016. this.centerWorld = BABYLON.Vector3.Zero();
  12017. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12018. this._update(BABYLON.Matrix.Identity());
  12019. }
  12020. // Methods
  12021. BoundingBox.prototype.getWorldMatrix = function () {
  12022. return this._worldMatrix;
  12023. };
  12024. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12025. this._worldMatrix.copyFrom(matrix);
  12026. return this;
  12027. };
  12028. BoundingBox.prototype._update = function (world) {
  12029. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12030. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12031. for (var index = 0; index < this.vectors.length; index++) {
  12032. var v = this.vectorsWorld[index];
  12033. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12034. if (v.x < this.minimumWorld.x)
  12035. this.minimumWorld.x = v.x;
  12036. if (v.y < this.minimumWorld.y)
  12037. this.minimumWorld.y = v.y;
  12038. if (v.z < this.minimumWorld.z)
  12039. this.minimumWorld.z = v.z;
  12040. if (v.x > this.maximumWorld.x)
  12041. this.maximumWorld.x = v.x;
  12042. if (v.y > this.maximumWorld.y)
  12043. this.maximumWorld.y = v.y;
  12044. if (v.z > this.maximumWorld.z)
  12045. this.maximumWorld.z = v.z;
  12046. }
  12047. // Extend
  12048. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12049. this.extendSizeWorld.scaleInPlace(0.5);
  12050. // OBB
  12051. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12052. this.centerWorld.scaleInPlace(0.5);
  12053. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12054. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12055. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12056. this._worldMatrix = world;
  12057. };
  12058. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12059. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12060. };
  12061. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12062. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12063. };
  12064. BoundingBox.prototype.intersectsPoint = function (point) {
  12065. var delta = -BABYLON.Epsilon;
  12066. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12067. return false;
  12068. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12069. return false;
  12070. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12071. return false;
  12072. return true;
  12073. };
  12074. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12075. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12076. };
  12077. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12078. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12079. return false;
  12080. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12081. return false;
  12082. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12083. return false;
  12084. return true;
  12085. };
  12086. // Statics
  12087. BoundingBox.Intersects = function (box0, box1) {
  12088. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12089. return false;
  12090. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12091. return false;
  12092. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12093. return false;
  12094. return true;
  12095. };
  12096. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12097. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12098. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12099. return (num <= (sphereRadius * sphereRadius));
  12100. };
  12101. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12102. for (var p = 0; p < 6; p++) {
  12103. for (var i = 0; i < 8; i++) {
  12104. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12105. return false;
  12106. }
  12107. }
  12108. }
  12109. return true;
  12110. };
  12111. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12112. for (var p = 0; p < 6; p++) {
  12113. var inCount = 8;
  12114. for (var i = 0; i < 8; i++) {
  12115. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12116. --inCount;
  12117. }
  12118. else {
  12119. break;
  12120. }
  12121. }
  12122. if (inCount === 0)
  12123. return false;
  12124. }
  12125. return true;
  12126. };
  12127. return BoundingBox;
  12128. }());
  12129. BABYLON.BoundingBox = BoundingBox;
  12130. })(BABYLON || (BABYLON = {}));
  12131. //# sourceMappingURL=babylon.boundingBox.js.map
  12132. var BABYLON;
  12133. (function (BABYLON) {
  12134. var computeBoxExtents = function (axis, box) {
  12135. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12136. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12137. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12138. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12139. var r = r0 + r1 + r2;
  12140. return {
  12141. min: p - r,
  12142. max: p + r
  12143. };
  12144. };
  12145. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12146. var axisOverlap = function (axis, box0, box1) {
  12147. var result0 = computeBoxExtents(axis, box0);
  12148. var result1 = computeBoxExtents(axis, box1);
  12149. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12150. };
  12151. var BoundingInfo = (function () {
  12152. function BoundingInfo(minimum, maximum) {
  12153. this.minimum = minimum;
  12154. this.maximum = maximum;
  12155. this._isLocked = false;
  12156. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12157. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12158. }
  12159. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12160. get: function () {
  12161. return this._isLocked;
  12162. },
  12163. set: function (value) {
  12164. this._isLocked = value;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. // Methods
  12170. BoundingInfo.prototype.update = function (world) {
  12171. if (this._isLocked) {
  12172. return;
  12173. }
  12174. this.boundingBox._update(world);
  12175. this.boundingSphere._update(world);
  12176. };
  12177. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12178. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12179. return false;
  12180. return this.boundingBox.isInFrustum(frustumPlanes);
  12181. };
  12182. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12183. /**
  12184. * Gets the world distance between the min and max points of the bounding box
  12185. */
  12186. get: function () {
  12187. var boundingBox = this.boundingBox;
  12188. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12189. return size.length();
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12195. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12196. };
  12197. BoundingInfo.prototype._checkCollision = function (collider) {
  12198. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12199. };
  12200. BoundingInfo.prototype.intersectsPoint = function (point) {
  12201. if (!this.boundingSphere.centerWorld) {
  12202. return false;
  12203. }
  12204. if (!this.boundingSphere.intersectsPoint(point)) {
  12205. return false;
  12206. }
  12207. if (!this.boundingBox.intersectsPoint(point)) {
  12208. return false;
  12209. }
  12210. return true;
  12211. };
  12212. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12213. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12214. return false;
  12215. }
  12216. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12217. return false;
  12218. }
  12219. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12220. return false;
  12221. }
  12222. if (!precise) {
  12223. return true;
  12224. }
  12225. var box0 = this.boundingBox;
  12226. var box1 = boundingInfo.boundingBox;
  12227. if (!axisOverlap(box0.directions[0], box0, box1))
  12228. return false;
  12229. if (!axisOverlap(box0.directions[1], box0, box1))
  12230. return false;
  12231. if (!axisOverlap(box0.directions[2], box0, box1))
  12232. return false;
  12233. if (!axisOverlap(box1.directions[0], box0, box1))
  12234. return false;
  12235. if (!axisOverlap(box1.directions[1], box0, box1))
  12236. return false;
  12237. if (!axisOverlap(box1.directions[2], box0, box1))
  12238. return false;
  12239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12240. return false;
  12241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12242. return false;
  12243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12244. return false;
  12245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12246. return false;
  12247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12248. return false;
  12249. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12250. return false;
  12251. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12252. return false;
  12253. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12254. return false;
  12255. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12256. return false;
  12257. return true;
  12258. };
  12259. return BoundingInfo;
  12260. }());
  12261. BABYLON.BoundingInfo = BoundingInfo;
  12262. })(BABYLON || (BABYLON = {}));
  12263. //# sourceMappingURL=babylon.boundingInfo.js.map
  12264. var BABYLON;
  12265. (function (BABYLON) {
  12266. var AbstractMesh = (function (_super) {
  12267. __extends(AbstractMesh, _super);
  12268. // Constructor
  12269. function AbstractMesh(name, scene) {
  12270. var _this = _super.call(this, name, scene) || this;
  12271. _this._facetNb = 0; // facet number
  12272. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12273. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12274. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12275. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12276. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12277. _this._subDiv = {
  12278. max: 1,
  12279. X: 1,
  12280. Y: 1,
  12281. Z: 1
  12282. };
  12283. // Events
  12284. /**
  12285. * An event triggered when this mesh collides with another one
  12286. * @type {BABYLON.Observable}
  12287. */
  12288. _this.onCollideObservable = new BABYLON.Observable();
  12289. /**
  12290. * An event triggered when the collision's position changes
  12291. * @type {BABYLON.Observable}
  12292. */
  12293. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12294. /**
  12295. * An event triggered after the world matrix is updated
  12296. * @type {BABYLON.Observable}
  12297. */
  12298. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12299. /**
  12300. * An event triggered when material is changed
  12301. * @type {BABYLON.Observable}
  12302. */
  12303. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12304. // Properties
  12305. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12306. _this.position = BABYLON.Vector3.Zero();
  12307. /**
  12308. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12309. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12310. * or
  12311. * 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.
  12312. * for more info check WebGl documentations
  12313. */
  12314. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12315. /**
  12316. * 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:
  12317. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12318. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12319. * 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.
  12320. */
  12321. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12322. /**
  12323. * 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.
  12324. * The default value is -1 which means don't break the query and wait till the result.
  12325. */
  12326. _this.occlusionRetryCount = -1;
  12327. _this._occlusionInternalRetryCounter = 0;
  12328. _this._isOccluded = false;
  12329. _this._isOcclusionQueryInProgress = false;
  12330. _this._rotation = BABYLON.Vector3.Zero();
  12331. _this._scaling = BABYLON.Vector3.One();
  12332. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12333. _this.visibility = 1.0;
  12334. _this.alphaIndex = Number.MAX_VALUE;
  12335. _this.infiniteDistance = false;
  12336. _this.isVisible = true;
  12337. _this.isPickable = true;
  12338. _this.showBoundingBox = false;
  12339. _this.showSubMeshesBoundingBox = false;
  12340. _this.isBlocker = false;
  12341. _this.enablePointerMoveEvents = false;
  12342. _this.renderingGroupId = 0;
  12343. _this._receiveShadows = false;
  12344. _this.renderOutline = false;
  12345. _this.outlineColor = BABYLON.Color3.Red();
  12346. _this.outlineWidth = 0.02;
  12347. _this.renderOverlay = false;
  12348. _this.overlayColor = BABYLON.Color3.Red();
  12349. _this.overlayAlpha = 0.5;
  12350. _this._hasVertexAlpha = false;
  12351. _this._useVertexColors = true;
  12352. _this._computeBonesUsingShaders = true;
  12353. _this._numBoneInfluencers = 4;
  12354. _this._applyFog = true;
  12355. _this.scalingDeterminant = 1;
  12356. _this.useOctreeForRenderingSelection = true;
  12357. _this.useOctreeForPicking = true;
  12358. _this.useOctreeForCollisions = true;
  12359. _this._layerMask = 0x0FFFFFFF;
  12360. /**
  12361. * True if the mesh must be rendered in any case.
  12362. */
  12363. _this.alwaysSelectAsActiveMesh = false;
  12364. // Collisions
  12365. _this._checkCollisions = false;
  12366. _this._collisionMask = -1;
  12367. _this._collisionGroup = -1;
  12368. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12369. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12370. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12371. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12372. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12373. // Edges
  12374. _this.edgesWidth = 1;
  12375. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12376. // Cache
  12377. _this._localWorld = BABYLON.Matrix.Zero();
  12378. _this._worldMatrix = BABYLON.Matrix.Zero();
  12379. _this._absolutePosition = BABYLON.Vector3.Zero();
  12380. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12381. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12382. _this._isDirty = false;
  12383. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12384. _this._postMultiplyPivotMatrix = false;
  12385. _this._isDisposed = false;
  12386. _this._renderId = 0;
  12387. _this._intersectionsInProgress = new Array();
  12388. _this._isWorldMatrixFrozen = false;
  12389. _this._unIndexed = false;
  12390. _this._lightSources = new Array();
  12391. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12392. if (collidedMesh === void 0) { collidedMesh = null; }
  12393. //TODO move this to the collision coordinator!
  12394. if (_this.getScene().workerCollisions)
  12395. newPosition.multiplyInPlace(_this._collider.radius);
  12396. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12397. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12398. _this.position.addInPlace(_this._diffPositionForCollisions);
  12399. }
  12400. if (collidedMesh) {
  12401. _this.onCollideObservable.notifyObservers(collidedMesh);
  12402. }
  12403. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12404. };
  12405. _this.getScene().addMesh(_this);
  12406. _this._resyncLightSources();
  12407. return _this;
  12408. }
  12409. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12410. get: function () {
  12411. return AbstractMesh._BILLBOARDMODE_NONE;
  12412. },
  12413. enumerable: true,
  12414. configurable: true
  12415. });
  12416. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12417. get: function () {
  12418. return AbstractMesh._BILLBOARDMODE_X;
  12419. },
  12420. enumerable: true,
  12421. configurable: true
  12422. });
  12423. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12424. get: function () {
  12425. return AbstractMesh._BILLBOARDMODE_Y;
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12431. get: function () {
  12432. return AbstractMesh._BILLBOARDMODE_Z;
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12438. get: function () {
  12439. return AbstractMesh._BILLBOARDMODE_ALL;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12445. /**
  12446. * Read-only : the number of facets in the mesh
  12447. */
  12448. get: function () {
  12449. return this._facetNb;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12455. /**
  12456. * The number (integer) of subdivisions per axis in the partioning space
  12457. */
  12458. get: function () {
  12459. return this._partitioningSubdivisions;
  12460. },
  12461. set: function (nb) {
  12462. this._partitioningSubdivisions = nb;
  12463. },
  12464. enumerable: true,
  12465. configurable: true
  12466. });
  12467. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12468. /**
  12469. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12470. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12471. */
  12472. get: function () {
  12473. return this._partitioningBBoxRatio;
  12474. },
  12475. set: function (ratio) {
  12476. this._partitioningBBoxRatio = ratio;
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12482. /**
  12483. * Read-only boolean : is the feature facetData enabled ?
  12484. */
  12485. get: function () {
  12486. return this._facetDataEnabled;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12492. set: function (callback) {
  12493. if (this._onCollideObserver) {
  12494. this.onCollideObservable.remove(this._onCollideObserver);
  12495. }
  12496. this._onCollideObserver = this.onCollideObservable.add(callback);
  12497. },
  12498. enumerable: true,
  12499. configurable: true
  12500. });
  12501. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12502. set: function (callback) {
  12503. if (this._onCollisionPositionChangeObserver) {
  12504. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12505. }
  12506. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12507. },
  12508. enumerable: true,
  12509. configurable: true
  12510. });
  12511. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12512. /**
  12513. * 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.
  12514. */
  12515. get: function () {
  12516. return this._isOccluded;
  12517. },
  12518. set: function (value) {
  12519. this._isOccluded = value;
  12520. },
  12521. enumerable: true,
  12522. configurable: true
  12523. });
  12524. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12525. /**
  12526. * Flag to check the progress status of the query
  12527. */
  12528. get: function () {
  12529. return this._isOcclusionQueryInProgress;
  12530. },
  12531. enumerable: true,
  12532. configurable: true
  12533. });
  12534. Object.defineProperty(AbstractMesh.prototype, "material", {
  12535. get: function () {
  12536. return this._material;
  12537. },
  12538. set: function (value) {
  12539. if (this._material === value) {
  12540. return;
  12541. }
  12542. this._material = value;
  12543. if (this.onMaterialChangedObservable.hasObservers) {
  12544. this.onMaterialChangedObservable.notifyObservers(this);
  12545. }
  12546. if (!this.subMeshes) {
  12547. return;
  12548. }
  12549. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12550. var subMesh = _a[_i];
  12551. subMesh.setEffect(null);
  12552. }
  12553. },
  12554. enumerable: true,
  12555. configurable: true
  12556. });
  12557. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12558. get: function () {
  12559. return this._receiveShadows;
  12560. },
  12561. set: function (value) {
  12562. if (this._receiveShadows === value) {
  12563. return;
  12564. }
  12565. this._receiveShadows = value;
  12566. this._markSubMeshesAsLightDirty();
  12567. },
  12568. enumerable: true,
  12569. configurable: true
  12570. });
  12571. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12572. get: function () {
  12573. return this._hasVertexAlpha;
  12574. },
  12575. set: function (value) {
  12576. if (this._hasVertexAlpha === value) {
  12577. return;
  12578. }
  12579. this._hasVertexAlpha = value;
  12580. this._markSubMeshesAsAttributesDirty();
  12581. },
  12582. enumerable: true,
  12583. configurable: true
  12584. });
  12585. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12586. get: function () {
  12587. return this._useVertexColors;
  12588. },
  12589. set: function (value) {
  12590. if (this._useVertexColors === value) {
  12591. return;
  12592. }
  12593. this._useVertexColors = value;
  12594. this._markSubMeshesAsAttributesDirty();
  12595. },
  12596. enumerable: true,
  12597. configurable: true
  12598. });
  12599. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12600. get: function () {
  12601. return this._computeBonesUsingShaders;
  12602. },
  12603. set: function (value) {
  12604. if (this._computeBonesUsingShaders === value) {
  12605. return;
  12606. }
  12607. this._computeBonesUsingShaders = value;
  12608. this._markSubMeshesAsAttributesDirty();
  12609. },
  12610. enumerable: true,
  12611. configurable: true
  12612. });
  12613. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12614. get: function () {
  12615. return this._numBoneInfluencers;
  12616. },
  12617. set: function (value) {
  12618. if (this._numBoneInfluencers === value) {
  12619. return;
  12620. }
  12621. this._numBoneInfluencers = value;
  12622. this._markSubMeshesAsAttributesDirty();
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12628. get: function () {
  12629. return this._applyFog;
  12630. },
  12631. set: function (value) {
  12632. if (this._applyFog === value) {
  12633. return;
  12634. }
  12635. this._applyFog = value;
  12636. this._markSubMeshesAsMiscDirty();
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12642. get: function () {
  12643. return this._layerMask;
  12644. },
  12645. set: function (value) {
  12646. if (value === this._layerMask) {
  12647. return;
  12648. }
  12649. this._layerMask = value;
  12650. this._resyncLightSources();
  12651. },
  12652. enumerable: true,
  12653. configurable: true
  12654. });
  12655. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12656. get: function () {
  12657. return this._collisionMask;
  12658. },
  12659. set: function (mask) {
  12660. this._collisionMask = !isNaN(mask) ? mask : -1;
  12661. },
  12662. enumerable: true,
  12663. configurable: true
  12664. });
  12665. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12666. get: function () {
  12667. return this._collisionGroup;
  12668. },
  12669. set: function (mask) {
  12670. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12676. get: function () {
  12677. return null;
  12678. },
  12679. enumerable: true,
  12680. configurable: true
  12681. });
  12682. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12683. get: function () {
  12684. return this._skeleton;
  12685. },
  12686. set: function (value) {
  12687. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12688. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12689. }
  12690. if (value && value.needInitialSkinMatrix) {
  12691. value._registerMeshWithPoseMatrix(this);
  12692. }
  12693. this._skeleton = value;
  12694. if (!this._skeleton) {
  12695. this._bonesTransformMatrices = null;
  12696. }
  12697. this._markSubMeshesAsAttributesDirty();
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. /**
  12703. * Boolean : true if the mesh has been disposed.
  12704. */
  12705. AbstractMesh.prototype.isDisposed = function () {
  12706. return this._isDisposed;
  12707. };
  12708. /**
  12709. * Returns the string "AbstractMesh"
  12710. */
  12711. AbstractMesh.prototype.getClassName = function () {
  12712. return "AbstractMesh";
  12713. };
  12714. /**
  12715. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12716. */
  12717. AbstractMesh.prototype.toString = function (fullDetails) {
  12718. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12719. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12720. if (this._skeleton) {
  12721. ret += ", skeleton: " + this._skeleton.name;
  12722. }
  12723. if (fullDetails) {
  12724. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12725. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12726. }
  12727. return ret;
  12728. };
  12729. AbstractMesh.prototype._rebuild = function () {
  12730. if (this._occlusionQuery) {
  12731. this._occlusionQuery = null;
  12732. }
  12733. if (this._edgesRenderer) {
  12734. this._edgesRenderer._rebuild();
  12735. }
  12736. if (!this.subMeshes) {
  12737. return;
  12738. }
  12739. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12740. var subMesh = _a[_i];
  12741. subMesh._rebuild();
  12742. }
  12743. };
  12744. AbstractMesh.prototype._resyncLightSources = function () {
  12745. this._lightSources.length = 0;
  12746. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12747. var light = _a[_i];
  12748. if (!light.isEnabled()) {
  12749. continue;
  12750. }
  12751. if (light.canAffectMesh(this)) {
  12752. this._lightSources.push(light);
  12753. }
  12754. }
  12755. this._markSubMeshesAsLightDirty();
  12756. };
  12757. AbstractMesh.prototype._resyncLighSource = function (light) {
  12758. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12759. var index = this._lightSources.indexOf(light);
  12760. if (index === -1) {
  12761. if (!isIn) {
  12762. return;
  12763. }
  12764. this._lightSources.push(light);
  12765. }
  12766. else {
  12767. if (isIn) {
  12768. return;
  12769. }
  12770. this._lightSources.splice(index, 1);
  12771. }
  12772. this._markSubMeshesAsLightDirty();
  12773. };
  12774. AbstractMesh.prototype._removeLightSource = function (light) {
  12775. var index = this._lightSources.indexOf(light);
  12776. if (index === -1) {
  12777. return;
  12778. }
  12779. this._lightSources.splice(index, 1);
  12780. };
  12781. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12782. if (!this.subMeshes) {
  12783. return;
  12784. }
  12785. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12786. var subMesh = _a[_i];
  12787. if (subMesh._materialDefines) {
  12788. func(subMesh._materialDefines);
  12789. }
  12790. }
  12791. };
  12792. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12793. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12794. };
  12795. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12796. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12797. };
  12798. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12799. if (!this.subMeshes) {
  12800. return;
  12801. }
  12802. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12803. var subMesh = _a[_i];
  12804. var material = subMesh.getMaterial();
  12805. if (material) {
  12806. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12807. }
  12808. }
  12809. };
  12810. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12811. /**
  12812. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12813. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12814. * Default : (0.0, 0.0, 0.0)
  12815. */
  12816. get: function () {
  12817. return this._rotation;
  12818. },
  12819. set: function (newRotation) {
  12820. this._rotation = newRotation;
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12826. /**
  12827. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12828. * Default : (1.0, 1.0, 1.0)
  12829. */
  12830. get: function () {
  12831. return this._scaling;
  12832. },
  12833. set: function (newScaling) {
  12834. this._scaling = newScaling;
  12835. if (this.physicsImpostor) {
  12836. this.physicsImpostor.forceUpdate();
  12837. }
  12838. },
  12839. enumerable: true,
  12840. configurable: true
  12841. });
  12842. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12843. /**
  12844. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12845. * It's null by default.
  12846. * 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)
  12847. */
  12848. get: function () {
  12849. return this._rotationQuaternion;
  12850. },
  12851. set: function (quaternion) {
  12852. this._rotationQuaternion = quaternion;
  12853. //reset the rotation vector.
  12854. if (quaternion && this.rotation.length()) {
  12855. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12856. }
  12857. },
  12858. enumerable: true,
  12859. configurable: true
  12860. });
  12861. // Methods
  12862. /**
  12863. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12864. * Returns the AbstractMesh.
  12865. */
  12866. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12867. this._poseMatrix.copyFrom(matrix);
  12868. return this;
  12869. };
  12870. /**
  12871. * Returns the mesh Pose matrix.
  12872. * Returned object : Matrix
  12873. */
  12874. AbstractMesh.prototype.getPoseMatrix = function () {
  12875. return this._poseMatrix;
  12876. };
  12877. /**
  12878. * Disables the mesh edger rendering mode.
  12879. * Returns the AbstractMesh.
  12880. */
  12881. AbstractMesh.prototype.disableEdgesRendering = function () {
  12882. if (this._edgesRenderer !== undefined) {
  12883. this._edgesRenderer.dispose();
  12884. this._edgesRenderer = undefined;
  12885. }
  12886. return this;
  12887. };
  12888. /**
  12889. * Enables the edge rendering mode on the mesh.
  12890. * This mode makes the mesh edges visible.
  12891. * Returns the AbstractMesh.
  12892. */
  12893. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12894. if (epsilon === void 0) { epsilon = 0.95; }
  12895. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12896. this.disableEdgesRendering();
  12897. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12898. return this;
  12899. };
  12900. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12901. /**
  12902. * Returns true if the mesh is blocked. Used by the class Mesh.
  12903. * Returns the boolean `false` by default.
  12904. */
  12905. get: function () {
  12906. return false;
  12907. },
  12908. enumerable: true,
  12909. configurable: true
  12910. });
  12911. /**
  12912. * Returns the mesh itself by default, used by the class Mesh.
  12913. * Returned type : AbstractMesh
  12914. */
  12915. AbstractMesh.prototype.getLOD = function (camera) {
  12916. return this;
  12917. };
  12918. /**
  12919. * Returns 0 by default, used by the class Mesh.
  12920. * Returns an integer.
  12921. */
  12922. AbstractMesh.prototype.getTotalVertices = function () {
  12923. return 0;
  12924. };
  12925. /**
  12926. * Returns null by default, used by the class Mesh.
  12927. * Returned type : integer array
  12928. */
  12929. AbstractMesh.prototype.getIndices = function () {
  12930. return null;
  12931. };
  12932. /**
  12933. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12934. * Returned type : float array or Float32Array
  12935. */
  12936. AbstractMesh.prototype.getVerticesData = function (kind) {
  12937. return null;
  12938. };
  12939. /**
  12940. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12941. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12942. * The `data` are either a numeric array either a Float32Array.
  12943. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12944. * 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).
  12945. * Note that a new underlying VertexBuffer object is created each call.
  12946. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12947. *
  12948. * Possible `kind` values :
  12949. * - BABYLON.VertexBuffer.PositionKind
  12950. * - BABYLON.VertexBuffer.UVKind
  12951. * - BABYLON.VertexBuffer.UV2Kind
  12952. * - BABYLON.VertexBuffer.UV3Kind
  12953. * - BABYLON.VertexBuffer.UV4Kind
  12954. * - BABYLON.VertexBuffer.UV5Kind
  12955. * - BABYLON.VertexBuffer.UV6Kind
  12956. * - BABYLON.VertexBuffer.ColorKind
  12957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12961. *
  12962. * Returns the Mesh.
  12963. */
  12964. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12965. return null;
  12966. };
  12967. /**
  12968. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12969. * If the mesh has no geometry, it is simply returned as it is.
  12970. * The `data` are either a numeric array either a Float32Array.
  12971. * No new underlying VertexBuffer object is created.
  12972. * 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.
  12973. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12974. *
  12975. * Possible `kind` values :
  12976. * - BABYLON.VertexBuffer.PositionKind
  12977. * - BABYLON.VertexBuffer.UVKind
  12978. * - BABYLON.VertexBuffer.UV2Kind
  12979. * - BABYLON.VertexBuffer.UV3Kind
  12980. * - BABYLON.VertexBuffer.UV4Kind
  12981. * - BABYLON.VertexBuffer.UV5Kind
  12982. * - BABYLON.VertexBuffer.UV6Kind
  12983. * - BABYLON.VertexBuffer.ColorKind
  12984. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12985. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12986. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12987. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12988. *
  12989. * Returns the Mesh.
  12990. */
  12991. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12992. return null;
  12993. };
  12994. /**
  12995. * Sets the mesh indices.
  12996. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12997. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12998. * This method creates a new index buffer each call.
  12999. * Returns the Mesh.
  13000. */
  13001. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13002. return null;
  13003. };
  13004. /** Returns false by default, used by the class Mesh.
  13005. * Returns a boolean
  13006. */
  13007. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13008. return false;
  13009. };
  13010. /**
  13011. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13012. * Returns a BoundingInfo
  13013. */
  13014. AbstractMesh.prototype.getBoundingInfo = function () {
  13015. if (this._masterMesh) {
  13016. return this._masterMesh.getBoundingInfo();
  13017. }
  13018. if (!this._boundingInfo) {
  13019. this._updateBoundingInfo();
  13020. }
  13021. return this._boundingInfo;
  13022. };
  13023. /**
  13024. * Sets a mesh new object BoundingInfo.
  13025. * Returns the AbstractMesh.
  13026. */
  13027. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13028. this._boundingInfo = boundingInfo;
  13029. return this;
  13030. };
  13031. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13032. get: function () {
  13033. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  13034. },
  13035. enumerable: true,
  13036. configurable: true
  13037. });
  13038. AbstractMesh.prototype._preActivate = function () {
  13039. };
  13040. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13041. };
  13042. AbstractMesh.prototype._activate = function (renderId) {
  13043. this._renderId = renderId;
  13044. };
  13045. /**
  13046. * Returns the last update of the World matrix
  13047. * Returns a Matrix.
  13048. */
  13049. AbstractMesh.prototype.getWorldMatrix = function () {
  13050. if (this._masterMesh) {
  13051. return this._masterMesh.getWorldMatrix();
  13052. }
  13053. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13054. this.computeWorldMatrix();
  13055. }
  13056. return this._worldMatrix;
  13057. };
  13058. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13059. /**
  13060. * Returns directly the last state of the mesh World matrix.
  13061. * A Matrix is returned.
  13062. */
  13063. get: function () {
  13064. return this._worldMatrix;
  13065. },
  13066. enumerable: true,
  13067. configurable: true
  13068. });
  13069. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13070. /**
  13071. * Returns the current mesh absolute position.
  13072. * Retuns a Vector3.
  13073. */
  13074. get: function () {
  13075. return this._absolutePosition;
  13076. },
  13077. enumerable: true,
  13078. configurable: true
  13079. });
  13080. /**
  13081. * Prevents the World matrix to be computed any longer.
  13082. * Returns the AbstractMesh.
  13083. */
  13084. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13085. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13086. this.computeWorldMatrix(true);
  13087. this._isWorldMatrixFrozen = true;
  13088. return this;
  13089. };
  13090. /**
  13091. * Allows back the World matrix computation.
  13092. * Returns the AbstractMesh.
  13093. */
  13094. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13095. this._isWorldMatrixFrozen = false;
  13096. this.computeWorldMatrix(true);
  13097. return this;
  13098. };
  13099. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13100. /**
  13101. * True if the World matrix has been frozen.
  13102. * Returns a boolean.
  13103. */
  13104. get: function () {
  13105. return this._isWorldMatrixFrozen;
  13106. },
  13107. enumerable: true,
  13108. configurable: true
  13109. });
  13110. /**
  13111. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13112. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13113. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13114. * The passed axis is also normalized.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13118. axis.normalize();
  13119. if (!this.rotationQuaternion) {
  13120. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13121. this.rotation = BABYLON.Vector3.Zero();
  13122. }
  13123. var rotationQuaternion;
  13124. if (!space || space === BABYLON.Space.LOCAL) {
  13125. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13126. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13127. }
  13128. else {
  13129. if (this.parent) {
  13130. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13131. invertParentWorldMatrix.invert();
  13132. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13133. }
  13134. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13135. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13136. }
  13137. return this;
  13138. };
  13139. /**
  13140. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13141. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13142. * The passed axis is also normalized.
  13143. * Returns the AbstractMesh.
  13144. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13145. */
  13146. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13147. axis.normalize();
  13148. if (!this.rotationQuaternion) {
  13149. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13150. this.rotation.copyFromFloats(0, 0, 0);
  13151. }
  13152. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13153. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13154. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13155. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13156. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13157. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13158. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13159. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13160. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13161. return this;
  13162. };
  13163. /**
  13164. * Translates the mesh along the axis vector for the passed distance in the given space.
  13165. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13166. * Returns the AbstractMesh.
  13167. */
  13168. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13169. var displacementVector = axis.scale(distance);
  13170. if (!space || space === BABYLON.Space.LOCAL) {
  13171. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13172. this.setPositionWithLocalVector(tempV3);
  13173. }
  13174. else {
  13175. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13176. }
  13177. return this;
  13178. };
  13179. /**
  13180. * Adds a rotation step to the mesh current rotation.
  13181. * x, y, z are Euler angles expressed in radians.
  13182. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13183. * This means this rotation is made in the mesh local space only.
  13184. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13185. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13186. * ```javascript
  13187. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13188. * ```
  13189. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13190. * 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.
  13191. * Returns the AbstractMesh.
  13192. */
  13193. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13194. var rotationQuaternion;
  13195. if (this.rotationQuaternion) {
  13196. rotationQuaternion = this.rotationQuaternion;
  13197. }
  13198. else {
  13199. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13200. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13201. }
  13202. var accumulation = BABYLON.Tmp.Quaternion[0];
  13203. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13204. rotationQuaternion.multiplyInPlace(accumulation);
  13205. if (!this.rotationQuaternion) {
  13206. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13207. }
  13208. return this;
  13209. };
  13210. /**
  13211. * Retuns the mesh absolute position in the World.
  13212. * Returns a Vector3.
  13213. */
  13214. AbstractMesh.prototype.getAbsolutePosition = function () {
  13215. this.computeWorldMatrix();
  13216. return this._absolutePosition;
  13217. };
  13218. /**
  13219. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13220. * Returns the AbstractMesh.
  13221. */
  13222. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13223. if (!absolutePosition) {
  13224. return;
  13225. }
  13226. var absolutePositionX;
  13227. var absolutePositionY;
  13228. var absolutePositionZ;
  13229. if (absolutePosition.x === undefined) {
  13230. if (arguments.length < 3) {
  13231. return;
  13232. }
  13233. absolutePositionX = arguments[0];
  13234. absolutePositionY = arguments[1];
  13235. absolutePositionZ = arguments[2];
  13236. }
  13237. else {
  13238. absolutePositionX = absolutePosition.x;
  13239. absolutePositionY = absolutePosition.y;
  13240. absolutePositionZ = absolutePosition.z;
  13241. }
  13242. if (this.parent) {
  13243. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13244. invertParentWorldMatrix.invert();
  13245. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13246. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13247. }
  13248. else {
  13249. this.position.x = absolutePositionX;
  13250. this.position.y = absolutePositionY;
  13251. this.position.z = absolutePositionZ;
  13252. }
  13253. return this;
  13254. };
  13255. // ================================== Point of View Movement =================================
  13256. /**
  13257. * Perform relative position change from the point of view of behind the front of the mesh.
  13258. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13259. * Supports definition of mesh facing forward or backward.
  13260. * @param {number} amountRight
  13261. * @param {number} amountUp
  13262. * @param {number} amountForward
  13263. *
  13264. * Returns the AbstractMesh.
  13265. */
  13266. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13267. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13268. return this;
  13269. };
  13270. /**
  13271. * Calculate relative position change from the point of view of behind the front of the mesh.
  13272. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13273. * Supports definition of mesh facing forward or backward.
  13274. * @param {number} amountRight
  13275. * @param {number} amountUp
  13276. * @param {number} amountForward
  13277. *
  13278. * Returns a new Vector3.
  13279. */
  13280. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13281. var rotMatrix = new BABYLON.Matrix();
  13282. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13283. rotQuaternion.toRotationMatrix(rotMatrix);
  13284. var translationDelta = BABYLON.Vector3.Zero();
  13285. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13286. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13287. return translationDelta;
  13288. };
  13289. // ================================== Point of View Rotation =================================
  13290. /**
  13291. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13292. * Supports definition of mesh facing forward or backward.
  13293. * @param {number} flipBack
  13294. * @param {number} twirlClockwise
  13295. * @param {number} tiltRight
  13296. *
  13297. * Returns the AbstractMesh.
  13298. */
  13299. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13300. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13301. return this;
  13302. };
  13303. /**
  13304. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13305. * Supports definition of mesh facing forward or backward.
  13306. * @param {number} flipBack
  13307. * @param {number} twirlClockwise
  13308. * @param {number} tiltRight
  13309. *
  13310. * Returns a new Vector3.
  13311. */
  13312. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13313. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13314. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13315. };
  13316. /**
  13317. * Sets a new pivot matrix to the mesh.
  13318. * Returns the AbstractMesh.
  13319. */
  13320. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13321. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13322. this._pivotMatrix = matrix.clone();
  13323. this._cache.pivotMatrixUpdated = true;
  13324. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13325. if (this._postMultiplyPivotMatrix) {
  13326. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13327. }
  13328. return this;
  13329. };
  13330. /**
  13331. * Returns the mesh pivot matrix.
  13332. * Default : Identity.
  13333. * A Matrix is returned.
  13334. */
  13335. AbstractMesh.prototype.getPivotMatrix = function () {
  13336. return this._pivotMatrix;
  13337. };
  13338. AbstractMesh.prototype._isSynchronized = function () {
  13339. if (this._isDirty) {
  13340. return false;
  13341. }
  13342. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13343. return false;
  13344. if (this._cache.pivotMatrixUpdated) {
  13345. return false;
  13346. }
  13347. if (this.infiniteDistance) {
  13348. return false;
  13349. }
  13350. if (!this._cache.position.equals(this.position))
  13351. return false;
  13352. if (this.rotationQuaternion) {
  13353. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13354. return false;
  13355. }
  13356. if (!this._cache.rotation.equals(this.rotation))
  13357. return false;
  13358. if (!this._cache.scaling.equals(this.scaling))
  13359. return false;
  13360. return true;
  13361. };
  13362. AbstractMesh.prototype._initCache = function () {
  13363. _super.prototype._initCache.call(this);
  13364. this._cache.localMatrixUpdated = false;
  13365. this._cache.position = BABYLON.Vector3.Zero();
  13366. this._cache.scaling = BABYLON.Vector3.Zero();
  13367. this._cache.rotation = BABYLON.Vector3.Zero();
  13368. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13369. this._cache.billboardMode = -1;
  13370. };
  13371. AbstractMesh.prototype.markAsDirty = function (property) {
  13372. if (property === "rotation") {
  13373. this.rotationQuaternion = null;
  13374. }
  13375. this._currentRenderId = Number.MAX_VALUE;
  13376. this._isDirty = true;
  13377. return this;
  13378. };
  13379. /**
  13380. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13381. */
  13382. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13383. this.computeWorldMatrix(true);
  13384. var min;
  13385. var max;
  13386. if (!this.subMeshes) {
  13387. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13388. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13389. }
  13390. else {
  13391. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13392. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13393. }
  13394. var descendants = this.getDescendants(false);
  13395. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13396. var descendant = descendants_1[_i];
  13397. var childMesh = descendant;
  13398. childMesh.computeWorldMatrix(true);
  13399. if (childMesh.getTotalVertices() === 0) {
  13400. continue;
  13401. }
  13402. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13403. var minBox = boundingBox.minimumWorld;
  13404. var maxBox = boundingBox.maximumWorld;
  13405. BABYLON.Tools.CheckExtends(minBox, min, max);
  13406. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13407. }
  13408. return {
  13409. min: min,
  13410. max: max
  13411. };
  13412. };
  13413. /**
  13414. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13415. * Returns the AbstractMesh.
  13416. */
  13417. AbstractMesh.prototype._updateBoundingInfo = function () {
  13418. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13419. this._boundingInfo.update(this.worldMatrixFromCache);
  13420. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13421. return this;
  13422. };
  13423. /**
  13424. * Update a mesh's children BoundingInfo objects only.
  13425. * Returns the AbstractMesh.
  13426. */
  13427. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13428. if (!this.subMeshes) {
  13429. return;
  13430. }
  13431. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13432. var subMesh = this.subMeshes[subIndex];
  13433. if (!subMesh.IsGlobal) {
  13434. subMesh.updateBoundingInfo(matrix);
  13435. }
  13436. }
  13437. return this;
  13438. };
  13439. /**
  13440. * Computes the mesh World matrix and returns it.
  13441. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13442. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13443. * If the parameter `force`is set to `true`, the actual computation is done.
  13444. * Returns the mesh World Matrix.
  13445. */
  13446. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13447. if (this._isWorldMatrixFrozen) {
  13448. return this._worldMatrix;
  13449. }
  13450. if (!force && this.isSynchronized(true)) {
  13451. this._currentRenderId = this.getScene().getRenderId();
  13452. return this._worldMatrix;
  13453. }
  13454. this._cache.position.copyFrom(this.position);
  13455. this._cache.scaling.copyFrom(this.scaling);
  13456. this._cache.pivotMatrixUpdated = false;
  13457. this._cache.billboardMode = this.billboardMode;
  13458. this._currentRenderId = this.getScene().getRenderId();
  13459. this._isDirty = false;
  13460. // Scaling
  13461. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13462. // Rotation
  13463. //rotate, if quaternion is set and rotation was used
  13464. if (this.rotationQuaternion) {
  13465. var len = this.rotation.length();
  13466. if (len) {
  13467. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13468. this.rotation.copyFromFloats(0, 0, 0);
  13469. }
  13470. }
  13471. if (this.rotationQuaternion) {
  13472. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13473. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13474. }
  13475. else {
  13476. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13477. this._cache.rotation.copyFrom(this.rotation);
  13478. }
  13479. // Translation
  13480. if (this.infiniteDistance && !this.parent) {
  13481. var camera = this.getScene().activeCamera;
  13482. if (camera) {
  13483. var cameraWorldMatrix = camera.getWorldMatrix();
  13484. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13485. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13486. }
  13487. }
  13488. else {
  13489. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13490. }
  13491. // Composing transformations
  13492. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13493. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13494. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13495. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13496. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13497. // Need to decompose each rotation here
  13498. var currentPosition = BABYLON.Tmp.Vector3[3];
  13499. if (this.parent && this.parent.getWorldMatrix) {
  13500. if (this._meshToBoneReferal) {
  13501. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13502. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13503. }
  13504. else {
  13505. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13506. }
  13507. }
  13508. else {
  13509. currentPosition.copyFrom(this.position);
  13510. }
  13511. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13512. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13513. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13514. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13515. }
  13516. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13517. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13518. }
  13519. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13520. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13521. }
  13522. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13523. }
  13524. else {
  13525. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13526. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13527. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13528. }
  13529. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13530. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13531. }
  13532. // Local world
  13533. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13534. // Parent
  13535. if (this.parent && this.parent.getWorldMatrix) {
  13536. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13537. if (this._meshToBoneReferal) {
  13538. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13539. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13540. }
  13541. else {
  13542. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13543. }
  13544. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13545. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13546. this._worldMatrix.copyFrom(this._localWorld);
  13547. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13548. }
  13549. else {
  13550. if (this._meshToBoneReferal) {
  13551. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13552. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13553. }
  13554. else {
  13555. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13556. }
  13557. }
  13558. this._markSyncedWithParent();
  13559. }
  13560. else {
  13561. this._worldMatrix.copyFrom(this._localWorld);
  13562. }
  13563. // Post multiply inverse of pivotMatrix
  13564. if (this._postMultiplyPivotMatrix) {
  13565. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13566. }
  13567. // Bounding info
  13568. this._updateBoundingInfo();
  13569. // Absolute position
  13570. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13571. // Callbacks
  13572. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13573. if (!this._poseMatrix) {
  13574. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13575. }
  13576. return this._worldMatrix;
  13577. };
  13578. /**
  13579. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13580. * @param func: callback function to add
  13581. *
  13582. * Returns the AbstractMesh.
  13583. */
  13584. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13585. this.onAfterWorldMatrixUpdateObservable.add(func);
  13586. return this;
  13587. };
  13588. /**
  13589. * Removes a registered callback function.
  13590. * Returns the AbstractMesh.
  13591. */
  13592. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13593. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13594. return this;
  13595. };
  13596. /**
  13597. * Sets the mesh position in its local space.
  13598. * Returns the AbstractMesh.
  13599. */
  13600. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13601. this.computeWorldMatrix();
  13602. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13603. return this;
  13604. };
  13605. /**
  13606. * Returns the mesh position in the local space from the current World matrix values.
  13607. * Returns a new Vector3.
  13608. */
  13609. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13610. this.computeWorldMatrix();
  13611. var invLocalWorldMatrix = this._localWorld.clone();
  13612. invLocalWorldMatrix.invert();
  13613. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13614. };
  13615. /**
  13616. * Translates the mesh along the passed Vector3 in its local space.
  13617. * Returns the AbstractMesh.
  13618. */
  13619. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13620. this.computeWorldMatrix(true);
  13621. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13622. return this;
  13623. };
  13624. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13625. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13626. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13627. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13628. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13629. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13630. /// <returns>Mesh oriented towards targetMesh</returns>
  13631. if (yawCor === void 0) { yawCor = 0; }
  13632. if (pitchCor === void 0) { pitchCor = 0; }
  13633. if (rollCor === void 0) { rollCor = 0; }
  13634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13635. var dv = AbstractMesh._lookAtVectorCache;
  13636. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13637. targetPoint.subtractToRef(pos, dv);
  13638. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13639. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13640. var pitch = Math.atan2(dv.y, len);
  13641. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13642. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13643. return this;
  13644. };
  13645. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13646. this._meshToBoneReferal = affectedMesh;
  13647. this.parent = bone;
  13648. if (bone.getWorldMatrix().determinant() < 0) {
  13649. this.scalingDeterminant *= -1;
  13650. }
  13651. return this;
  13652. };
  13653. AbstractMesh.prototype.detachFromBone = function () {
  13654. if (this.parent.getWorldMatrix().determinant() < 0) {
  13655. this.scalingDeterminant *= -1;
  13656. }
  13657. this._meshToBoneReferal = null;
  13658. this.parent = null;
  13659. return this;
  13660. };
  13661. /**
  13662. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13663. * A mesh is in the frustum if its bounding box intersects the frustum.
  13664. * Boolean returned.
  13665. */
  13666. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13667. return this._boundingInfo.isInFrustum(frustumPlanes);
  13668. };
  13669. /**
  13670. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13671. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13672. * Boolean returned.
  13673. */
  13674. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13675. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13676. ;
  13677. };
  13678. /**
  13679. * True if the mesh intersects another mesh or a SolidParticle object.
  13680. * 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)
  13681. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  13682. * Returns a boolean.
  13683. */
  13684. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  13685. if (!this._boundingInfo || !mesh._boundingInfo) {
  13686. return false;
  13687. }
  13688. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  13689. return true;
  13690. }
  13691. if (includeDescendants) {
  13692. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  13693. var child = _a[_i];
  13694. if (child.intersectsMesh(mesh, precise, true)) {
  13695. return true;
  13696. }
  13697. }
  13698. }
  13699. return false;
  13700. };
  13701. /**
  13702. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13703. * Returns a boolean.
  13704. */
  13705. AbstractMesh.prototype.intersectsPoint = function (point) {
  13706. if (!this._boundingInfo) {
  13707. return false;
  13708. }
  13709. return this._boundingInfo.intersectsPoint(point);
  13710. };
  13711. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13712. return this.physicsImpostor;
  13713. };
  13714. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13715. if (!camera) {
  13716. camera = this.getScene().activeCamera;
  13717. }
  13718. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13719. };
  13720. /**
  13721. * Returns the distance from the mesh to the active camera.
  13722. * Returns a float.
  13723. */
  13724. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13725. if (!camera) {
  13726. camera = this.getScene().activeCamera;
  13727. }
  13728. return this.absolutePosition.subtract(camera.position).length();
  13729. };
  13730. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13731. if (!this.physicsImpostor) {
  13732. return;
  13733. }
  13734. this.physicsImpostor.applyImpulse(force, contactPoint);
  13735. return this;
  13736. };
  13737. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13738. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13739. return;
  13740. }
  13741. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13742. mainPivot: pivot1,
  13743. connectedPivot: pivot2,
  13744. nativeParams: options
  13745. });
  13746. return this;
  13747. };
  13748. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13749. // Collisions
  13750. /**
  13751. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13752. * Default `false`.
  13753. */
  13754. get: function () {
  13755. return this._checkCollisions;
  13756. },
  13757. set: function (collisionEnabled) {
  13758. this._checkCollisions = collisionEnabled;
  13759. if (this.getScene().workerCollisions) {
  13760. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13761. }
  13762. },
  13763. enumerable: true,
  13764. configurable: true
  13765. });
  13766. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13767. var globalPosition = this.getAbsolutePosition();
  13768. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13769. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13770. if (!this._collider) {
  13771. this._collider = new BABYLON.Collider();
  13772. }
  13773. this._collider.radius = this.ellipsoid;
  13774. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13775. return this;
  13776. };
  13777. // Submeshes octree
  13778. /**
  13779. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13780. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13781. * Returns an Octree of submeshes.
  13782. */
  13783. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13784. if (maxCapacity === void 0) { maxCapacity = 64; }
  13785. if (maxDepth === void 0) { maxDepth = 2; }
  13786. if (!this._submeshesOctree) {
  13787. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13788. }
  13789. this.computeWorldMatrix(true);
  13790. // Update octree
  13791. var bbox = this.getBoundingInfo().boundingBox;
  13792. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13793. return this._submeshesOctree;
  13794. };
  13795. // Collisions
  13796. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13797. this._generatePointsArray();
  13798. // Transformation
  13799. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13800. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13801. subMesh._lastColliderWorldVertices = [];
  13802. subMesh._trianglePlanes = [];
  13803. var start = subMesh.verticesStart;
  13804. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13805. for (var i = start; i < end; i++) {
  13806. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13807. }
  13808. }
  13809. // Collide
  13810. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13811. if (collider.collisionFound) {
  13812. collider.collidedMesh = this;
  13813. }
  13814. return this;
  13815. };
  13816. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13817. var subMeshes;
  13818. var len;
  13819. // Octrees
  13820. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13821. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13822. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13823. len = intersections.length;
  13824. subMeshes = intersections.data;
  13825. }
  13826. else {
  13827. subMeshes = this.subMeshes;
  13828. len = subMeshes.length;
  13829. }
  13830. for (var index = 0; index < len; index++) {
  13831. var subMesh = subMeshes[index];
  13832. // Bounding test
  13833. if (len > 1 && !subMesh._checkCollision(collider))
  13834. continue;
  13835. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13836. }
  13837. return this;
  13838. };
  13839. AbstractMesh.prototype._checkCollision = function (collider) {
  13840. // Bounding box test
  13841. if (!this._boundingInfo._checkCollision(collider))
  13842. return this;
  13843. // Transformation matrix
  13844. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13845. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13846. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13847. return this;
  13848. };
  13849. // Picking
  13850. AbstractMesh.prototype._generatePointsArray = function () {
  13851. return false;
  13852. };
  13853. /**
  13854. * Checks if the passed Ray intersects with the mesh.
  13855. * Returns an object PickingInfo.
  13856. */
  13857. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13858. var pickingInfo = new BABYLON.PickingInfo();
  13859. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13860. return pickingInfo;
  13861. }
  13862. if (!this._generatePointsArray()) {
  13863. return pickingInfo;
  13864. }
  13865. var intersectInfo = null;
  13866. // Octrees
  13867. var subMeshes;
  13868. var len;
  13869. if (this._submeshesOctree && this.useOctreeForPicking) {
  13870. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13871. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13872. len = intersections.length;
  13873. subMeshes = intersections.data;
  13874. }
  13875. else {
  13876. subMeshes = this.subMeshes;
  13877. len = subMeshes.length;
  13878. }
  13879. for (var index = 0; index < len; index++) {
  13880. var subMesh = subMeshes[index];
  13881. // Bounding test
  13882. if (len > 1 && !subMesh.canIntersects(ray))
  13883. continue;
  13884. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13885. if (currentIntersectInfo) {
  13886. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13887. intersectInfo = currentIntersectInfo;
  13888. intersectInfo.subMeshId = index;
  13889. if (fastCheck) {
  13890. break;
  13891. }
  13892. }
  13893. }
  13894. }
  13895. if (intersectInfo) {
  13896. // Get picked point
  13897. var world = this.getWorldMatrix();
  13898. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13899. var direction = ray.direction.clone();
  13900. direction = direction.scale(intersectInfo.distance);
  13901. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13902. var pickedPoint = worldOrigin.add(worldDirection);
  13903. // Return result
  13904. pickingInfo.hit = true;
  13905. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13906. pickingInfo.pickedPoint = pickedPoint;
  13907. pickingInfo.pickedMesh = this;
  13908. pickingInfo.bu = intersectInfo.bu;
  13909. pickingInfo.bv = intersectInfo.bv;
  13910. pickingInfo.faceId = intersectInfo.faceId;
  13911. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13912. return pickingInfo;
  13913. }
  13914. return pickingInfo;
  13915. };
  13916. /**
  13917. * Clones the mesh, used by the class Mesh.
  13918. * Just returns `null` for an AbstractMesh.
  13919. */
  13920. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13921. return null;
  13922. };
  13923. /**
  13924. * Disposes all the mesh submeshes.
  13925. * Returns the AbstractMesh.
  13926. */
  13927. AbstractMesh.prototype.releaseSubMeshes = function () {
  13928. if (this.subMeshes) {
  13929. while (this.subMeshes.length) {
  13930. this.subMeshes[0].dispose();
  13931. }
  13932. }
  13933. else {
  13934. this.subMeshes = new Array();
  13935. }
  13936. return this;
  13937. };
  13938. /**
  13939. * Disposes the AbstractMesh.
  13940. * Some internal references are kept for further use.
  13941. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13942. * Returns nothing.
  13943. */
  13944. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13945. var _this = this;
  13946. var index;
  13947. // Action manager
  13948. if (this.actionManager) {
  13949. this.actionManager.dispose();
  13950. this.actionManager = null;
  13951. }
  13952. // Skeleton
  13953. this.skeleton = null;
  13954. // Animations
  13955. this.getScene().stopAnimation(this);
  13956. // Physics
  13957. if (this.physicsImpostor) {
  13958. this.physicsImpostor.dispose();
  13959. }
  13960. // Intersections in progress
  13961. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13962. var other = this._intersectionsInProgress[index];
  13963. var pos = other._intersectionsInProgress.indexOf(this);
  13964. other._intersectionsInProgress.splice(pos, 1);
  13965. }
  13966. this._intersectionsInProgress = [];
  13967. // Lights
  13968. var lights = this.getScene().lights;
  13969. lights.forEach(function (light) {
  13970. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13971. if (meshIndex !== -1) {
  13972. light.includedOnlyMeshes.splice(meshIndex, 1);
  13973. }
  13974. meshIndex = light.excludedMeshes.indexOf(_this);
  13975. if (meshIndex !== -1) {
  13976. light.excludedMeshes.splice(meshIndex, 1);
  13977. }
  13978. // Shadow generators
  13979. var generator = light.getShadowGenerator();
  13980. if (generator) {
  13981. var shadowMap = generator.getShadowMap();
  13982. meshIndex = shadowMap.renderList.indexOf(_this);
  13983. if (meshIndex !== -1) {
  13984. shadowMap.renderList.splice(meshIndex, 1);
  13985. }
  13986. }
  13987. });
  13988. // Edges
  13989. if (this._edgesRenderer) {
  13990. this._edgesRenderer.dispose();
  13991. this._edgesRenderer = null;
  13992. }
  13993. // SubMeshes
  13994. if (this.getClassName() !== "InstancedMesh") {
  13995. this.releaseSubMeshes();
  13996. }
  13997. // Octree
  13998. var sceneOctree = this.getScene().selectionOctree;
  13999. if (sceneOctree) {
  14000. var index = sceneOctree.dynamicContent.indexOf(this);
  14001. if (index !== -1) {
  14002. sceneOctree.dynamicContent.splice(index, 1);
  14003. }
  14004. }
  14005. // Query
  14006. var engine = this.getScene().getEngine();
  14007. if (this._occlusionQuery) {
  14008. this._isOcclusionQueryInProgress = false;
  14009. engine.deleteQuery(this._occlusionQuery);
  14010. this._occlusionQuery = null;
  14011. }
  14012. // Engine
  14013. engine.wipeCaches();
  14014. // Remove from scene
  14015. this.getScene().removeMesh(this);
  14016. if (!doNotRecurse) {
  14017. // Particles
  14018. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14019. if (this.getScene().particleSystems[index].emitter === this) {
  14020. this.getScene().particleSystems[index].dispose();
  14021. index--;
  14022. }
  14023. }
  14024. // Children
  14025. var objects = this.getDescendants(true);
  14026. for (index = 0; index < objects.length; index++) {
  14027. objects[index].dispose();
  14028. }
  14029. }
  14030. else {
  14031. var childMeshes = this.getChildMeshes(true);
  14032. for (index = 0; index < childMeshes.length; index++) {
  14033. var child = childMeshes[index];
  14034. child.parent = null;
  14035. child.computeWorldMatrix(true);
  14036. }
  14037. }
  14038. // facet data
  14039. if (this._facetDataEnabled) {
  14040. this.disableFacetData();
  14041. }
  14042. this.onAfterWorldMatrixUpdateObservable.clear();
  14043. this.onCollideObservable.clear();
  14044. this.onCollisionPositionChangeObservable.clear();
  14045. this._isDisposed = true;
  14046. _super.prototype.dispose.call(this);
  14047. };
  14048. /**
  14049. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14050. * This Vector3 is expressed in the World space.
  14051. */
  14052. AbstractMesh.prototype.getDirection = function (localAxis) {
  14053. var result = BABYLON.Vector3.Zero();
  14054. this.getDirectionToRef(localAxis, result);
  14055. return result;
  14056. };
  14057. /**
  14058. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14059. * localAxis is expressed in the mesh local space.
  14060. * result is computed in the Wordl space from the mesh World matrix.
  14061. * Returns the AbstractMesh.
  14062. */
  14063. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14064. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14065. return this;
  14066. };
  14067. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14069. if (this.getScene().getRenderId() == 0) {
  14070. this.computeWorldMatrix(true);
  14071. }
  14072. var wm = this.getWorldMatrix();
  14073. if (space == BABYLON.Space.WORLD) {
  14074. var tmat = BABYLON.Tmp.Matrix[0];
  14075. wm.invertToRef(tmat);
  14076. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14077. }
  14078. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14079. this._pivotMatrix.m[12] = -point.x;
  14080. this._pivotMatrix.m[13] = -point.y;
  14081. this._pivotMatrix.m[14] = -point.z;
  14082. this._cache.pivotMatrixUpdated = true;
  14083. return this;
  14084. };
  14085. /**
  14086. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14087. */
  14088. AbstractMesh.prototype.getPivotPoint = function () {
  14089. var point = BABYLON.Vector3.Zero();
  14090. this.getPivotPointToRef(point);
  14091. return point;
  14092. };
  14093. /**
  14094. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14095. * Returns the AbstractMesh.
  14096. */
  14097. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14098. result.x = -this._pivotMatrix.m[12];
  14099. result.y = -this._pivotMatrix.m[13];
  14100. result.z = -this._pivotMatrix.m[14];
  14101. return this;
  14102. };
  14103. /**
  14104. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14105. */
  14106. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14107. var point = BABYLON.Vector3.Zero();
  14108. this.getAbsolutePivotPointToRef(point);
  14109. return point;
  14110. };
  14111. /**
  14112. * Defines the passed mesh as the parent of the current mesh.
  14113. * Returns the AbstractMesh.
  14114. */
  14115. AbstractMesh.prototype.setParent = function (mesh) {
  14116. var child = this;
  14117. var parent = mesh;
  14118. if (mesh == null) {
  14119. var rotation = BABYLON.Tmp.Quaternion[0];
  14120. var position = BABYLON.Tmp.Vector3[0];
  14121. var scale = BABYLON.Tmp.Vector3[1];
  14122. child.getWorldMatrix().decompose(scale, rotation, position);
  14123. if (child.rotationQuaternion) {
  14124. child.rotationQuaternion.copyFrom(rotation);
  14125. }
  14126. else {
  14127. rotation.toEulerAnglesToRef(child.rotation);
  14128. }
  14129. child.position.x = position.x;
  14130. child.position.y = position.y;
  14131. child.position.z = position.z;
  14132. }
  14133. else {
  14134. var position = BABYLON.Tmp.Vector3[0];
  14135. var m1 = BABYLON.Tmp.Matrix[0];
  14136. parent.getWorldMatrix().invertToRef(m1);
  14137. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14138. child.position.copyFrom(position);
  14139. }
  14140. child.parent = parent;
  14141. return this;
  14142. };
  14143. /**
  14144. * Adds the passed mesh as a child to the current mesh.
  14145. * Returns the AbstractMesh.
  14146. */
  14147. AbstractMesh.prototype.addChild = function (mesh) {
  14148. mesh.setParent(this);
  14149. return this;
  14150. };
  14151. /**
  14152. * Removes the passed mesh from the current mesh children list.
  14153. * Returns the AbstractMesh.
  14154. */
  14155. AbstractMesh.prototype.removeChild = function (mesh) {
  14156. mesh.setParent(null);
  14157. return this;
  14158. };
  14159. /**
  14160. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14161. * Returns the AbstractMesh.
  14162. */
  14163. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14164. result.x = this._pivotMatrix.m[12];
  14165. result.y = this._pivotMatrix.m[13];
  14166. result.z = this._pivotMatrix.m[14];
  14167. this.getPivotPointToRef(result);
  14168. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14169. return this;
  14170. };
  14171. // Facet data
  14172. /**
  14173. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14174. * Returns the AbstractMesh.
  14175. */
  14176. AbstractMesh.prototype._initFacetData = function () {
  14177. if (!this._facetNormals) {
  14178. this._facetNormals = new Array();
  14179. }
  14180. if (!this._facetPositions) {
  14181. this._facetPositions = new Array();
  14182. }
  14183. if (!this._facetPartitioning) {
  14184. this._facetPartitioning = new Array();
  14185. }
  14186. this._facetNb = this.getIndices().length / 3;
  14187. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14188. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14189. for (var f = 0; f < this._facetNb; f++) {
  14190. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14191. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14192. }
  14193. this._facetDataEnabled = true;
  14194. return this;
  14195. };
  14196. /**
  14197. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14198. * This method can be called within the render loop.
  14199. * 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.
  14200. * Returns the AbstractMesh.
  14201. */
  14202. AbstractMesh.prototype.updateFacetData = function () {
  14203. if (!this._facetDataEnabled) {
  14204. this._initFacetData();
  14205. }
  14206. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14207. var indices = this.getIndices();
  14208. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14209. var bInfo = this.getBoundingInfo();
  14210. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14211. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14212. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14213. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14214. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14215. this._subDiv.max = this._partitioningSubdivisions;
  14216. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14217. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14218. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14219. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14220. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14221. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14222. // set the parameters for ComputeNormals()
  14223. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14224. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14225. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14226. this._facetParameters.bInfo = bInfo;
  14227. this._facetParameters.bbSize = this._bbSize;
  14228. this._facetParameters.subDiv = this._subDiv;
  14229. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14230. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14231. return this;
  14232. };
  14233. /**
  14234. * Returns the facetLocalNormals array.
  14235. * The normals are expressed in the mesh local space.
  14236. */
  14237. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14238. if (!this._facetNormals) {
  14239. this.updateFacetData();
  14240. }
  14241. return this._facetNormals;
  14242. };
  14243. /**
  14244. * Returns the facetLocalPositions array.
  14245. * The facet positions are expressed in the mesh local space.
  14246. */
  14247. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14248. if (!this._facetPositions) {
  14249. this.updateFacetData();
  14250. }
  14251. return this._facetPositions;
  14252. };
  14253. /**
  14254. * Returns the facetLocalPartioning array.
  14255. */
  14256. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14257. if (!this._facetPartitioning) {
  14258. this.updateFacetData();
  14259. }
  14260. return this._facetPartitioning;
  14261. };
  14262. /**
  14263. * Returns the i-th facet position in the world system.
  14264. * This method allocates a new Vector3 per call.
  14265. */
  14266. AbstractMesh.prototype.getFacetPosition = function (i) {
  14267. var pos = BABYLON.Vector3.Zero();
  14268. this.getFacetPositionToRef(i, pos);
  14269. return pos;
  14270. };
  14271. /**
  14272. * Sets the reference Vector3 with the i-th facet position in the world system.
  14273. * Returns the AbstractMesh.
  14274. */
  14275. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14276. var localPos = (this.getFacetLocalPositions())[i];
  14277. var world = this.getWorldMatrix();
  14278. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14279. return this;
  14280. };
  14281. /**
  14282. * Returns the i-th facet normal in the world system.
  14283. * This method allocates a new Vector3 per call.
  14284. */
  14285. AbstractMesh.prototype.getFacetNormal = function (i) {
  14286. var norm = BABYLON.Vector3.Zero();
  14287. this.getFacetNormalToRef(i, norm);
  14288. return norm;
  14289. };
  14290. /**
  14291. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14292. * Returns the AbstractMesh.
  14293. */
  14294. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14295. var localNorm = (this.getFacetLocalNormals())[i];
  14296. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14297. return this;
  14298. };
  14299. /**
  14300. * 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).
  14301. */
  14302. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14303. var bInfo = this.getBoundingInfo();
  14304. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14305. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14306. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14307. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14308. return null;
  14309. }
  14310. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14311. };
  14312. /**
  14313. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14314. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14315. * 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.
  14316. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14317. * 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.
  14318. */
  14319. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14320. if (checkFace === void 0) { checkFace = false; }
  14321. if (facing === void 0) { facing = true; }
  14322. var world = this.getWorldMatrix();
  14323. var invMat = BABYLON.Tmp.Matrix[5];
  14324. world.invertToRef(invMat);
  14325. var invVect = BABYLON.Tmp.Vector3[8];
  14326. var closest = null;
  14327. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14328. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14329. if (projected) {
  14330. // tranform the local computed projected vector to world coordinates
  14331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14332. }
  14333. return closest;
  14334. };
  14335. /**
  14336. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14337. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14338. * 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.
  14339. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14340. * 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.
  14341. */
  14342. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14343. if (checkFace === void 0) { checkFace = false; }
  14344. if (facing === void 0) { facing = true; }
  14345. var closest = null;
  14346. var tmpx = 0.0;
  14347. var tmpy = 0.0;
  14348. var tmpz = 0.0;
  14349. var d = 0.0; // tmp dot facet normal * facet position
  14350. var t0 = 0.0;
  14351. var projx = 0.0;
  14352. var projy = 0.0;
  14353. var projz = 0.0;
  14354. // Get all the facets in the same partitioning block than (x, y, z)
  14355. var facetPositions = this.getFacetLocalPositions();
  14356. var facetNormals = this.getFacetLocalNormals();
  14357. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14358. if (!facetsInBlock) {
  14359. return null;
  14360. }
  14361. // Get the closest facet to (x, y, z)
  14362. var shortest = Number.MAX_VALUE; // init distance vars
  14363. var tmpDistance = shortest;
  14364. var fib; // current facet in the block
  14365. var norm; // current facet normal
  14366. var p0; // current facet barycenter position
  14367. // loop on all the facets in the current partitioning block
  14368. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14369. fib = facetsInBlock[idx];
  14370. norm = facetNormals[fib];
  14371. p0 = facetPositions[fib];
  14372. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14373. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14374. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14375. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14376. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14377. projx = x + norm.x * t0;
  14378. projy = y + norm.y * t0;
  14379. projz = z + norm.z * t0;
  14380. tmpx = projx - x;
  14381. tmpy = projy - y;
  14382. tmpz = projz - z;
  14383. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14384. if (tmpDistance < shortest) {
  14385. shortest = tmpDistance;
  14386. closest = fib;
  14387. if (projected) {
  14388. projected.x = projx;
  14389. projected.y = projy;
  14390. projected.z = projz;
  14391. }
  14392. }
  14393. }
  14394. }
  14395. return closest;
  14396. };
  14397. /**
  14398. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14399. */
  14400. AbstractMesh.prototype.getFacetDataParameters = function () {
  14401. return this._facetParameters;
  14402. };
  14403. /**
  14404. * Disables the feature FacetData and frees the related memory.
  14405. * Returns the AbstractMesh.
  14406. */
  14407. AbstractMesh.prototype.disableFacetData = function () {
  14408. if (this._facetDataEnabled) {
  14409. this._facetDataEnabled = false;
  14410. this._facetPositions = null;
  14411. this._facetNormals = null;
  14412. this._facetPartitioning = null;
  14413. this._facetParameters = null;
  14414. }
  14415. return this;
  14416. };
  14417. /**
  14418. * Creates new normals data for the mesh.
  14419. * @param updatable.
  14420. */
  14421. AbstractMesh.prototype.createNormals = function (updatable) {
  14422. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14423. var indices = this.getIndices();
  14424. var normals;
  14425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14426. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14427. }
  14428. else {
  14429. normals = [];
  14430. }
  14431. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14432. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14433. };
  14434. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14435. var engine = this.getEngine();
  14436. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14437. this._isOccluded = false;
  14438. return;
  14439. }
  14440. if (this.isOcclusionQueryInProgress) {
  14441. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14442. if (isOcclusionQueryAvailable) {
  14443. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14444. this._isOcclusionQueryInProgress = false;
  14445. this._occlusionInternalRetryCounter = 0;
  14446. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14447. }
  14448. else {
  14449. this._occlusionInternalRetryCounter++;
  14450. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14451. this._isOcclusionQueryInProgress = false;
  14452. this._occlusionInternalRetryCounter = 0;
  14453. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14454. // if strict continue the last state of the object.
  14455. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14456. }
  14457. else {
  14458. return;
  14459. }
  14460. }
  14461. }
  14462. var scene = this.getScene();
  14463. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14464. if (!this._occlusionQuery) {
  14465. this._occlusionQuery = engine.createQuery();
  14466. }
  14467. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14468. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14469. engine.endQuery(this.occlusionQueryAlgorithmType);
  14470. this._isOcclusionQueryInProgress = true;
  14471. };
  14472. // Statics
  14473. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14474. AbstractMesh._BILLBOARDMODE_X = 1;
  14475. AbstractMesh._BILLBOARDMODE_Y = 2;
  14476. AbstractMesh._BILLBOARDMODE_Z = 4;
  14477. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14478. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14479. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14480. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14481. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14482. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14483. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14484. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14485. return AbstractMesh;
  14486. }(BABYLON.Node));
  14487. BABYLON.AbstractMesh = AbstractMesh;
  14488. })(BABYLON || (BABYLON = {}));
  14489. //# sourceMappingURL=babylon.abstractMesh.js.map
  14490. var BABYLON;
  14491. (function (BABYLON) {
  14492. var Light = (function (_super) {
  14493. __extends(Light, _super);
  14494. /**
  14495. * Creates a Light object in the scene.
  14496. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14497. */
  14498. function Light(name, scene) {
  14499. var _this = _super.call(this, name, scene) || this;
  14500. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14501. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14502. _this.intensity = 1.0;
  14503. _this.range = Number.MAX_VALUE;
  14504. /**
  14505. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14506. * of light.
  14507. */
  14508. _this._photometricScale = 1.0;
  14509. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14510. _this._radius = 0.00001;
  14511. _this.renderPriority = 0;
  14512. /**
  14513. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14514. * the current shadow generator.
  14515. */
  14516. _this.shadowEnabled = true;
  14517. _this._excludeWithLayerMask = 0;
  14518. _this._includeOnlyWithLayerMask = 0;
  14519. _this._lightmapMode = 0;
  14520. _this._excludedMeshesIds = new Array();
  14521. _this._includedOnlyMeshesIds = new Array();
  14522. _this.getScene().addLight(_this);
  14523. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14524. _this._buildUniformLayout();
  14525. _this.includedOnlyMeshes = new Array();
  14526. _this.excludedMeshes = new Array();
  14527. _this._resyncMeshes();
  14528. return _this;
  14529. }
  14530. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14531. /**
  14532. * If every light affecting the material is in this lightmapMode,
  14533. * material.lightmapTexture adds or multiplies
  14534. * (depends on material.useLightmapAsShadowmap)
  14535. * after every other light calculations.
  14536. */
  14537. get: function () {
  14538. return Light._LIGHTMAP_DEFAULT;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14544. /**
  14545. * material.lightmapTexture as only diffuse lighting from this light
  14546. * adds pnly specular lighting from this light
  14547. * adds dynamic shadows
  14548. */
  14549. get: function () {
  14550. return Light._LIGHTMAP_SPECULAR;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14556. /**
  14557. * material.lightmapTexture as only lighting
  14558. * no light calculation from this light
  14559. * only adds dynamic shadows from this light
  14560. */
  14561. get: function () {
  14562. return Light._LIGHTMAP_SHADOWSONLY;
  14563. },
  14564. enumerable: true,
  14565. configurable: true
  14566. });
  14567. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14568. /**
  14569. * Each light type uses the default quantity according to its type:
  14570. * point/spot lights use luminous intensity
  14571. * directional lights use illuminance
  14572. */
  14573. get: function () {
  14574. return Light._INTENSITYMODE_AUTOMATIC;
  14575. },
  14576. enumerable: true,
  14577. configurable: true
  14578. });
  14579. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14580. /**
  14581. * lumen (lm)
  14582. */
  14583. get: function () {
  14584. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14585. },
  14586. enumerable: true,
  14587. configurable: true
  14588. });
  14589. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14590. /**
  14591. * candela (lm/sr)
  14592. */
  14593. get: function () {
  14594. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14595. },
  14596. enumerable: true,
  14597. configurable: true
  14598. });
  14599. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14600. /**
  14601. * lux (lm/m^2)
  14602. */
  14603. get: function () {
  14604. return Light._INTENSITYMODE_ILLUMINANCE;
  14605. },
  14606. enumerable: true,
  14607. configurable: true
  14608. });
  14609. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14610. /**
  14611. * nit (cd/m^2)
  14612. */
  14613. get: function () {
  14614. return Light._INTENSITYMODE_LUMINANCE;
  14615. },
  14616. enumerable: true,
  14617. configurable: true
  14618. });
  14619. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14620. /**
  14621. * Light type const id of the point light.
  14622. */
  14623. get: function () {
  14624. return Light._LIGHTTYPEID_POINTLIGHT;
  14625. },
  14626. enumerable: true,
  14627. configurable: true
  14628. });
  14629. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14630. /**
  14631. * Light type const id of the directional light.
  14632. */
  14633. get: function () {
  14634. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14635. },
  14636. enumerable: true,
  14637. configurable: true
  14638. });
  14639. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14640. /**
  14641. * Light type const id of the spot light.
  14642. */
  14643. get: function () {
  14644. return Light._LIGHTTYPEID_SPOTLIGHT;
  14645. },
  14646. enumerable: true,
  14647. configurable: true
  14648. });
  14649. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14650. /**
  14651. * Light type const id of the hemispheric light.
  14652. */
  14653. get: function () {
  14654. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14655. },
  14656. enumerable: true,
  14657. configurable: true
  14658. });
  14659. Object.defineProperty(Light.prototype, "intensityMode", {
  14660. /**
  14661. * Gets the photometric scale used to interpret the intensity.
  14662. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14663. */
  14664. get: function () {
  14665. return this._intensityMode;
  14666. },
  14667. /**
  14668. * Sets the photometric scale used to interpret the intensity.
  14669. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14670. */
  14671. set: function (value) {
  14672. this._intensityMode = value;
  14673. this._computePhotometricScale();
  14674. },
  14675. enumerable: true,
  14676. configurable: true
  14677. });
  14678. ;
  14679. ;
  14680. Object.defineProperty(Light.prototype, "radius", {
  14681. /**
  14682. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14683. */
  14684. get: function () {
  14685. return this._radius;
  14686. },
  14687. /**
  14688. * sets the light radius used by PBR Materials to simulate soft area lights.
  14689. */
  14690. set: function (value) {
  14691. this._radius = value;
  14692. this._computePhotometricScale();
  14693. },
  14694. enumerable: true,
  14695. configurable: true
  14696. });
  14697. ;
  14698. ;
  14699. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14700. get: function () {
  14701. return this._includedOnlyMeshes;
  14702. },
  14703. set: function (value) {
  14704. this._includedOnlyMeshes = value;
  14705. this._hookArrayForIncludedOnly(value);
  14706. },
  14707. enumerable: true,
  14708. configurable: true
  14709. });
  14710. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14711. get: function () {
  14712. return this._excludedMeshes;
  14713. },
  14714. set: function (value) {
  14715. this._excludedMeshes = value;
  14716. this._hookArrayForExcluded(value);
  14717. },
  14718. enumerable: true,
  14719. configurable: true
  14720. });
  14721. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14722. get: function () {
  14723. return this._excludeWithLayerMask;
  14724. },
  14725. set: function (value) {
  14726. this._excludeWithLayerMask = value;
  14727. this._resyncMeshes();
  14728. },
  14729. enumerable: true,
  14730. configurable: true
  14731. });
  14732. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14733. get: function () {
  14734. return this._includeOnlyWithLayerMask;
  14735. },
  14736. set: function (value) {
  14737. this._includeOnlyWithLayerMask = value;
  14738. this._resyncMeshes();
  14739. },
  14740. enumerable: true,
  14741. configurable: true
  14742. });
  14743. Object.defineProperty(Light.prototype, "lightmapMode", {
  14744. get: function () {
  14745. return this._lightmapMode;
  14746. },
  14747. set: function (value) {
  14748. if (this._lightmapMode === value) {
  14749. return;
  14750. }
  14751. this._lightmapMode = value;
  14752. this._markMeshesAsLightDirty();
  14753. },
  14754. enumerable: true,
  14755. configurable: true
  14756. });
  14757. Light.prototype._buildUniformLayout = function () {
  14758. // Overridden
  14759. };
  14760. /**
  14761. * Returns the string "Light".
  14762. */
  14763. Light.prototype.getClassName = function () {
  14764. return "Light";
  14765. };
  14766. /**
  14767. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14768. */
  14769. Light.prototype.toString = function (fullDetails) {
  14770. var ret = "Name: " + this.name;
  14771. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14772. if (this.animations) {
  14773. for (var i = 0; i < this.animations.length; i++) {
  14774. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14775. }
  14776. }
  14777. if (fullDetails) {
  14778. }
  14779. return ret;
  14780. };
  14781. /**
  14782. * Set the enabled state of this node.
  14783. * @param {boolean} value - the new enabled state
  14784. * @see isEnabled
  14785. */
  14786. Light.prototype.setEnabled = function (value) {
  14787. _super.prototype.setEnabled.call(this, value);
  14788. this._resyncMeshes();
  14789. };
  14790. /**
  14791. * Returns the Light associated shadow generator.
  14792. */
  14793. Light.prototype.getShadowGenerator = function () {
  14794. return this._shadowGenerator;
  14795. };
  14796. /**
  14797. * Returns a Vector3, the absolute light position in the World.
  14798. */
  14799. Light.prototype.getAbsolutePosition = function () {
  14800. return BABYLON.Vector3.Zero();
  14801. };
  14802. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14803. };
  14804. Light.prototype._getWorldMatrix = function () {
  14805. return BABYLON.Matrix.Identity();
  14806. };
  14807. /**
  14808. * Boolean : True if the light will affect the passed mesh.
  14809. */
  14810. Light.prototype.canAffectMesh = function (mesh) {
  14811. if (!mesh) {
  14812. return true;
  14813. }
  14814. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14815. return false;
  14816. }
  14817. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14818. return false;
  14819. }
  14820. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14821. return false;
  14822. }
  14823. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14824. return false;
  14825. }
  14826. return true;
  14827. };
  14828. /**
  14829. * Returns the light World matrix.
  14830. */
  14831. Light.prototype.getWorldMatrix = function () {
  14832. this._currentRenderId = this.getScene().getRenderId();
  14833. var worldMatrix = this._getWorldMatrix();
  14834. if (this.parent && this.parent.getWorldMatrix) {
  14835. if (!this._parentedWorldMatrix) {
  14836. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14837. }
  14838. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14839. this._markSyncedWithParent();
  14840. return this._parentedWorldMatrix;
  14841. }
  14842. return worldMatrix;
  14843. };
  14844. /**
  14845. * Sort function to order lights for rendering.
  14846. * @param a First Light object to compare to second.
  14847. * @param b Second Light object to compare first.
  14848. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14849. */
  14850. Light.compareLightsPriority = function (a, b) {
  14851. //shadow-casting lights have priority over non-shadow-casting lights
  14852. //the renderPrioirty is a secondary sort criterion
  14853. if (a.shadowEnabled !== b.shadowEnabled) {
  14854. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14855. }
  14856. return b.renderPriority - a.renderPriority;
  14857. };
  14858. /**
  14859. * Disposes the light.
  14860. */
  14861. Light.prototype.dispose = function () {
  14862. if (this._shadowGenerator) {
  14863. this._shadowGenerator.dispose();
  14864. this._shadowGenerator = null;
  14865. }
  14866. // Animations
  14867. this.getScene().stopAnimation(this);
  14868. // Remove from meshes
  14869. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14870. var mesh = _a[_i];
  14871. mesh._removeLightSource(this);
  14872. }
  14873. this._uniformBuffer.dispose();
  14874. // Remove from scene
  14875. this.getScene().removeLight(this);
  14876. _super.prototype.dispose.call(this);
  14877. };
  14878. /**
  14879. * Returns the light type ID (integer).
  14880. */
  14881. Light.prototype.getTypeID = function () {
  14882. return 0;
  14883. };
  14884. /**
  14885. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14886. */
  14887. Light.prototype.getScaledIntensity = function () {
  14888. return this._photometricScale * this.intensity;
  14889. };
  14890. /**
  14891. * Returns a new Light object, named "name", from the current one.
  14892. */
  14893. Light.prototype.clone = function (name) {
  14894. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14895. };
  14896. /**
  14897. * Serializes the current light into a Serialization object.
  14898. * Returns the serialized object.
  14899. */
  14900. Light.prototype.serialize = function () {
  14901. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14902. // Type
  14903. serializationObject.type = this.getTypeID();
  14904. // Parent
  14905. if (this.parent) {
  14906. serializationObject.parentId = this.parent.id;
  14907. }
  14908. // Inclusion / exclusions
  14909. if (this.excludedMeshes.length > 0) {
  14910. serializationObject.excludedMeshesIds = [];
  14911. this.excludedMeshes.forEach(function (mesh) {
  14912. serializationObject.excludedMeshesIds.push(mesh.id);
  14913. });
  14914. }
  14915. if (this.includedOnlyMeshes.length > 0) {
  14916. serializationObject.includedOnlyMeshesIds = [];
  14917. this.includedOnlyMeshes.forEach(function (mesh) {
  14918. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14919. });
  14920. }
  14921. // Animations
  14922. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14923. serializationObject.ranges = this.serializeAnimationRanges();
  14924. return serializationObject;
  14925. };
  14926. /**
  14927. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14928. * This new light is named "name" and added to the passed scene.
  14929. */
  14930. Light.GetConstructorFromName = function (type, name, scene) {
  14931. switch (type) {
  14932. case 0:
  14933. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14934. case 1:
  14935. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14936. case 2:
  14937. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14938. case 3:
  14939. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14940. }
  14941. };
  14942. /**
  14943. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14944. */
  14945. Light.Parse = function (parsedLight, scene) {
  14946. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14947. // Inclusion / exclusions
  14948. if (parsedLight.excludedMeshesIds) {
  14949. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14950. }
  14951. if (parsedLight.includedOnlyMeshesIds) {
  14952. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14953. }
  14954. // Parent
  14955. if (parsedLight.parentId) {
  14956. light._waitingParentId = parsedLight.parentId;
  14957. }
  14958. // Animations
  14959. if (parsedLight.animations) {
  14960. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14961. var parsedAnimation = parsedLight.animations[animationIndex];
  14962. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14963. }
  14964. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14965. }
  14966. if (parsedLight.autoAnimate) {
  14967. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14968. }
  14969. return light;
  14970. };
  14971. Light.prototype._hookArrayForExcluded = function (array) {
  14972. var _this = this;
  14973. var oldPush = array.push;
  14974. array.push = function () {
  14975. var items = [];
  14976. for (var _i = 0; _i < arguments.length; _i++) {
  14977. items[_i] = arguments[_i];
  14978. }
  14979. var result = oldPush.apply(array, items);
  14980. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14981. var item = items_1[_a];
  14982. item._resyncLighSource(_this);
  14983. }
  14984. return result;
  14985. };
  14986. var oldSplice = array.splice;
  14987. array.splice = function (index, deleteCount) {
  14988. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14989. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14990. var item = deleted_1[_i];
  14991. item._resyncLighSource(_this);
  14992. }
  14993. return deleted;
  14994. };
  14995. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14996. var item = array_1[_i];
  14997. item._resyncLighSource(this);
  14998. }
  14999. };
  15000. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15001. var _this = this;
  15002. var oldPush = array.push;
  15003. array.push = function () {
  15004. var items = [];
  15005. for (var _i = 0; _i < arguments.length; _i++) {
  15006. items[_i] = arguments[_i];
  15007. }
  15008. var result = oldPush.apply(array, items);
  15009. _this._resyncMeshes();
  15010. return result;
  15011. };
  15012. var oldSplice = array.splice;
  15013. array.splice = function (index, deleteCount) {
  15014. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15015. _this._resyncMeshes();
  15016. return deleted;
  15017. };
  15018. this._resyncMeshes();
  15019. };
  15020. Light.prototype._resyncMeshes = function () {
  15021. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15022. var mesh = _a[_i];
  15023. mesh._resyncLighSource(this);
  15024. }
  15025. };
  15026. Light.prototype._markMeshesAsLightDirty = function () {
  15027. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15028. var mesh = _a[_i];
  15029. if (mesh._lightSources.indexOf(this) !== -1) {
  15030. mesh._markSubMeshesAsLightDirty();
  15031. }
  15032. }
  15033. };
  15034. /**
  15035. * Recomputes the cached photometric scale if needed.
  15036. */
  15037. Light.prototype._computePhotometricScale = function () {
  15038. this._photometricScale = this._getPhotometricScale();
  15039. this.getScene().resetCachedMaterial();
  15040. };
  15041. /**
  15042. * Returns the Photometric Scale according to the light type and intensity mode.
  15043. */
  15044. Light.prototype._getPhotometricScale = function () {
  15045. var photometricScale = 0.0;
  15046. var lightTypeID = this.getTypeID();
  15047. //get photometric mode
  15048. var photometricMode = this.intensityMode;
  15049. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15050. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15051. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15052. }
  15053. else {
  15054. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15055. }
  15056. }
  15057. //compute photometric scale
  15058. switch (lightTypeID) {
  15059. case Light.LIGHTTYPEID_POINTLIGHT:
  15060. case Light.LIGHTTYPEID_SPOTLIGHT:
  15061. switch (photometricMode) {
  15062. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15063. photometricScale = 1.0 / (4.0 * Math.PI);
  15064. break;
  15065. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15066. photometricScale = 1.0;
  15067. break;
  15068. case Light.INTENSITYMODE_LUMINANCE:
  15069. photometricScale = this.radius * this.radius;
  15070. break;
  15071. }
  15072. break;
  15073. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15074. switch (photometricMode) {
  15075. case Light.INTENSITYMODE_ILLUMINANCE:
  15076. photometricScale = 1.0;
  15077. break;
  15078. case Light.INTENSITYMODE_LUMINANCE:
  15079. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15080. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15081. var apexAngleRadians = this.radius;
  15082. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15083. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15084. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15085. photometricScale = solidAngle;
  15086. break;
  15087. }
  15088. break;
  15089. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15090. // No fall off in hemisperic light.
  15091. photometricScale = 1.0;
  15092. break;
  15093. }
  15094. return photometricScale;
  15095. };
  15096. Light.prototype._reorderLightsInScene = function () {
  15097. var scene = this.getScene();
  15098. if (this.renderPriority != 0) {
  15099. scene.requireLightSorting = true;
  15100. }
  15101. this.getScene().sortLightsByPriority();
  15102. };
  15103. //lightmapMode Consts
  15104. Light._LIGHTMAP_DEFAULT = 0;
  15105. Light._LIGHTMAP_SPECULAR = 1;
  15106. Light._LIGHTMAP_SHADOWSONLY = 2;
  15107. // Intensity Mode Consts
  15108. Light._INTENSITYMODE_AUTOMATIC = 0;
  15109. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15110. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15111. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15112. Light._INTENSITYMODE_LUMINANCE = 4;
  15113. // Light types ids const.
  15114. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15115. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15116. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15117. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15118. __decorate([
  15119. BABYLON.serializeAsColor3()
  15120. ], Light.prototype, "diffuse", void 0);
  15121. __decorate([
  15122. BABYLON.serializeAsColor3()
  15123. ], Light.prototype, "specular", void 0);
  15124. __decorate([
  15125. BABYLON.serialize()
  15126. ], Light.prototype, "intensity", void 0);
  15127. __decorate([
  15128. BABYLON.serialize()
  15129. ], Light.prototype, "range", void 0);
  15130. __decorate([
  15131. BABYLON.serialize()
  15132. ], Light.prototype, "intensityMode", null);
  15133. __decorate([
  15134. BABYLON.serialize()
  15135. ], Light.prototype, "radius", null);
  15136. __decorate([
  15137. BABYLON.serialize()
  15138. ], Light.prototype, "_renderPriority", void 0);
  15139. __decorate([
  15140. BABYLON.expandToProperty("_reorderLightsInScene")
  15141. ], Light.prototype, "renderPriority", void 0);
  15142. __decorate([
  15143. BABYLON.serialize()
  15144. ], Light.prototype, "shadowEnabled", void 0);
  15145. __decorate([
  15146. BABYLON.serialize("excludeWithLayerMask")
  15147. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15148. __decorate([
  15149. BABYLON.serialize("includeOnlyWithLayerMask")
  15150. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15151. __decorate([
  15152. BABYLON.serialize("lightmapMode")
  15153. ], Light.prototype, "_lightmapMode", void 0);
  15154. return Light;
  15155. }(BABYLON.Node));
  15156. BABYLON.Light = Light;
  15157. })(BABYLON || (BABYLON = {}));
  15158. //# sourceMappingURL=babylon.light.js.map
  15159. var BABYLON;
  15160. (function (BABYLON) {
  15161. var Camera = (function (_super) {
  15162. __extends(Camera, _super);
  15163. function Camera(name, position, scene) {
  15164. var _this = _super.call(this, name, scene) || this;
  15165. _this.upVector = BABYLON.Vector3.Up();
  15166. _this.orthoLeft = null;
  15167. _this.orthoRight = null;
  15168. _this.orthoBottom = null;
  15169. _this.orthoTop = null;
  15170. _this.fov = 0.8;
  15171. _this.minZ = 1;
  15172. _this.maxZ = 10000.0;
  15173. _this.inertia = 0.9;
  15174. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15175. _this.isIntermediate = false;
  15176. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15177. _this.layerMask = 0x0FFFFFFF;
  15178. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15179. // Camera rig members
  15180. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15181. _this._rigCameras = new Array();
  15182. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15183. _this._skipRendering = false;
  15184. _this.customRenderTargets = new Array();
  15185. // Observables
  15186. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15187. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15188. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15189. _this.onRestoreStateObservable = new BABYLON.Observable();
  15190. // Cache
  15191. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15192. _this._projectionMatrix = new BABYLON.Matrix();
  15193. _this._doNotComputeProjectionMatrix = false;
  15194. _this._postProcesses = new Array();
  15195. _this._transformMatrix = BABYLON.Matrix.Zero();
  15196. _this._activeMeshes = new BABYLON.SmartArray(256);
  15197. _this._globalPosition = BABYLON.Vector3.Zero();
  15198. _this._refreshFrustumPlanes = true;
  15199. _this.getScene().addCamera(_this);
  15200. if (!_this.getScene().activeCamera) {
  15201. _this.getScene().activeCamera = _this;
  15202. }
  15203. _this.position = position;
  15204. return _this;
  15205. }
  15206. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15207. get: function () {
  15208. return Camera._PERSPECTIVE_CAMERA;
  15209. },
  15210. enumerable: true,
  15211. configurable: true
  15212. });
  15213. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15214. get: function () {
  15215. return Camera._ORTHOGRAPHIC_CAMERA;
  15216. },
  15217. enumerable: true,
  15218. configurable: true
  15219. });
  15220. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15221. get: function () {
  15222. return Camera._FOVMODE_VERTICAL_FIXED;
  15223. },
  15224. enumerable: true,
  15225. configurable: true
  15226. });
  15227. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15228. get: function () {
  15229. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15230. },
  15231. enumerable: true,
  15232. configurable: true
  15233. });
  15234. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15235. get: function () {
  15236. return Camera._RIG_MODE_NONE;
  15237. },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15242. get: function () {
  15243. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15244. },
  15245. enumerable: true,
  15246. configurable: true
  15247. });
  15248. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15249. get: function () {
  15250. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15251. },
  15252. enumerable: true,
  15253. configurable: true
  15254. });
  15255. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15256. get: function () {
  15257. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15258. },
  15259. enumerable: true,
  15260. configurable: true
  15261. });
  15262. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15263. get: function () {
  15264. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15265. },
  15266. enumerable: true,
  15267. configurable: true
  15268. });
  15269. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15270. get: function () {
  15271. return Camera._RIG_MODE_VR;
  15272. },
  15273. enumerable: true,
  15274. configurable: true
  15275. });
  15276. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15277. get: function () {
  15278. return Camera._RIG_MODE_WEBVR;
  15279. },
  15280. enumerable: true,
  15281. configurable: true
  15282. });
  15283. /**
  15284. * Store current camera state (fov, position, etc..)
  15285. */
  15286. Camera.prototype.storeState = function () {
  15287. this._stateStored = true;
  15288. this._storedFov = this.fov;
  15289. return this;
  15290. };
  15291. /**
  15292. * Restores the camera state values if it has been stored. You must call storeState() first
  15293. */
  15294. Camera.prototype._restoreStateValues = function () {
  15295. if (!this._stateStored) {
  15296. return false;
  15297. }
  15298. this.fov = this._storedFov;
  15299. return true;
  15300. };
  15301. /**
  15302. * Restored camera state. You must call storeState() first
  15303. */
  15304. Camera.prototype.restoreState = function () {
  15305. if (this._restoreStateValues()) {
  15306. this.onRestoreStateObservable.notifyObservers(this);
  15307. return true;
  15308. }
  15309. return false;
  15310. };
  15311. Camera.prototype.getClassName = function () {
  15312. return "Camera";
  15313. };
  15314. /**
  15315. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15316. */
  15317. Camera.prototype.toString = function (fullDetails) {
  15318. var ret = "Name: " + this.name;
  15319. ret += ", type: " + this.getClassName();
  15320. if (this.animations) {
  15321. for (var i = 0; i < this.animations.length; i++) {
  15322. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15323. }
  15324. }
  15325. if (fullDetails) {
  15326. }
  15327. return ret;
  15328. };
  15329. Object.defineProperty(Camera.prototype, "globalPosition", {
  15330. get: function () {
  15331. return this._globalPosition;
  15332. },
  15333. enumerable: true,
  15334. configurable: true
  15335. });
  15336. Camera.prototype.getActiveMeshes = function () {
  15337. return this._activeMeshes;
  15338. };
  15339. Camera.prototype.isActiveMesh = function (mesh) {
  15340. return (this._activeMeshes.indexOf(mesh) !== -1);
  15341. };
  15342. //Cache
  15343. Camera.prototype._initCache = function () {
  15344. _super.prototype._initCache.call(this);
  15345. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15346. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15347. this._cache.mode = undefined;
  15348. this._cache.minZ = undefined;
  15349. this._cache.maxZ = undefined;
  15350. this._cache.fov = undefined;
  15351. this._cache.fovMode = undefined;
  15352. this._cache.aspectRatio = undefined;
  15353. this._cache.orthoLeft = undefined;
  15354. this._cache.orthoRight = undefined;
  15355. this._cache.orthoBottom = undefined;
  15356. this._cache.orthoTop = undefined;
  15357. this._cache.renderWidth = undefined;
  15358. this._cache.renderHeight = undefined;
  15359. };
  15360. Camera.prototype._updateCache = function (ignoreParentClass) {
  15361. if (!ignoreParentClass) {
  15362. _super.prototype._updateCache.call(this);
  15363. }
  15364. var engine = this.getEngine();
  15365. this._cache.position.copyFrom(this.position);
  15366. this._cache.upVector.copyFrom(this.upVector);
  15367. };
  15368. // Synchronized
  15369. Camera.prototype._isSynchronized = function () {
  15370. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15371. };
  15372. Camera.prototype._isSynchronizedViewMatrix = function () {
  15373. if (!_super.prototype._isSynchronized.call(this))
  15374. return false;
  15375. return this._cache.position.equals(this.position)
  15376. && this._cache.upVector.equals(this.upVector)
  15377. && this.isSynchronizedWithParent();
  15378. };
  15379. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15380. var check = this._cache.mode === this.mode
  15381. && this._cache.minZ === this.minZ
  15382. && this._cache.maxZ === this.maxZ;
  15383. if (!check) {
  15384. return false;
  15385. }
  15386. var engine = this.getEngine();
  15387. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15388. check = this._cache.fov === this.fov
  15389. && this._cache.fovMode === this.fovMode
  15390. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15391. }
  15392. else {
  15393. check = this._cache.orthoLeft === this.orthoLeft
  15394. && this._cache.orthoRight === this.orthoRight
  15395. && this._cache.orthoBottom === this.orthoBottom
  15396. && this._cache.orthoTop === this.orthoTop
  15397. && this._cache.renderWidth === engine.getRenderWidth()
  15398. && this._cache.renderHeight === engine.getRenderHeight();
  15399. }
  15400. return check;
  15401. };
  15402. // Controls
  15403. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15404. };
  15405. Camera.prototype.detachControl = function (element) {
  15406. };
  15407. Camera.prototype.update = function () {
  15408. this._checkInputs();
  15409. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15410. this._updateRigCameras();
  15411. }
  15412. };
  15413. Camera.prototype._checkInputs = function () {
  15414. this.onAfterCheckInputsObservable.notifyObservers(this);
  15415. };
  15416. Object.defineProperty(Camera.prototype, "rigCameras", {
  15417. get: function () {
  15418. return this._rigCameras;
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15424. get: function () {
  15425. return this._rigPostProcess;
  15426. },
  15427. enumerable: true,
  15428. configurable: true
  15429. });
  15430. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15431. // invalidate framebuffer
  15432. if (this._postProcesses.length > 0) {
  15433. this._postProcesses[0].markTextureDirty();
  15434. }
  15435. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15436. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15437. var cam = this._rigCameras[i];
  15438. var rigPostProcess = cam._rigPostProcess;
  15439. // for VR rig, there does not have to be a post process
  15440. if (rigPostProcess) {
  15441. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15442. if (isPass) {
  15443. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15444. cam.isIntermediate = this._postProcesses.length === 0;
  15445. }
  15446. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15447. rigPostProcess.markTextureDirty();
  15448. }
  15449. else {
  15450. cam._postProcesses = this._postProcesses.slice(0);
  15451. }
  15452. }
  15453. };
  15454. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15455. if (insertAt === void 0) { insertAt = null; }
  15456. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15457. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15458. return 0;
  15459. }
  15460. if (insertAt == null || insertAt < 0) {
  15461. this._postProcesses.push(postProcess);
  15462. }
  15463. else {
  15464. this._postProcesses.splice(insertAt, 0, postProcess);
  15465. }
  15466. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15467. return this._postProcesses.indexOf(postProcess);
  15468. };
  15469. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15470. if (atIndices === void 0) { atIndices = null; }
  15471. var result = [];
  15472. var i;
  15473. var index;
  15474. if (!atIndices) {
  15475. var idx = this._postProcesses.indexOf(postProcess);
  15476. if (idx !== -1) {
  15477. this._postProcesses.splice(idx, 1);
  15478. }
  15479. }
  15480. else {
  15481. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15482. // iterate descending, so can just splice as we go
  15483. for (i = atIndices.length - 1; i >= 0; i--) {
  15484. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15485. result.push(i);
  15486. continue;
  15487. }
  15488. index = atIndices[i];
  15489. this._postProcesses.splice(index, 1);
  15490. }
  15491. }
  15492. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15493. return result;
  15494. };
  15495. Camera.prototype.getWorldMatrix = function () {
  15496. if (!this._worldMatrix) {
  15497. this._worldMatrix = BABYLON.Matrix.Identity();
  15498. }
  15499. var viewMatrix = this.getViewMatrix();
  15500. viewMatrix.invertToRef(this._worldMatrix);
  15501. return this._worldMatrix;
  15502. };
  15503. Camera.prototype._getViewMatrix = function () {
  15504. return BABYLON.Matrix.Identity();
  15505. };
  15506. Camera.prototype.getViewMatrix = function (force) {
  15507. if (!force && this._isSynchronizedViewMatrix()) {
  15508. return this._computedViewMatrix;
  15509. }
  15510. this.updateCache();
  15511. this._computedViewMatrix = this._getViewMatrix();
  15512. this._currentRenderId = this.getScene().getRenderId();
  15513. this._refreshFrustumPlanes = true;
  15514. if (!this.parent || !this.parent.getWorldMatrix) {
  15515. this._globalPosition.copyFrom(this.position);
  15516. }
  15517. else {
  15518. if (!this._worldMatrix) {
  15519. this._worldMatrix = BABYLON.Matrix.Identity();
  15520. }
  15521. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15522. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15523. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15524. this._computedViewMatrix.invert();
  15525. this._markSyncedWithParent();
  15526. }
  15527. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15528. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15529. }
  15530. this.onViewMatrixChangedObservable.notifyObservers(this);
  15531. return this._computedViewMatrix;
  15532. };
  15533. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15534. this._doNotComputeProjectionMatrix = true;
  15535. if (projection !== undefined) {
  15536. this._projectionMatrix = projection;
  15537. }
  15538. };
  15539. ;
  15540. Camera.prototype.unfreezeProjectionMatrix = function () {
  15541. this._doNotComputeProjectionMatrix = false;
  15542. };
  15543. ;
  15544. Camera.prototype.getProjectionMatrix = function (force) {
  15545. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15546. return this._projectionMatrix;
  15547. }
  15548. // Cache
  15549. this._cache.mode = this.mode;
  15550. this._cache.minZ = this.minZ;
  15551. this._cache.maxZ = this.maxZ;
  15552. // Matrix
  15553. this._refreshFrustumPlanes = true;
  15554. var engine = this.getEngine();
  15555. var scene = this.getScene();
  15556. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15557. this._cache.fov = this.fov;
  15558. this._cache.fovMode = this.fovMode;
  15559. this._cache.aspectRatio = engine.getAspectRatio(this);
  15560. if (this.minZ <= 0) {
  15561. this.minZ = 0.1;
  15562. }
  15563. if (scene.useRightHandedSystem) {
  15564. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15565. }
  15566. else {
  15567. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15568. }
  15569. }
  15570. else {
  15571. var halfWidth = engine.getRenderWidth() / 2.0;
  15572. var halfHeight = engine.getRenderHeight() / 2.0;
  15573. if (scene.useRightHandedSystem) {
  15574. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15575. }
  15576. else {
  15577. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15578. }
  15579. this._cache.orthoLeft = this.orthoLeft;
  15580. this._cache.orthoRight = this.orthoRight;
  15581. this._cache.orthoBottom = this.orthoBottom;
  15582. this._cache.orthoTop = this.orthoTop;
  15583. this._cache.renderWidth = engine.getRenderWidth();
  15584. this._cache.renderHeight = engine.getRenderHeight();
  15585. }
  15586. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15587. return this._projectionMatrix;
  15588. };
  15589. Camera.prototype.getTranformationMatrix = function () {
  15590. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15591. return this._transformMatrix;
  15592. };
  15593. Camera.prototype.updateFrustumPlanes = function () {
  15594. if (!this._refreshFrustumPlanes) {
  15595. return;
  15596. }
  15597. this.getTranformationMatrix();
  15598. if (!this._frustumPlanes) {
  15599. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15600. }
  15601. else {
  15602. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15603. }
  15604. this._refreshFrustumPlanes = false;
  15605. };
  15606. Camera.prototype.isInFrustum = function (target) {
  15607. this.updateFrustumPlanes();
  15608. return target.isInFrustum(this._frustumPlanes);
  15609. };
  15610. Camera.prototype.isCompletelyInFrustum = function (target) {
  15611. this.updateFrustumPlanes();
  15612. return target.isCompletelyInFrustum(this._frustumPlanes);
  15613. };
  15614. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15615. if (length === void 0) { length = 100; }
  15616. if (!transform) {
  15617. transform = this.getWorldMatrix();
  15618. }
  15619. if (!origin) {
  15620. origin = this.position;
  15621. }
  15622. var forward = new BABYLON.Vector3(0, 0, 1);
  15623. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15624. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15625. return new BABYLON.Ray(origin, direction, length);
  15626. };
  15627. Camera.prototype.dispose = function () {
  15628. // Observables
  15629. this.onViewMatrixChangedObservable.clear();
  15630. this.onProjectionMatrixChangedObservable.clear();
  15631. this.onAfterCheckInputsObservable.clear();
  15632. this.onRestoreStateObservable.clear();
  15633. // Inputs
  15634. if (this.inputs) {
  15635. this.inputs.clear();
  15636. }
  15637. // Animations
  15638. this.getScene().stopAnimation(this);
  15639. // Remove from scene
  15640. this.getScene().removeCamera(this);
  15641. while (this._rigCameras.length > 0) {
  15642. this._rigCameras.pop().dispose();
  15643. }
  15644. // Postprocesses
  15645. if (this._rigPostProcess) {
  15646. this._rigPostProcess.dispose(this);
  15647. this._rigPostProcess = null;
  15648. this._postProcesses = [];
  15649. }
  15650. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15651. this._rigPostProcess = null;
  15652. this._postProcesses = [];
  15653. }
  15654. else {
  15655. var i = this._postProcesses.length;
  15656. while (--i >= 0) {
  15657. this._postProcesses[i].dispose(this);
  15658. }
  15659. }
  15660. // Render targets
  15661. var i = this.customRenderTargets.length;
  15662. while (--i >= 0) {
  15663. this.customRenderTargets[i].dispose();
  15664. }
  15665. this.customRenderTargets = [];
  15666. // Active Meshes
  15667. this._activeMeshes.dispose();
  15668. _super.prototype.dispose.call(this);
  15669. };
  15670. Object.defineProperty(Camera.prototype, "leftCamera", {
  15671. // ---- Camera rigs section ----
  15672. get: function () {
  15673. if (this._rigCameras.length < 1) {
  15674. return undefined;
  15675. }
  15676. return this._rigCameras[0];
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(Camera.prototype, "rightCamera", {
  15682. get: function () {
  15683. if (this._rigCameras.length < 2) {
  15684. return undefined;
  15685. }
  15686. return this._rigCameras[1];
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Camera.prototype.getLeftTarget = function () {
  15692. if (this._rigCameras.length < 1) {
  15693. return undefined;
  15694. }
  15695. return this._rigCameras[0].getTarget();
  15696. };
  15697. Camera.prototype.getRightTarget = function () {
  15698. if (this._rigCameras.length < 2) {
  15699. return undefined;
  15700. }
  15701. return this._rigCameras[1].getTarget();
  15702. };
  15703. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15704. if (this.cameraRigMode === mode) {
  15705. return;
  15706. }
  15707. while (this._rigCameras.length > 0) {
  15708. this._rigCameras.pop().dispose();
  15709. }
  15710. this.cameraRigMode = mode;
  15711. this._cameraRigParams = {};
  15712. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15713. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15714. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15715. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15716. // create the rig cameras, unless none
  15717. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15718. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15719. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15720. }
  15721. switch (this.cameraRigMode) {
  15722. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15723. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15724. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15725. break;
  15726. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15727. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15728. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15729. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15730. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15731. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15732. break;
  15733. case Camera.RIG_MODE_VR:
  15734. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15735. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15736. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15737. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15738. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15739. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15740. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15741. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15742. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15743. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15744. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15745. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15746. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15747. if (metrics.compensateDistortion) {
  15748. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15749. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15750. }
  15751. break;
  15752. case Camera.RIG_MODE_WEBVR:
  15753. if (rigParams.vrDisplay) {
  15754. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15755. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15756. //Left eye
  15757. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15758. this._rigCameras[0].setCameraRigParameter("left", true);
  15759. //leaving this for future reference
  15760. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15761. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15762. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15763. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15764. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15765. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15766. this._rigCameras[0].parent = this;
  15767. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15768. //Right eye
  15769. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15770. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15771. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15772. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15773. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15774. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15775. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15776. this._rigCameras[1].parent = this;
  15777. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15778. if (Camera.UseAlternateWebVRRendering) {
  15779. this._rigCameras[1]._skipRendering = true;
  15780. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15781. }
  15782. }
  15783. break;
  15784. }
  15785. this._cascadePostProcessesToRigCams();
  15786. this.update();
  15787. };
  15788. Camera.prototype._getVRProjectionMatrix = function () {
  15789. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15790. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15791. return this._projectionMatrix;
  15792. };
  15793. Camera.prototype._updateCameraRotationMatrix = function () {
  15794. //Here for WebVR
  15795. };
  15796. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15797. //Here for WebVR
  15798. };
  15799. /**
  15800. * This function MUST be overwritten by the different WebVR cameras available.
  15801. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15802. */
  15803. Camera.prototype._getWebVRProjectionMatrix = function () {
  15804. return BABYLON.Matrix.Identity();
  15805. };
  15806. /**
  15807. * This function MUST be overwritten by the different WebVR cameras available.
  15808. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15809. */
  15810. Camera.prototype._getWebVRViewMatrix = function () {
  15811. return BABYLON.Matrix.Identity();
  15812. };
  15813. Camera.prototype.setCameraRigParameter = function (name, value) {
  15814. if (!this._cameraRigParams) {
  15815. this._cameraRigParams = {};
  15816. }
  15817. this._cameraRigParams[name] = value;
  15818. //provisionnally:
  15819. if (name === "interaxialDistance") {
  15820. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15821. }
  15822. };
  15823. /**
  15824. * needs to be overridden by children so sub has required properties to be copied
  15825. */
  15826. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15827. return null;
  15828. };
  15829. /**
  15830. * May need to be overridden by children
  15831. */
  15832. Camera.prototype._updateRigCameras = function () {
  15833. for (var i = 0; i < this._rigCameras.length; i++) {
  15834. this._rigCameras[i].minZ = this.minZ;
  15835. this._rigCameras[i].maxZ = this.maxZ;
  15836. this._rigCameras[i].fov = this.fov;
  15837. }
  15838. // only update viewport when ANAGLYPH
  15839. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15840. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15841. }
  15842. };
  15843. Camera.prototype._setupInputs = function () {
  15844. };
  15845. Camera.prototype.serialize = function () {
  15846. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15847. // Type
  15848. serializationObject.type = this.getClassName();
  15849. // Parent
  15850. if (this.parent) {
  15851. serializationObject.parentId = this.parent.id;
  15852. }
  15853. if (this.inputs) {
  15854. this.inputs.serialize(serializationObject);
  15855. }
  15856. // Animations
  15857. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15858. serializationObject.ranges = this.serializeAnimationRanges();
  15859. return serializationObject;
  15860. };
  15861. Camera.prototype.clone = function (name) {
  15862. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15863. };
  15864. Camera.prototype.getDirection = function (localAxis) {
  15865. var result = BABYLON.Vector3.Zero();
  15866. this.getDirectionToRef(localAxis, result);
  15867. return result;
  15868. };
  15869. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15870. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15871. };
  15872. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15873. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15874. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15875. switch (type) {
  15876. case "ArcRotateCamera":
  15877. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15878. case "DeviceOrientationCamera":
  15879. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15880. case "FollowCamera":
  15881. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15882. case "ArcFollowCamera":
  15883. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15884. case "GamepadCamera":
  15885. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15886. case "TouchCamera":
  15887. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15888. case "VirtualJoysticksCamera":
  15889. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15890. case "WebVRFreeCamera":
  15891. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15892. case "WebVRGamepadCamera":
  15893. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15894. case "VRDeviceOrientationFreeCamera":
  15895. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15896. case "VRDeviceOrientationGamepadCamera":
  15897. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15898. case "AnaglyphArcRotateCamera":
  15899. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15900. case "AnaglyphFreeCamera":
  15901. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15902. case "AnaglyphGamepadCamera":
  15903. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15904. case "AnaglyphUniversalCamera":
  15905. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15906. case "StereoscopicArcRotateCamera":
  15907. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15908. case "StereoscopicFreeCamera":
  15909. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15910. case "StereoscopicGamepadCamera":
  15911. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15912. case "StereoscopicUniversalCamera":
  15913. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15914. case "FreeCamera":// Forcing Universal here
  15915. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15916. default:// Universal Camera is the default value
  15917. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15918. }
  15919. };
  15920. Camera.Parse = function (parsedCamera, scene) {
  15921. var type = parsedCamera.type;
  15922. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15923. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15924. // Parent
  15925. if (parsedCamera.parentId) {
  15926. camera._waitingParentId = parsedCamera.parentId;
  15927. }
  15928. //If camera has an input manager, let it parse inputs settings
  15929. if (camera.inputs) {
  15930. camera.inputs.parse(parsedCamera);
  15931. camera._setupInputs();
  15932. }
  15933. if (camera.setPosition) {
  15934. camera.position.copyFromFloats(0, 0, 0);
  15935. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15936. }
  15937. // Target
  15938. if (parsedCamera.target) {
  15939. if (camera.setTarget) {
  15940. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15941. }
  15942. }
  15943. // Apply 3d rig, when found
  15944. if (parsedCamera.cameraRigMode) {
  15945. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15946. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15947. }
  15948. // Animations
  15949. if (parsedCamera.animations) {
  15950. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15951. var parsedAnimation = parsedCamera.animations[animationIndex];
  15952. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15953. }
  15954. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15955. }
  15956. if (parsedCamera.autoAnimate) {
  15957. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15958. }
  15959. return camera;
  15960. };
  15961. // Statics
  15962. Camera._PERSPECTIVE_CAMERA = 0;
  15963. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15964. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15965. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15966. Camera._RIG_MODE_NONE = 0;
  15967. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15968. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15969. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15970. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15971. Camera._RIG_MODE_VR = 20;
  15972. Camera._RIG_MODE_WEBVR = 21;
  15973. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15974. Camera.UseAlternateWebVRRendering = false;
  15975. __decorate([
  15976. BABYLON.serializeAsVector3()
  15977. ], Camera.prototype, "position", void 0);
  15978. __decorate([
  15979. BABYLON.serializeAsVector3()
  15980. ], Camera.prototype, "upVector", void 0);
  15981. __decorate([
  15982. BABYLON.serialize()
  15983. ], Camera.prototype, "orthoLeft", void 0);
  15984. __decorate([
  15985. BABYLON.serialize()
  15986. ], Camera.prototype, "orthoRight", void 0);
  15987. __decorate([
  15988. BABYLON.serialize()
  15989. ], Camera.prototype, "orthoBottom", void 0);
  15990. __decorate([
  15991. BABYLON.serialize()
  15992. ], Camera.prototype, "orthoTop", void 0);
  15993. __decorate([
  15994. BABYLON.serialize()
  15995. ], Camera.prototype, "fov", void 0);
  15996. __decorate([
  15997. BABYLON.serialize()
  15998. ], Camera.prototype, "minZ", void 0);
  15999. __decorate([
  16000. BABYLON.serialize()
  16001. ], Camera.prototype, "maxZ", void 0);
  16002. __decorate([
  16003. BABYLON.serialize()
  16004. ], Camera.prototype, "inertia", void 0);
  16005. __decorate([
  16006. BABYLON.serialize()
  16007. ], Camera.prototype, "mode", void 0);
  16008. __decorate([
  16009. BABYLON.serialize()
  16010. ], Camera.prototype, "layerMask", void 0);
  16011. __decorate([
  16012. BABYLON.serialize()
  16013. ], Camera.prototype, "fovMode", void 0);
  16014. __decorate([
  16015. BABYLON.serialize()
  16016. ], Camera.prototype, "cameraRigMode", void 0);
  16017. __decorate([
  16018. BABYLON.serialize()
  16019. ], Camera.prototype, "interaxialDistance", void 0);
  16020. __decorate([
  16021. BABYLON.serialize()
  16022. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16023. return Camera;
  16024. }(BABYLON.Node));
  16025. BABYLON.Camera = Camera;
  16026. })(BABYLON || (BABYLON = {}));
  16027. //# sourceMappingURL=babylon.camera.js.map
  16028. var BABYLON;
  16029. (function (BABYLON) {
  16030. var RenderingManager = (function () {
  16031. function RenderingManager(scene) {
  16032. this._renderingGroups = new Array();
  16033. this._autoClearDepthStencil = {};
  16034. this._customOpaqueSortCompareFn = {};
  16035. this._customAlphaTestSortCompareFn = {};
  16036. this._customTransparentSortCompareFn = {};
  16037. this._renderinGroupInfo = null;
  16038. this._scene = scene;
  16039. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16040. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16041. }
  16042. }
  16043. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16044. if (depth === void 0) { depth = true; }
  16045. if (stencil === void 0) { stencil = true; }
  16046. if (this._depthStencilBufferAlreadyCleaned) {
  16047. return;
  16048. }
  16049. this._scene.getEngine().clear(null, false, depth, stencil);
  16050. this._depthStencilBufferAlreadyCleaned = true;
  16051. };
  16052. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16053. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16054. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16055. var info = null;
  16056. if (observable) {
  16057. if (!this._renderinGroupInfo) {
  16058. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16059. }
  16060. info = this._renderinGroupInfo;
  16061. info.scene = this._scene;
  16062. info.camera = this._scene.activeCamera;
  16063. }
  16064. // Dispatch sprites
  16065. if (renderSprites) {
  16066. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16067. var manager = this._scene.spriteManagers[index];
  16068. this.dispatchSprites(manager);
  16069. }
  16070. }
  16071. // Render
  16072. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16073. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16074. var renderingGroup = this._renderingGroups[index];
  16075. if (!renderingGroup && !observable)
  16076. continue;
  16077. this._currentIndex = index;
  16078. var renderingGroupMask = 0;
  16079. // Fire PRECLEAR stage
  16080. if (observable) {
  16081. renderingGroupMask = Math.pow(2, index);
  16082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16083. info.renderingGroupId = index;
  16084. observable.notifyObservers(info, renderingGroupMask);
  16085. }
  16086. // Clear depth/stencil if needed
  16087. if (RenderingManager.AUTOCLEAR) {
  16088. var autoClear = this._autoClearDepthStencil[index];
  16089. if (autoClear && autoClear.autoClear) {
  16090. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16091. }
  16092. }
  16093. if (observable) {
  16094. // Fire PREOPAQUE stage
  16095. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16096. observable.notifyObservers(info, renderingGroupMask);
  16097. // Fire PRETRANSPARENT stage
  16098. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16099. observable.notifyObservers(info, renderingGroupMask);
  16100. }
  16101. if (renderingGroup)
  16102. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16103. // Fire POSTTRANSPARENT stage
  16104. if (observable) {
  16105. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16106. observable.notifyObservers(info, renderingGroupMask);
  16107. }
  16108. }
  16109. };
  16110. RenderingManager.prototype.reset = function () {
  16111. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16112. var renderingGroup = this._renderingGroups[index];
  16113. if (renderingGroup) {
  16114. renderingGroup.prepare();
  16115. }
  16116. }
  16117. };
  16118. RenderingManager.prototype.dispose = function () {
  16119. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16120. var renderingGroup = this._renderingGroups[index];
  16121. if (renderingGroup) {
  16122. renderingGroup.dispose();
  16123. }
  16124. }
  16125. this._renderingGroups.length = 0;
  16126. };
  16127. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16128. if (!this._renderingGroups[renderingGroupId]) {
  16129. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16130. }
  16131. };
  16132. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16133. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16134. this._prepareRenderingGroup(renderingGroupId);
  16135. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16136. };
  16137. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16138. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16139. this._prepareRenderingGroup(renderingGroupId);
  16140. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16141. };
  16142. RenderingManager.prototype.dispatch = function (subMesh) {
  16143. var mesh = subMesh.getMesh();
  16144. var renderingGroupId = mesh.renderingGroupId || 0;
  16145. this._prepareRenderingGroup(renderingGroupId);
  16146. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16147. };
  16148. /**
  16149. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16150. * This allowed control for front to back rendering or reversly depending of the special needs.
  16151. *
  16152. * @param renderingGroupId The rendering group id corresponding to its index
  16153. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16154. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16155. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16156. */
  16157. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16158. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16159. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16160. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16161. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16162. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16163. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16164. if (this._renderingGroups[renderingGroupId]) {
  16165. var group = this._renderingGroups[renderingGroupId];
  16166. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16167. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16168. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16169. }
  16170. };
  16171. /**
  16172. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16173. *
  16174. * @param renderingGroupId The rendering group id corresponding to its index
  16175. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16176. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16177. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16178. */
  16179. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16180. if (depth === void 0) { depth = true; }
  16181. if (stencil === void 0) { stencil = true; }
  16182. this._autoClearDepthStencil[renderingGroupId] = {
  16183. autoClear: autoClearDepthStencil,
  16184. depth: depth,
  16185. stencil: stencil
  16186. };
  16187. };
  16188. /**
  16189. * The max id used for rendering groups (not included)
  16190. */
  16191. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16192. /**
  16193. * The min id used for rendering groups (included)
  16194. */
  16195. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16196. /**
  16197. * Used to globally prevent autoclearing scenes.
  16198. */
  16199. RenderingManager.AUTOCLEAR = true;
  16200. return RenderingManager;
  16201. }());
  16202. BABYLON.RenderingManager = RenderingManager;
  16203. })(BABYLON || (BABYLON = {}));
  16204. //# sourceMappingURL=babylon.renderingManager.js.map
  16205. var BABYLON;
  16206. (function (BABYLON) {
  16207. var RenderingGroup = (function () {
  16208. /**
  16209. * Creates a new rendering group.
  16210. * @param index The rendering group index
  16211. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16212. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16213. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16214. */
  16215. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16216. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16217. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16218. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16219. this.index = index;
  16220. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16221. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16222. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16223. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16224. this._particleSystems = new BABYLON.SmartArray(256);
  16225. this._spriteManagers = new BABYLON.SmartArray(256);
  16226. this._edgesRenderers = new BABYLON.SmartArray(16);
  16227. this._scene = scene;
  16228. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16229. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16230. this.transparentSortCompareFn = transparentSortCompareFn;
  16231. }
  16232. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16233. /**
  16234. * Set the opaque sort comparison function.
  16235. * If null the sub meshes will be render in the order they were created
  16236. */
  16237. set: function (value) {
  16238. this._opaqueSortCompareFn = value;
  16239. if (value) {
  16240. this._renderOpaque = this.renderOpaqueSorted;
  16241. }
  16242. else {
  16243. this._renderOpaque = RenderingGroup.renderUnsorted;
  16244. }
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16250. /**
  16251. * Set the alpha test sort comparison function.
  16252. * If null the sub meshes will be render in the order they were created
  16253. */
  16254. set: function (value) {
  16255. this._alphaTestSortCompareFn = value;
  16256. if (value) {
  16257. this._renderAlphaTest = this.renderAlphaTestSorted;
  16258. }
  16259. else {
  16260. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16261. }
  16262. },
  16263. enumerable: true,
  16264. configurable: true
  16265. });
  16266. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16267. /**
  16268. * Set the transparent sort comparison function.
  16269. * If null the sub meshes will be render in the order they were created
  16270. */
  16271. set: function (value) {
  16272. if (value) {
  16273. this._transparentSortCompareFn = value;
  16274. }
  16275. else {
  16276. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16277. }
  16278. this._renderTransparent = this.renderTransparentSorted;
  16279. },
  16280. enumerable: true,
  16281. configurable: true
  16282. });
  16283. /**
  16284. * Render all the sub meshes contained in the group.
  16285. * @param customRenderFunction Used to override the default render behaviour of the group.
  16286. * @returns true if rendered some submeshes.
  16287. */
  16288. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16289. if (customRenderFunction) {
  16290. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16291. return;
  16292. }
  16293. var engine = this._scene.getEngine();
  16294. // Depth only
  16295. if (this._depthOnlySubMeshes.length !== 0) {
  16296. engine.setAlphaTesting(true);
  16297. engine.setColorWrite(false);
  16298. this._renderAlphaTest(this._depthOnlySubMeshes);
  16299. engine.setAlphaTesting(false);
  16300. engine.setColorWrite(true);
  16301. }
  16302. // Opaque
  16303. if (this._opaqueSubMeshes.length !== 0) {
  16304. this._renderOpaque(this._opaqueSubMeshes);
  16305. }
  16306. // Alpha test
  16307. if (this._alphaTestSubMeshes.length !== 0) {
  16308. engine.setAlphaTesting(true);
  16309. this._renderAlphaTest(this._alphaTestSubMeshes);
  16310. engine.setAlphaTesting(false);
  16311. }
  16312. var stencilState = engine.getStencilBuffer();
  16313. engine.setStencilBuffer(false);
  16314. // Sprites
  16315. if (renderSprites) {
  16316. this._renderSprites();
  16317. }
  16318. // Particles
  16319. if (renderParticles) {
  16320. this._renderParticles(activeMeshes);
  16321. }
  16322. if (this.onBeforeTransparentRendering) {
  16323. this.onBeforeTransparentRendering();
  16324. }
  16325. // Transparent
  16326. if (this._transparentSubMeshes.length !== 0) {
  16327. this._renderTransparent(this._transparentSubMeshes);
  16328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16329. }
  16330. // Set back stencil to false in case it changes before the edge renderer.
  16331. engine.setStencilBuffer(false);
  16332. // Edges
  16333. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16334. this._edgesRenderers.data[edgesRendererIndex].render();
  16335. }
  16336. // Restore Stencil state.
  16337. engine.setStencilBuffer(stencilState);
  16338. };
  16339. /**
  16340. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16341. * @param subMeshes The submeshes to render
  16342. */
  16343. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16344. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16345. };
  16346. /**
  16347. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16348. * @param subMeshes The submeshes to render
  16349. */
  16350. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16351. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16352. };
  16353. /**
  16354. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16355. * @param subMeshes The submeshes to render
  16356. */
  16357. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16358. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16359. };
  16360. /**
  16361. * Renders the submeshes in a specified order.
  16362. * @param subMeshes The submeshes to sort before render
  16363. * @param sortCompareFn The comparison function use to sort
  16364. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16365. * @param transparent Specifies to activate blending if true
  16366. */
  16367. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16368. var subIndex = 0;
  16369. var subMesh;
  16370. for (; subIndex < subMeshes.length; subIndex++) {
  16371. subMesh = subMeshes.data[subIndex];
  16372. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16373. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16374. }
  16375. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16376. sortedArray.sort(sortCompareFn);
  16377. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16378. subMesh = sortedArray[subIndex];
  16379. if (transparent) {
  16380. var material = subMesh.getMaterial();
  16381. if (material.needDepthPrePass) {
  16382. var engine = material.getScene().getEngine();
  16383. engine.setColorWrite(false);
  16384. engine.setAlphaTesting(true);
  16385. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16386. subMesh.render(false);
  16387. engine.setAlphaTesting(false);
  16388. engine.setColorWrite(true);
  16389. }
  16390. }
  16391. subMesh.render(transparent);
  16392. }
  16393. };
  16394. /**
  16395. * Renders the submeshes in the order they were dispatched (no sort applied).
  16396. * @param subMeshes The submeshes to render
  16397. */
  16398. RenderingGroup.renderUnsorted = function (subMeshes) {
  16399. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16400. var submesh = subMeshes.data[subIndex];
  16401. submesh.render(false);
  16402. }
  16403. };
  16404. /**
  16405. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16406. * are rendered back to front if in the same alpha index.
  16407. *
  16408. * @param a The first submesh
  16409. * @param b The second submesh
  16410. * @returns The result of the comparison
  16411. */
  16412. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16413. // Alpha index first
  16414. if (a._alphaIndex > b._alphaIndex) {
  16415. return 1;
  16416. }
  16417. if (a._alphaIndex < b._alphaIndex) {
  16418. return -1;
  16419. }
  16420. // Then distance to camera
  16421. return RenderingGroup.backToFrontSortCompare(a, b);
  16422. };
  16423. /**
  16424. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16425. * are rendered back to front.
  16426. *
  16427. * @param a The first submesh
  16428. * @param b The second submesh
  16429. * @returns The result of the comparison
  16430. */
  16431. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16432. // Then distance to camera
  16433. if (a._distanceToCamera < b._distanceToCamera) {
  16434. return 1;
  16435. }
  16436. if (a._distanceToCamera > b._distanceToCamera) {
  16437. return -1;
  16438. }
  16439. return 0;
  16440. };
  16441. /**
  16442. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16443. * are rendered front to back (prevent overdraw).
  16444. *
  16445. * @param a The first submesh
  16446. * @param b The second submesh
  16447. * @returns The result of the comparison
  16448. */
  16449. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16450. // Then distance to camera
  16451. if (a._distanceToCamera < b._distanceToCamera) {
  16452. return -1;
  16453. }
  16454. if (a._distanceToCamera > b._distanceToCamera) {
  16455. return 1;
  16456. }
  16457. return 0;
  16458. };
  16459. /**
  16460. * Resets the different lists of submeshes to prepare a new frame.
  16461. */
  16462. RenderingGroup.prototype.prepare = function () {
  16463. this._opaqueSubMeshes.reset();
  16464. this._transparentSubMeshes.reset();
  16465. this._alphaTestSubMeshes.reset();
  16466. this._depthOnlySubMeshes.reset();
  16467. this._particleSystems.reset();
  16468. this._spriteManagers.reset();
  16469. this._edgesRenderers.reset();
  16470. };
  16471. RenderingGroup.prototype.dispose = function () {
  16472. this._opaqueSubMeshes.dispose();
  16473. this._transparentSubMeshes.dispose();
  16474. this._alphaTestSubMeshes.dispose();
  16475. this._depthOnlySubMeshes.dispose();
  16476. this._particleSystems.dispose();
  16477. this._spriteManagers.dispose();
  16478. this._edgesRenderers.dispose();
  16479. };
  16480. /**
  16481. * Inserts the submesh in its correct queue depending on its material.
  16482. * @param subMesh The submesh to dispatch
  16483. */
  16484. RenderingGroup.prototype.dispatch = function (subMesh) {
  16485. var material = subMesh.getMaterial();
  16486. var mesh = subMesh.getMesh();
  16487. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16488. this._transparentSubMeshes.push(subMesh);
  16489. }
  16490. else if (material.needAlphaTesting()) {
  16491. if (material.needDepthPrePass) {
  16492. this._depthOnlySubMeshes.push(subMesh);
  16493. }
  16494. this._alphaTestSubMeshes.push(subMesh);
  16495. }
  16496. else {
  16497. if (material.needDepthPrePass) {
  16498. this._depthOnlySubMeshes.push(subMesh);
  16499. }
  16500. this._opaqueSubMeshes.push(subMesh); // Opaque
  16501. }
  16502. if (mesh._edgesRenderer) {
  16503. this._edgesRenderers.push(mesh._edgesRenderer);
  16504. }
  16505. };
  16506. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16507. this._spriteManagers.push(spriteManager);
  16508. };
  16509. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16510. this._particleSystems.push(particleSystem);
  16511. };
  16512. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16513. if (this._particleSystems.length === 0) {
  16514. return;
  16515. }
  16516. // Particles
  16517. var activeCamera = this._scene.activeCamera;
  16518. this._scene._particlesDuration.beginMonitoring();
  16519. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16520. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16521. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16522. continue;
  16523. }
  16524. var emitter = particleSystem.emitter;
  16525. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16526. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16527. }
  16528. }
  16529. this._scene._particlesDuration.endMonitoring(false);
  16530. };
  16531. RenderingGroup.prototype._renderSprites = function () {
  16532. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16533. return;
  16534. }
  16535. // Sprites
  16536. var activeCamera = this._scene.activeCamera;
  16537. this._scene._spritesDuration.beginMonitoring();
  16538. for (var id = 0; id < this._spriteManagers.length; id++) {
  16539. var spriteManager = this._spriteManagers.data[id];
  16540. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16541. spriteManager.render();
  16542. }
  16543. }
  16544. this._scene._spritesDuration.endMonitoring(false);
  16545. };
  16546. return RenderingGroup;
  16547. }());
  16548. BABYLON.RenderingGroup = RenderingGroup;
  16549. })(BABYLON || (BABYLON = {}));
  16550. //# sourceMappingURL=babylon.renderingGroup.js.map
  16551. var BABYLON;
  16552. (function (BABYLON) {
  16553. var ClickInfo = (function () {
  16554. function ClickInfo() {
  16555. this._singleClick = false;
  16556. this._doubleClick = false;
  16557. this._hasSwiped = false;
  16558. this._ignore = false;
  16559. }
  16560. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16561. get: function () {
  16562. return this._singleClick;
  16563. },
  16564. set: function (b) {
  16565. this._singleClick = b;
  16566. },
  16567. enumerable: true,
  16568. configurable: true
  16569. });
  16570. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16571. get: function () {
  16572. return this._doubleClick;
  16573. },
  16574. set: function (b) {
  16575. this._doubleClick = b;
  16576. },
  16577. enumerable: true,
  16578. configurable: true
  16579. });
  16580. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16581. get: function () {
  16582. return this._hasSwiped;
  16583. },
  16584. set: function (b) {
  16585. this._hasSwiped = b;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16591. get: function () {
  16592. return this._ignore;
  16593. },
  16594. set: function (b) {
  16595. this._ignore = b;
  16596. },
  16597. enumerable: true,
  16598. configurable: true
  16599. });
  16600. return ClickInfo;
  16601. }());
  16602. /**
  16603. * This class is used by the onRenderingGroupObservable
  16604. */
  16605. var RenderingGroupInfo = (function () {
  16606. function RenderingGroupInfo() {
  16607. }
  16608. /**
  16609. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16610. * This stage will be fired no matter what
  16611. */
  16612. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16613. /**
  16614. * Called before opaque object are rendered.
  16615. * This stage will be fired only if there's 3D Opaque content to render
  16616. */
  16617. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16618. /**
  16619. * Called after the opaque objects are rendered and before the transparent ones
  16620. * This stage will be fired only if there's 3D transparent content to render
  16621. */
  16622. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16623. /**
  16624. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16625. * This stage will be fired no matter what
  16626. */
  16627. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16628. return RenderingGroupInfo;
  16629. }());
  16630. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16631. /**
  16632. * Represents a scene to be rendered by the engine.
  16633. * @see http://doc.babylonjs.com/page.php?p=21911
  16634. */
  16635. var Scene = (function () {
  16636. /**
  16637. * @constructor
  16638. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16639. */
  16640. function Scene(engine) {
  16641. // Members
  16642. this.autoClear = true;
  16643. this.autoClearDepthAndStencil = true;
  16644. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16645. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16646. this.forceWireframe = false;
  16647. this._forcePointsCloud = false;
  16648. this.forceShowBoundingBoxes = false;
  16649. this.animationsEnabled = true;
  16650. this.constantlyUpdateMeshUnderPointer = false;
  16651. this.hoverCursor = "pointer";
  16652. this.defaultCursor = "";
  16653. // Metadata
  16654. this.metadata = null;
  16655. /**
  16656. * An event triggered when the scene is disposed.
  16657. * @type {BABYLON.Observable}
  16658. */
  16659. this.onDisposeObservable = new BABYLON.Observable();
  16660. /**
  16661. * An event triggered before rendering the scene
  16662. * @type {BABYLON.Observable}
  16663. */
  16664. this.onBeforeRenderObservable = new BABYLON.Observable();
  16665. /**
  16666. * An event triggered after rendering the scene
  16667. * @type {BABYLON.Observable}
  16668. */
  16669. this.onAfterRenderObservable = new BABYLON.Observable();
  16670. /**
  16671. * An event triggered when the scene is ready
  16672. * @type {BABYLON.Observable}
  16673. */
  16674. this.onReadyObservable = new BABYLON.Observable();
  16675. /**
  16676. * An event triggered before rendering a camera
  16677. * @type {BABYLON.Observable}
  16678. */
  16679. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16680. /**
  16681. * An event triggered after rendering a camera
  16682. * @type {BABYLON.Observable}
  16683. */
  16684. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16685. /**
  16686. * An event triggered when a camera is created
  16687. * @type {BABYLON.Observable}
  16688. */
  16689. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16690. /**
  16691. * An event triggered when a camera is removed
  16692. * @type {BABYLON.Observable}
  16693. */
  16694. this.onCameraRemovedObservable = new BABYLON.Observable();
  16695. /**
  16696. * An event triggered when a light is created
  16697. * @type {BABYLON.Observable}
  16698. */
  16699. this.onNewLightAddedObservable = new BABYLON.Observable();
  16700. /**
  16701. * An event triggered when a light is removed
  16702. * @type {BABYLON.Observable}
  16703. */
  16704. this.onLightRemovedObservable = new BABYLON.Observable();
  16705. /**
  16706. * An event triggered when a geometry is created
  16707. * @type {BABYLON.Observable}
  16708. */
  16709. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16710. /**
  16711. * An event triggered when a geometry is removed
  16712. * @type {BABYLON.Observable}
  16713. */
  16714. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16715. /**
  16716. * An event triggered when a mesh is created
  16717. * @type {BABYLON.Observable}
  16718. */
  16719. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16720. /**
  16721. * An event triggered when a mesh is removed
  16722. * @type {BABYLON.Observable}
  16723. */
  16724. this.onMeshRemovedObservable = new BABYLON.Observable();
  16725. /**
  16726. * An event triggered before calculating deterministic simulation step
  16727. * @type {BABYLON.Observable}
  16728. */
  16729. this.onBeforeStepObservable = new BABYLON.Observable();
  16730. /**
  16731. * An event triggered after calculating deterministic simulation step
  16732. * @type {BABYLON.Observable}
  16733. */
  16734. this.onAfterStepObservable = new BABYLON.Observable();
  16735. /**
  16736. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16737. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16738. * 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)
  16739. */
  16740. this.onRenderingGroupObservable = new BABYLON.Observable();
  16741. // Animations
  16742. this.animations = [];
  16743. /**
  16744. * 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).
  16745. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16746. */
  16747. this.onPrePointerObservable = new BABYLON.Observable();
  16748. /**
  16749. * Observable event triggered each time an input event is received from the rendering canvas
  16750. */
  16751. this.onPointerObservable = new BABYLON.Observable();
  16752. this._meshPickProceed = false;
  16753. this._previousHasSwiped = false;
  16754. this._currentPickResult = null;
  16755. this._previousPickResult = null;
  16756. this._totalPointersPressed = 0;
  16757. this._doubleClickOccured = false;
  16758. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16759. this.cameraToUseForPointers = null;
  16760. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16761. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16762. this._startingPointerTime = 0;
  16763. this._previousStartingPointerTime = 0;
  16764. // Deterministic lockstep
  16765. this._timeAccumulator = 0;
  16766. this._currentStepId = 0;
  16767. this._currentInternalStep = 0;
  16768. // Keyboard
  16769. /**
  16770. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16771. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16772. */
  16773. this.onPreKeyboardObservable = new BABYLON.Observable();
  16774. /**
  16775. * Observable event triggered each time an keyboard event is received from the hosting window
  16776. */
  16777. this.onKeyboardObservable = new BABYLON.Observable();
  16778. // Coordinate system
  16779. /**
  16780. * use right-handed coordinate system on this scene.
  16781. * @type {boolean}
  16782. */
  16783. this._useRightHandedSystem = false;
  16784. // Fog
  16785. this._fogEnabled = true;
  16786. this._fogMode = Scene.FOGMODE_NONE;
  16787. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16788. this.fogDensity = 0.1;
  16789. this.fogStart = 0;
  16790. this.fogEnd = 1000.0;
  16791. // Lights
  16792. /**
  16793. * is shadow enabled on this scene.
  16794. * @type {boolean}
  16795. */
  16796. this._shadowsEnabled = true;
  16797. /**
  16798. * is light enabled on this scene.
  16799. * @type {boolean}
  16800. */
  16801. this._lightsEnabled = true;
  16802. /**
  16803. * All of the lights added to this scene.
  16804. * @see BABYLON.Light
  16805. * @type {BABYLON.Light[]}
  16806. */
  16807. this.lights = new Array();
  16808. // Cameras
  16809. /** All of the cameras added to this scene. */
  16810. this.cameras = new Array();
  16811. /** All of the active cameras added to this scene. */
  16812. this.activeCameras = new Array();
  16813. // Meshes
  16814. /**
  16815. * All of the (abstract) meshes added to this scene.
  16816. * @see BABYLON.AbstractMesh
  16817. * @type {BABYLON.AbstractMesh[]}
  16818. */
  16819. this.meshes = new Array();
  16820. // Geometries
  16821. this._geometries = new Array();
  16822. this.materials = new Array();
  16823. this.multiMaterials = new Array();
  16824. // Textures
  16825. this._texturesEnabled = true;
  16826. this.textures = new Array();
  16827. // Particles
  16828. this.particlesEnabled = true;
  16829. this.particleSystems = new Array();
  16830. // Sprites
  16831. this.spritesEnabled = true;
  16832. this.spriteManagers = new Array();
  16833. // Layers
  16834. this.layers = new Array();
  16835. this.highlightLayers = new Array();
  16836. // Skeletons
  16837. this._skeletonsEnabled = true;
  16838. this.skeletons = new Array();
  16839. // Morph targets
  16840. this.morphTargetManagers = new Array();
  16841. // Lens flares
  16842. this.lensFlaresEnabled = true;
  16843. this.lensFlareSystems = new Array();
  16844. // Collisions
  16845. this.collisionsEnabled = true;
  16846. /** Defines the gravity applied to this scene */
  16847. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16848. // Postprocesses
  16849. this.postProcesses = new Array();
  16850. this.postProcessesEnabled = true;
  16851. // Customs render targets
  16852. this.renderTargetsEnabled = true;
  16853. this.dumpNextRenderTargets = false;
  16854. this.customRenderTargets = new Array();
  16855. // Imported meshes
  16856. this.importedMeshesFiles = new Array();
  16857. // Probes
  16858. this.probesEnabled = true;
  16859. this.reflectionProbes = new Array();
  16860. this._actionManagers = new Array();
  16861. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16862. // Procedural textures
  16863. this.proceduralTexturesEnabled = true;
  16864. this._proceduralTextures = new Array();
  16865. this.soundTracks = new Array();
  16866. this._audioEnabled = true;
  16867. this._headphone = false;
  16868. // Performance counters
  16869. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16870. this._totalLightsCounter = new BABYLON.PerfCounter();
  16871. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16872. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16873. this._totalVertices = new BABYLON.PerfCounter();
  16874. this._activeIndices = new BABYLON.PerfCounter();
  16875. this._activeParticles = new BABYLON.PerfCounter();
  16876. this._interFrameDuration = new BABYLON.PerfCounter();
  16877. this._lastFrameDuration = new BABYLON.PerfCounter();
  16878. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16879. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16880. this._particlesDuration = new BABYLON.PerfCounter();
  16881. this._renderDuration = new BABYLON.PerfCounter();
  16882. this._spritesDuration = new BABYLON.PerfCounter();
  16883. this._activeBones = new BABYLON.PerfCounter();
  16884. this._animationTime = 0;
  16885. this.animationTimeScale = 1;
  16886. this._renderId = 0;
  16887. this._executeWhenReadyTimeoutId = -1;
  16888. this._intermediateRendering = false;
  16889. this._viewUpdateFlag = -1;
  16890. this._projectionUpdateFlag = -1;
  16891. this._alternateViewUpdateFlag = -1;
  16892. this._alternateProjectionUpdateFlag = -1;
  16893. this._toBeDisposed = new BABYLON.SmartArray(256);
  16894. this._pendingData = new Array();
  16895. this._activeMeshes = new BABYLON.SmartArray(256);
  16896. this._processedMaterials = new BABYLON.SmartArray(256);
  16897. this._renderTargets = new BABYLON.SmartArray(256);
  16898. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16899. this._activeSkeletons = new BABYLON.SmartArray(32);
  16900. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16901. this._activeAnimatables = new Array();
  16902. this._transformMatrix = BABYLON.Matrix.Zero();
  16903. this._useAlternateCameraConfiguration = false;
  16904. this._alternateRendering = false;
  16905. this.requireLightSorting = false;
  16906. this._activeMeshesFrozen = false;
  16907. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16908. this._engine.scenes.push(this);
  16909. this._uid = null;
  16910. this._renderingManager = new BABYLON.RenderingManager(this);
  16911. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16912. if (BABYLON.OutlineRenderer) {
  16913. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16914. }
  16915. if (BABYLON.Tools.IsWindowObjectExist()) {
  16916. this.attachControl();
  16917. }
  16918. //simplification queue
  16919. if (BABYLON.SimplificationQueue) {
  16920. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16921. }
  16922. //collision coordinator initialization. For now legacy per default.
  16923. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16924. // Uniform Buffer
  16925. this._createUbo();
  16926. // Default Image processing definition.
  16927. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16928. }
  16929. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16930. /** The fog is deactivated */
  16931. get: function () {
  16932. return Scene._FOGMODE_NONE;
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16938. /** The fog density is following an exponential function */
  16939. get: function () {
  16940. return Scene._FOGMODE_EXP;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16946. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16947. get: function () {
  16948. return Scene._FOGMODE_EXP2;
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16954. /** The fog density is following a linear function. */
  16955. get: function () {
  16956. return Scene._FOGMODE_LINEAR;
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16962. /**
  16963. * Texture used in all pbr material as the reflection texture.
  16964. * As in the majority of the scene they are the same (exception for multi room and so on),
  16965. * this is easier to reference from here than from all the materials.
  16966. */
  16967. get: function () {
  16968. return this._environmentTexture;
  16969. },
  16970. /**
  16971. * Texture used in all pbr material as the reflection texture.
  16972. * As in the majority of the scene they are the same (exception for multi room and so on),
  16973. * this is easier to set here than in all the materials.
  16974. */
  16975. set: function (value) {
  16976. this._environmentTexture = value;
  16977. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16983. /**
  16984. * Default image processing configuration used either in the rendering
  16985. * Forward main pass or through the imageProcessingPostProcess if present.
  16986. * As in the majority of the scene they are the same (exception for multi camera),
  16987. * this is easier to reference from here than from all the materials and post process.
  16988. *
  16989. * No setter as we it is a shared configuration, you can set the values instead.
  16990. */
  16991. get: function () {
  16992. return this._imageProcessingConfiguration;
  16993. },
  16994. enumerable: true,
  16995. configurable: true
  16996. });
  16997. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16998. get: function () {
  16999. return this._forcePointsCloud;
  17000. },
  17001. set: function (value) {
  17002. if (this._forcePointsCloud === value) {
  17003. return;
  17004. }
  17005. this._forcePointsCloud = value;
  17006. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(Scene.prototype, "onDispose", {
  17012. /** A function to be executed when this scene is disposed. */
  17013. set: function (callback) {
  17014. if (this._onDisposeObserver) {
  17015. this.onDisposeObservable.remove(this._onDisposeObserver);
  17016. }
  17017. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17018. },
  17019. enumerable: true,
  17020. configurable: true
  17021. });
  17022. Object.defineProperty(Scene.prototype, "beforeRender", {
  17023. /** A function to be executed before rendering this scene */
  17024. set: function (callback) {
  17025. if (this._onBeforeRenderObserver) {
  17026. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17027. }
  17028. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17029. },
  17030. enumerable: true,
  17031. configurable: true
  17032. });
  17033. Object.defineProperty(Scene.prototype, "afterRender", {
  17034. /** A function to be executed after rendering this scene */
  17035. set: function (callback) {
  17036. if (this._onAfterRenderObserver) {
  17037. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17038. }
  17039. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17040. },
  17041. enumerable: true,
  17042. configurable: true
  17043. });
  17044. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17045. set: function (callback) {
  17046. if (this._onBeforeCameraRenderObserver) {
  17047. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17048. }
  17049. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17050. },
  17051. enumerable: true,
  17052. configurable: true
  17053. });
  17054. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17055. set: function (callback) {
  17056. if (this._onAfterCameraRenderObserver) {
  17057. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17058. }
  17059. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17065. get: function () {
  17066. if (!this._gamepadManager) {
  17067. this._gamepadManager = new BABYLON.GamepadManager();
  17068. }
  17069. return this._gamepadManager;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17075. get: function () {
  17076. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17082. get: function () {
  17083. return this._useRightHandedSystem;
  17084. },
  17085. set: function (value) {
  17086. if (this._useRightHandedSystem === value) {
  17087. return;
  17088. }
  17089. this._useRightHandedSystem = value;
  17090. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Scene.prototype.setStepId = function (newStepId) {
  17096. this._currentStepId = newStepId;
  17097. };
  17098. ;
  17099. Scene.prototype.getStepId = function () {
  17100. return this._currentStepId;
  17101. };
  17102. ;
  17103. Scene.prototype.getInternalStep = function () {
  17104. return this._currentInternalStep;
  17105. };
  17106. ;
  17107. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17108. get: function () {
  17109. return this._fogEnabled;
  17110. },
  17111. /**
  17112. * is fog enabled on this scene.
  17113. */
  17114. set: function (value) {
  17115. if (this._fogEnabled === value) {
  17116. return;
  17117. }
  17118. this._fogEnabled = value;
  17119. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(Scene.prototype, "fogMode", {
  17125. get: function () {
  17126. return this._fogMode;
  17127. },
  17128. set: function (value) {
  17129. if (this._fogMode === value) {
  17130. return;
  17131. }
  17132. this._fogMode = value;
  17133. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17134. },
  17135. enumerable: true,
  17136. configurable: true
  17137. });
  17138. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17139. get: function () {
  17140. return this._shadowsEnabled;
  17141. },
  17142. set: function (value) {
  17143. if (this._shadowsEnabled === value) {
  17144. return;
  17145. }
  17146. this._shadowsEnabled = value;
  17147. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17148. },
  17149. enumerable: true,
  17150. configurable: true
  17151. });
  17152. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17153. get: function () {
  17154. return this._lightsEnabled;
  17155. },
  17156. set: function (value) {
  17157. if (this._lightsEnabled === value) {
  17158. return;
  17159. }
  17160. this._lightsEnabled = value;
  17161. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17162. },
  17163. enumerable: true,
  17164. configurable: true
  17165. });
  17166. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17167. /** The default material used on meshes when no material is affected */
  17168. get: function () {
  17169. if (!this._defaultMaterial) {
  17170. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17171. }
  17172. return this._defaultMaterial;
  17173. },
  17174. /** The default material used on meshes when no material is affected */
  17175. set: function (value) {
  17176. this._defaultMaterial = value;
  17177. },
  17178. enumerable: true,
  17179. configurable: true
  17180. });
  17181. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17182. get: function () {
  17183. return this._texturesEnabled;
  17184. },
  17185. set: function (value) {
  17186. if (this._texturesEnabled === value) {
  17187. return;
  17188. }
  17189. this._texturesEnabled = value;
  17190. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17191. },
  17192. enumerable: true,
  17193. configurable: true
  17194. });
  17195. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17196. get: function () {
  17197. return this._skeletonsEnabled;
  17198. },
  17199. set: function (value) {
  17200. if (this._skeletonsEnabled === value) {
  17201. return;
  17202. }
  17203. this._skeletonsEnabled = value;
  17204. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17205. },
  17206. enumerable: true,
  17207. configurable: true
  17208. });
  17209. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17210. get: function () {
  17211. if (!this._postProcessRenderPipelineManager) {
  17212. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17213. }
  17214. return this._postProcessRenderPipelineManager;
  17215. },
  17216. enumerable: true,
  17217. configurable: true
  17218. });
  17219. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17220. get: function () {
  17221. if (!this._mainSoundTrack) {
  17222. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17223. }
  17224. return this._mainSoundTrack;
  17225. },
  17226. enumerable: true,
  17227. configurable: true
  17228. });
  17229. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17230. get: function () {
  17231. return this._alternateRendering;
  17232. },
  17233. enumerable: true,
  17234. configurable: true
  17235. });
  17236. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17237. get: function () {
  17238. return this._frustumPlanes;
  17239. },
  17240. enumerable: true,
  17241. configurable: true
  17242. });
  17243. Object.defineProperty(Scene.prototype, "debugLayer", {
  17244. // Properties
  17245. get: function () {
  17246. if (!this._debugLayer) {
  17247. this._debugLayer = new BABYLON.DebugLayer(this);
  17248. }
  17249. return this._debugLayer;
  17250. },
  17251. enumerable: true,
  17252. configurable: true
  17253. });
  17254. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17255. get: function () {
  17256. return this._workerCollisions;
  17257. },
  17258. set: function (enabled) {
  17259. if (!BABYLON.CollisionCoordinatorLegacy) {
  17260. return;
  17261. }
  17262. enabled = (enabled && !!Worker);
  17263. this._workerCollisions = enabled;
  17264. if (this.collisionCoordinator) {
  17265. this.collisionCoordinator.destroy();
  17266. }
  17267. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17268. this.collisionCoordinator.init(this);
  17269. },
  17270. enumerable: true,
  17271. configurable: true
  17272. });
  17273. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17274. get: function () {
  17275. return this._selectionOctree;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17281. /**
  17282. * The mesh that is currently under the pointer.
  17283. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17284. */
  17285. get: function () {
  17286. return this._pointerOverMesh;
  17287. },
  17288. enumerable: true,
  17289. configurable: true
  17290. });
  17291. Object.defineProperty(Scene.prototype, "pointerX", {
  17292. /**
  17293. * Current on-screen X position of the pointer
  17294. * @return {number} X position of the pointer
  17295. */
  17296. get: function () {
  17297. return this._pointerX;
  17298. },
  17299. enumerable: true,
  17300. configurable: true
  17301. });
  17302. Object.defineProperty(Scene.prototype, "pointerY", {
  17303. /**
  17304. * Current on-screen Y position of the pointer
  17305. * @return {number} Y position of the pointer
  17306. */
  17307. get: function () {
  17308. return this._pointerY;
  17309. },
  17310. enumerable: true,
  17311. configurable: true
  17312. });
  17313. Scene.prototype.getCachedMaterial = function () {
  17314. return this._cachedMaterial;
  17315. };
  17316. Scene.prototype.getCachedEffect = function () {
  17317. return this._cachedEffect;
  17318. };
  17319. Scene.prototype.getCachedVisibility = function () {
  17320. return this._cachedVisibility;
  17321. };
  17322. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17323. if (visibility === void 0) { visibility = 1; }
  17324. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17325. };
  17326. Scene.prototype.getBoundingBoxRenderer = function () {
  17327. if (!this._boundingBoxRenderer) {
  17328. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17329. }
  17330. return this._boundingBoxRenderer;
  17331. };
  17332. Scene.prototype.getOutlineRenderer = function () {
  17333. return this._outlineRenderer;
  17334. };
  17335. Scene.prototype.getEngine = function () {
  17336. return this._engine;
  17337. };
  17338. Scene.prototype.getTotalVertices = function () {
  17339. return this._totalVertices.current;
  17340. };
  17341. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17342. get: function () {
  17343. return this._totalVertices;
  17344. },
  17345. enumerable: true,
  17346. configurable: true
  17347. });
  17348. Scene.prototype.getActiveIndices = function () {
  17349. return this._activeIndices.current;
  17350. };
  17351. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17352. get: function () {
  17353. return this._activeIndices;
  17354. },
  17355. enumerable: true,
  17356. configurable: true
  17357. });
  17358. Scene.prototype.getActiveParticles = function () {
  17359. return this._activeParticles.current;
  17360. };
  17361. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17362. get: function () {
  17363. return this._activeParticles;
  17364. },
  17365. enumerable: true,
  17366. configurable: true
  17367. });
  17368. Scene.prototype.getActiveBones = function () {
  17369. return this._activeBones.current;
  17370. };
  17371. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17372. get: function () {
  17373. return this._activeBones;
  17374. },
  17375. enumerable: true,
  17376. configurable: true
  17377. });
  17378. // Stats
  17379. Scene.prototype.getInterFramePerfCounter = function () {
  17380. return this._interFrameDuration.current;
  17381. };
  17382. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17383. get: function () {
  17384. return this._interFrameDuration;
  17385. },
  17386. enumerable: true,
  17387. configurable: true
  17388. });
  17389. Scene.prototype.getLastFrameDuration = function () {
  17390. return this._lastFrameDuration.current;
  17391. };
  17392. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17393. get: function () {
  17394. return this._lastFrameDuration;
  17395. },
  17396. enumerable: true,
  17397. configurable: true
  17398. });
  17399. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17400. return this._evaluateActiveMeshesDuration.current;
  17401. };
  17402. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17403. get: function () {
  17404. return this._evaluateActiveMeshesDuration;
  17405. },
  17406. enumerable: true,
  17407. configurable: true
  17408. });
  17409. Scene.prototype.getActiveMeshes = function () {
  17410. return this._activeMeshes;
  17411. };
  17412. Scene.prototype.getRenderTargetsDuration = function () {
  17413. return this._renderTargetsDuration.current;
  17414. };
  17415. Scene.prototype.getRenderDuration = function () {
  17416. return this._renderDuration.current;
  17417. };
  17418. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17419. get: function () {
  17420. return this._renderDuration;
  17421. },
  17422. enumerable: true,
  17423. configurable: true
  17424. });
  17425. Scene.prototype.getParticlesDuration = function () {
  17426. return this._particlesDuration.current;
  17427. };
  17428. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17429. get: function () {
  17430. return this._particlesDuration;
  17431. },
  17432. enumerable: true,
  17433. configurable: true
  17434. });
  17435. Scene.prototype.getSpritesDuration = function () {
  17436. return this._spritesDuration.current;
  17437. };
  17438. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17439. get: function () {
  17440. return this._spritesDuration;
  17441. },
  17442. enumerable: true,
  17443. configurable: true
  17444. });
  17445. Scene.prototype.getAnimationRatio = function () {
  17446. return this._animationRatio;
  17447. };
  17448. Scene.prototype.getRenderId = function () {
  17449. return this._renderId;
  17450. };
  17451. Scene.prototype.incrementRenderId = function () {
  17452. this._renderId++;
  17453. };
  17454. Scene.prototype._updatePointerPosition = function (evt) {
  17455. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17456. this._pointerX = evt.clientX - canvasRect.left;
  17457. this._pointerY = evt.clientY - canvasRect.top;
  17458. this._unTranslatedPointerX = this._pointerX;
  17459. this._unTranslatedPointerY = this._pointerY;
  17460. };
  17461. Scene.prototype._createUbo = function () {
  17462. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17463. this._sceneUbo.addUniform("viewProjection", 16);
  17464. this._sceneUbo.addUniform("view", 16);
  17465. };
  17466. Scene.prototype._createAlternateUbo = function () {
  17467. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17468. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17469. this._alternateSceneUbo.addUniform("view", 16);
  17470. };
  17471. // Pointers handling
  17472. /**
  17473. * Use this method to simulate a pointer move on a mesh
  17474. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17475. */
  17476. Scene.prototype.simulatePointerMove = function (pickResult) {
  17477. var evt = new PointerEvent("pointermove");
  17478. return this._processPointerMove(pickResult, evt);
  17479. };
  17480. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17481. var canvas = this._engine.getRenderingCanvas();
  17482. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17483. this.setPointerOverSprite(null);
  17484. this.setPointerOverMesh(pickResult.pickedMesh);
  17485. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17486. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17487. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17488. }
  17489. else {
  17490. canvas.style.cursor = this.hoverCursor;
  17491. }
  17492. }
  17493. else {
  17494. canvas.style.cursor = this.defaultCursor;
  17495. }
  17496. }
  17497. else {
  17498. this.setPointerOverMesh(null);
  17499. // Sprites
  17500. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17501. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17502. this.setPointerOverSprite(pickResult.pickedSprite);
  17503. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17504. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17505. }
  17506. else {
  17507. canvas.style.cursor = this.hoverCursor;
  17508. }
  17509. }
  17510. else {
  17511. this.setPointerOverSprite(null);
  17512. // Restore pointer
  17513. canvas.style.cursor = this.defaultCursor;
  17514. }
  17515. }
  17516. if (this.onPointerMove) {
  17517. this.onPointerMove(evt, pickResult);
  17518. }
  17519. if (this.onPointerObservable.hasObservers()) {
  17520. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17521. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17522. this.onPointerObservable.notifyObservers(pi, type);
  17523. }
  17524. return this;
  17525. };
  17526. /**
  17527. * Use this method to simulate a pointer down on a mesh
  17528. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17529. */
  17530. Scene.prototype.simulatePointerDown = function (pickResult) {
  17531. var evt = new PointerEvent("pointerdown");
  17532. return this._processPointerDown(pickResult, evt);
  17533. };
  17534. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17535. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17536. this._pickedDownMesh = pickResult.pickedMesh;
  17537. var actionManager = pickResult.pickedMesh.actionManager;
  17538. if (actionManager) {
  17539. if (actionManager.hasPickTriggers) {
  17540. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17541. switch (evt.button) {
  17542. case 0:
  17543. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17544. break;
  17545. case 1:
  17546. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17547. break;
  17548. case 2:
  17549. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17550. break;
  17551. }
  17552. }
  17553. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17554. window.setTimeout((function () {
  17555. var _this = this;
  17556. 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);
  17557. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17558. if (this._totalPointersPressed !== 0 &&
  17559. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17560. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17561. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17562. this._startingPointerTime = 0;
  17563. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17564. }
  17565. }
  17566. }).bind(this), Scene.LongPressDelay);
  17567. }
  17568. }
  17569. }
  17570. if (this.onPointerDown) {
  17571. this.onPointerDown(evt, pickResult);
  17572. }
  17573. if (this.onPointerObservable.hasObservers()) {
  17574. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17575. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17576. this.onPointerObservable.notifyObservers(pi, type);
  17577. }
  17578. return this;
  17579. };
  17580. /**
  17581. * Use this method to simulate a pointer up on a mesh
  17582. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17583. */
  17584. Scene.prototype.simulatePointerUp = function (pickResult) {
  17585. var evt = new PointerEvent("pointerup");
  17586. var clickInfo = new ClickInfo();
  17587. clickInfo.singleClick = true;
  17588. return this._processPointerUp(pickResult, evt, clickInfo);
  17589. };
  17590. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17591. if (pickResult && pickResult && pickResult.pickedMesh) {
  17592. this._pickedUpMesh = pickResult.pickedMesh;
  17593. if (this._pickedDownMesh === this._pickedUpMesh) {
  17594. if (this.onPointerPick) {
  17595. this.onPointerPick(evt, pickResult);
  17596. }
  17597. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17598. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17599. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17600. this.onPointerObservable.notifyObservers(pi, type);
  17601. }
  17602. }
  17603. if (pickResult.pickedMesh.actionManager) {
  17604. if (clickInfo.ignore) {
  17605. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17606. }
  17607. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17608. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17609. }
  17610. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17611. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17612. }
  17613. }
  17614. }
  17615. if (this._pickedDownMesh &&
  17616. this._pickedDownMesh.actionManager &&
  17617. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17618. this._pickedDownMesh !== this._pickedUpMesh) {
  17619. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17620. }
  17621. if (this.onPointerUp) {
  17622. this.onPointerUp(evt, pickResult);
  17623. }
  17624. if (this.onPointerObservable.hasObservers()) {
  17625. if (!clickInfo.ignore) {
  17626. if (!clickInfo.hasSwiped) {
  17627. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17628. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17629. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17630. this.onPointerObservable.notifyObservers(pi, type);
  17631. }
  17632. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17633. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17634. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17635. this.onPointerObservable.notifyObservers(pi, type);
  17636. }
  17637. }
  17638. }
  17639. else {
  17640. var type = BABYLON.PointerEventTypes.POINTERUP;
  17641. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17642. this.onPointerObservable.notifyObservers(pi, type);
  17643. }
  17644. }
  17645. return this;
  17646. };
  17647. /**
  17648. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17649. * @param attachUp defines if you want to attach events to pointerup
  17650. * @param attachDown defines if you want to attach events to pointerdown
  17651. * @param attachMove defines if you want to attach events to pointermove
  17652. */
  17653. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17654. var _this = this;
  17655. if (attachUp === void 0) { attachUp = true; }
  17656. if (attachDown === void 0) { attachDown = true; }
  17657. if (attachMove === void 0) { attachMove = true; }
  17658. this._initActionManager = function (act, clickInfo) {
  17659. if (!_this._meshPickProceed) {
  17660. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17661. _this._currentPickResult = pickResult;
  17662. if (pickResult) {
  17663. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17664. }
  17665. _this._meshPickProceed = true;
  17666. }
  17667. return act;
  17668. };
  17669. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17670. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17671. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17672. btn !== _this._previousButtonPressed) {
  17673. _this._doubleClickOccured = false;
  17674. clickInfo.singleClick = true;
  17675. clickInfo.ignore = false;
  17676. cb(clickInfo, _this._currentPickResult);
  17677. }
  17678. };
  17679. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17680. var clickInfo = new ClickInfo();
  17681. _this._currentPickResult = null;
  17682. var act;
  17683. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17684. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17685. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17686. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17687. act = _this._initActionManager(act, clickInfo);
  17688. if (act)
  17689. checkPicking = act.hasPickTriggers;
  17690. }
  17691. if (checkPicking) {
  17692. var btn = evt.button;
  17693. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17694. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17695. if (!clickInfo.hasSwiped) {
  17696. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17697. if (!checkSingleClickImmediately) {
  17698. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17699. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17700. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17701. act = _this._initActionManager(act, clickInfo);
  17702. if (act)
  17703. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17704. }
  17705. }
  17706. if (checkSingleClickImmediately) {
  17707. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17708. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17709. btn !== _this._previousButtonPressed) {
  17710. clickInfo.singleClick = true;
  17711. cb(clickInfo, _this._currentPickResult);
  17712. }
  17713. }
  17714. else {
  17715. // wait that no double click has been raised during the double click delay
  17716. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17717. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17718. }
  17719. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17720. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17721. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17722. act = _this._initActionManager(act, clickInfo);
  17723. if (act)
  17724. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17725. }
  17726. if (checkDoubleClick) {
  17727. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17728. if (btn === _this._previousButtonPressed &&
  17729. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17730. !_this._doubleClickOccured) {
  17731. // pointer has not moved for 2 clicks, it's a double click
  17732. if (!clickInfo.hasSwiped &&
  17733. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17734. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17735. _this._previousStartingPointerTime = 0;
  17736. _this._doubleClickOccured = true;
  17737. clickInfo.doubleClick = true;
  17738. clickInfo.ignore = false;
  17739. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  17740. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17741. }
  17742. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17743. cb(clickInfo, _this._currentPickResult);
  17744. }
  17745. else {
  17746. _this._doubleClickOccured = false;
  17747. _this._previousStartingPointerTime = _this._startingPointerTime;
  17748. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17749. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17750. _this._previousButtonPressed = btn;
  17751. _this._previousHasSwiped = clickInfo.hasSwiped;
  17752. if (Scene.ExclusiveDoubleClickMode) {
  17753. if (_this._previousDelayedSimpleClickTimeout) {
  17754. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17755. }
  17756. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17757. cb(clickInfo, _this._previousPickResult);
  17758. }
  17759. else {
  17760. cb(clickInfo, _this._currentPickResult);
  17761. }
  17762. }
  17763. }
  17764. else {
  17765. _this._doubleClickOccured = false;
  17766. _this._previousStartingPointerTime = _this._startingPointerTime;
  17767. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17768. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17769. _this._previousButtonPressed = btn;
  17770. _this._previousHasSwiped = clickInfo.hasSwiped;
  17771. }
  17772. }
  17773. }
  17774. }
  17775. clickInfo.ignore = true;
  17776. cb(clickInfo, _this._currentPickResult);
  17777. };
  17778. this._spritePredicate = function (sprite) {
  17779. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17780. };
  17781. this._onPointerMove = function (evt) {
  17782. _this._updatePointerPosition(evt);
  17783. // PreObservable support
  17784. if (_this.onPrePointerObservable.hasObservers()) {
  17785. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17786. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17787. _this.onPrePointerObservable.notifyObservers(pi, type);
  17788. if (pi.skipOnPointerObservable) {
  17789. return;
  17790. }
  17791. }
  17792. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17793. return;
  17794. }
  17795. if (!_this.pointerMovePredicate) {
  17796. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17797. }
  17798. // Meshes
  17799. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17800. _this._processPointerMove(pickResult, evt);
  17801. };
  17802. this._onPointerDown = function (evt) {
  17803. _this._totalPointersPressed++;
  17804. _this._pickedDownMesh = null;
  17805. _this._meshPickProceed = false;
  17806. _this._updatePointerPosition(evt);
  17807. // PreObservable support
  17808. if (_this.onPrePointerObservable.hasObservers()) {
  17809. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17810. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17811. _this.onPrePointerObservable.notifyObservers(pi, type);
  17812. if (pi.skipOnPointerObservable) {
  17813. return;
  17814. }
  17815. }
  17816. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17817. return;
  17818. }
  17819. _this._startingPointerPosition.x = _this._pointerX;
  17820. _this._startingPointerPosition.y = _this._pointerY;
  17821. _this._startingPointerTime = new Date().getTime();
  17822. if (!_this.pointerDownPredicate) {
  17823. _this.pointerDownPredicate = function (mesh) {
  17824. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17825. };
  17826. }
  17827. // Meshes
  17828. _this._pickedDownMesh = null;
  17829. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17830. _this._processPointerDown(pickResult, evt);
  17831. // Sprites
  17832. _this._pickedDownSprite = null;
  17833. if (_this.spriteManagers.length > 0) {
  17834. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17835. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17836. if (pickResult.pickedSprite.actionManager) {
  17837. _this._pickedDownSprite = pickResult.pickedSprite;
  17838. switch (evt.button) {
  17839. case 0:
  17840. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17841. break;
  17842. case 1:
  17843. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17844. break;
  17845. case 2:
  17846. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17847. break;
  17848. }
  17849. if (pickResult.pickedSprite.actionManager) {
  17850. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17851. }
  17852. }
  17853. }
  17854. }
  17855. };
  17856. this._onPointerUp = function (evt) {
  17857. if (_this._totalPointersPressed === 0) {
  17858. return; // So we need to test it the pointer down was pressed before.
  17859. }
  17860. _this._totalPointersPressed--;
  17861. _this._pickedUpMesh = null;
  17862. _this._meshPickProceed = false;
  17863. _this._updatePointerPosition(evt);
  17864. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17865. // PreObservable support
  17866. if (this.onPrePointerObservable.hasObservers()) {
  17867. if (!clickInfo.ignore) {
  17868. if (!clickInfo.hasSwiped) {
  17869. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17870. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17871. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17872. this.onPrePointerObservable.notifyObservers(pi, type);
  17873. if (pi.skipOnPointerObservable) {
  17874. return;
  17875. }
  17876. }
  17877. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17878. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17879. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17880. this.onPrePointerObservable.notifyObservers(pi, type);
  17881. if (pi.skipOnPointerObservable) {
  17882. return;
  17883. }
  17884. }
  17885. }
  17886. }
  17887. else {
  17888. var type = BABYLON.PointerEventTypes.POINTERUP;
  17889. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17890. this.onPrePointerObservable.notifyObservers(pi, type);
  17891. if (pi.skipOnPointerObservable) {
  17892. return;
  17893. }
  17894. }
  17895. }
  17896. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17897. return;
  17898. }
  17899. if (!this.pointerUpPredicate) {
  17900. this.pointerUpPredicate = function (mesh) {
  17901. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17902. };
  17903. }
  17904. // Meshes
  17905. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17906. this._initActionManager(null, clickInfo);
  17907. }
  17908. if (!pickResult) {
  17909. pickResult = this._currentPickResult;
  17910. }
  17911. this._processPointerUp(pickResult, evt, clickInfo);
  17912. // Sprites
  17913. if (this.spriteManagers.length > 0) {
  17914. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17915. if (pickResult.hit && pickResult.pickedSprite) {
  17916. if (pickResult.pickedSprite.actionManager) {
  17917. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17918. if (pickResult.pickedSprite.actionManager) {
  17919. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17920. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17921. }
  17922. }
  17923. }
  17924. }
  17925. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17926. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17927. }
  17928. }
  17929. this._previousPickResult = this._currentPickResult;
  17930. }).bind(_this));
  17931. };
  17932. this._onKeyDown = function (evt) {
  17933. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17934. if (_this.onPreKeyboardObservable.hasObservers()) {
  17935. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17936. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17937. if (pi.skipOnPointerObservable) {
  17938. return;
  17939. }
  17940. }
  17941. if (_this.onKeyboardObservable.hasObservers()) {
  17942. var pi = new BABYLON.KeyboardInfo(type, evt);
  17943. _this.onKeyboardObservable.notifyObservers(pi, type);
  17944. }
  17945. if (_this.actionManager) {
  17946. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17947. }
  17948. };
  17949. this._onKeyUp = function (evt) {
  17950. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17951. if (_this.onPreKeyboardObservable.hasObservers()) {
  17952. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17953. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17954. if (pi.skipOnPointerObservable) {
  17955. return;
  17956. }
  17957. }
  17958. if (_this.onKeyboardObservable.hasObservers()) {
  17959. var pi = new BABYLON.KeyboardInfo(type, evt);
  17960. _this.onKeyboardObservable.notifyObservers(pi, type);
  17961. }
  17962. if (_this.actionManager) {
  17963. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17964. }
  17965. };
  17966. var engine = this.getEngine();
  17967. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17968. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17969. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17970. });
  17971. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17972. canvas.removeEventListener("keydown", _this._onKeyDown);
  17973. canvas.removeEventListener("keyup", _this._onKeyUp);
  17974. });
  17975. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17976. var canvas = this._engine.getRenderingCanvas();
  17977. if (attachMove) {
  17978. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17979. // Wheel
  17980. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17981. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17982. }
  17983. if (attachDown) {
  17984. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17985. }
  17986. if (attachUp) {
  17987. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17988. }
  17989. canvas.tabIndex = 1;
  17990. };
  17991. Scene.prototype.detachControl = function () {
  17992. var engine = this.getEngine();
  17993. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17994. var canvas = engine.getRenderingCanvas();
  17995. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17996. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17997. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17998. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17999. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18000. // Wheel
  18001. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18002. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18003. // Keyboard
  18004. canvas.removeEventListener("keydown", this._onKeyDown);
  18005. canvas.removeEventListener("keyup", this._onKeyUp);
  18006. // Observables
  18007. this.onKeyboardObservable.clear();
  18008. this.onPreKeyboardObservable.clear();
  18009. this.onPointerObservable.clear();
  18010. this.onPrePointerObservable.clear();
  18011. };
  18012. // Ready
  18013. Scene.prototype.isReady = function () {
  18014. if (this._pendingData.length > 0) {
  18015. return false;
  18016. }
  18017. var index;
  18018. // Geometries
  18019. for (index = 0; index < this._geometries.length; index++) {
  18020. var geometry = this._geometries[index];
  18021. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18022. return false;
  18023. }
  18024. }
  18025. // Meshes
  18026. for (index = 0; index < this.meshes.length; index++) {
  18027. var mesh = this.meshes[index];
  18028. if (!mesh.isEnabled()) {
  18029. continue;
  18030. }
  18031. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18032. continue;
  18033. }
  18034. if (!mesh.isReady()) {
  18035. return false;
  18036. }
  18037. var mat = mesh.material;
  18038. if (mat) {
  18039. if (!mat.isReady(mesh)) {
  18040. return false;
  18041. }
  18042. }
  18043. }
  18044. return true;
  18045. };
  18046. Scene.prototype.resetCachedMaterial = function () {
  18047. this._cachedMaterial = null;
  18048. this._cachedEffect = null;
  18049. this._cachedVisibility = null;
  18050. };
  18051. Scene.prototype.registerBeforeRender = function (func) {
  18052. this.onBeforeRenderObservable.add(func);
  18053. };
  18054. Scene.prototype.unregisterBeforeRender = function (func) {
  18055. this.onBeforeRenderObservable.removeCallback(func);
  18056. };
  18057. Scene.prototype.registerAfterRender = function (func) {
  18058. this.onAfterRenderObservable.add(func);
  18059. };
  18060. Scene.prototype.unregisterAfterRender = function (func) {
  18061. this.onAfterRenderObservable.removeCallback(func);
  18062. };
  18063. Scene.prototype._addPendingData = function (data) {
  18064. this._pendingData.push(data);
  18065. };
  18066. Scene.prototype._removePendingData = function (data) {
  18067. var index = this._pendingData.indexOf(data);
  18068. if (index !== -1) {
  18069. this._pendingData.splice(index, 1);
  18070. }
  18071. };
  18072. Scene.prototype.getWaitingItemsCount = function () {
  18073. return this._pendingData.length;
  18074. };
  18075. /**
  18076. * Registers a function to be executed when the scene is ready.
  18077. * @param {Function} func - the function to be executed.
  18078. */
  18079. Scene.prototype.executeWhenReady = function (func) {
  18080. var _this = this;
  18081. this.onReadyObservable.add(func);
  18082. if (this._executeWhenReadyTimeoutId !== -1) {
  18083. return;
  18084. }
  18085. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18086. _this._checkIsReady();
  18087. }, 150);
  18088. };
  18089. Scene.prototype._checkIsReady = function () {
  18090. var _this = this;
  18091. if (this.isReady()) {
  18092. this.onReadyObservable.notifyObservers(this);
  18093. this.onReadyObservable.clear();
  18094. this._executeWhenReadyTimeoutId = -1;
  18095. return;
  18096. }
  18097. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18098. _this._checkIsReady();
  18099. }, 150);
  18100. };
  18101. // Animations
  18102. /**
  18103. * Will start the animation sequence of a given target
  18104. * @param target - the target
  18105. * @param {number} from - from which frame should animation start
  18106. * @param {number} to - till which frame should animation run.
  18107. * @param {boolean} [loop] - should the animation loop
  18108. * @param {number} [speedRatio] - the speed in which to run the animation
  18109. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18110. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18111. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18112. * See BABYLON.Animatable
  18113. */
  18114. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18115. if (speedRatio === void 0) { speedRatio = 1.0; }
  18116. if (from > to && speedRatio > 0) {
  18117. speedRatio *= -1;
  18118. }
  18119. this.stopAnimation(target);
  18120. if (!animatable) {
  18121. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18122. }
  18123. // Local animations
  18124. if (target.animations) {
  18125. animatable.appendAnimations(target, target.animations);
  18126. }
  18127. // Children animations
  18128. if (target.getAnimatables) {
  18129. var animatables = target.getAnimatables();
  18130. for (var index = 0; index < animatables.length; index++) {
  18131. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18132. }
  18133. }
  18134. animatable.reset();
  18135. return animatable;
  18136. };
  18137. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18138. if (speedRatio === undefined) {
  18139. speedRatio = 1.0;
  18140. }
  18141. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18142. return animatable;
  18143. };
  18144. Scene.prototype.getAnimatableByTarget = function (target) {
  18145. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18146. if (this._activeAnimatables[index].target === target) {
  18147. return this._activeAnimatables[index];
  18148. }
  18149. }
  18150. return null;
  18151. };
  18152. Object.defineProperty(Scene.prototype, "Animatables", {
  18153. get: function () {
  18154. return this._activeAnimatables;
  18155. },
  18156. enumerable: true,
  18157. configurable: true
  18158. });
  18159. /**
  18160. * Will stop the animation of the given target
  18161. * @param target - the target
  18162. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18163. * @see beginAnimation
  18164. */
  18165. Scene.prototype.stopAnimation = function (target, animationName) {
  18166. var animatable = this.getAnimatableByTarget(target);
  18167. if (animatable) {
  18168. animatable.stop(animationName);
  18169. }
  18170. };
  18171. Scene.prototype._animate = function () {
  18172. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18173. return;
  18174. }
  18175. // Getting time
  18176. var now = BABYLON.Tools.Now;
  18177. if (!this._animationTimeLast) {
  18178. if (this._pendingData.length > 0) {
  18179. return;
  18180. }
  18181. this._animationTimeLast = now;
  18182. }
  18183. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18184. this._animationTime += deltaTime;
  18185. this._animationTimeLast = now;
  18186. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18187. this._activeAnimatables[index]._animate(this._animationTime);
  18188. }
  18189. };
  18190. // Matrix
  18191. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18192. this._useAlternateCameraConfiguration = active;
  18193. };
  18194. Scene.prototype.getViewMatrix = function () {
  18195. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18196. };
  18197. Scene.prototype.getProjectionMatrix = function () {
  18198. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18199. };
  18200. Scene.prototype.getTransformMatrix = function () {
  18201. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18202. };
  18203. Scene.prototype.setTransformMatrix = function (view, projection) {
  18204. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18205. return;
  18206. }
  18207. this._viewUpdateFlag = view.updateFlag;
  18208. this._projectionUpdateFlag = projection.updateFlag;
  18209. this._viewMatrix = view;
  18210. this._projectionMatrix = projection;
  18211. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18212. // Update frustum
  18213. if (!this._frustumPlanes) {
  18214. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18215. }
  18216. else {
  18217. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18218. }
  18219. if (this.activeCamera._alternateCamera) {
  18220. var otherCamera = this.activeCamera._alternateCamera;
  18221. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18222. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18223. }
  18224. if (this._sceneUbo.useUbo) {
  18225. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18226. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18227. this._sceneUbo.update();
  18228. }
  18229. };
  18230. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18231. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18232. return;
  18233. }
  18234. this._alternateViewUpdateFlag = view.updateFlag;
  18235. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18236. this._alternateViewMatrix = view;
  18237. this._alternateProjectionMatrix = projection;
  18238. if (!this._alternateTransformMatrix) {
  18239. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18240. }
  18241. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18242. if (!this._alternateSceneUbo) {
  18243. this._createAlternateUbo();
  18244. }
  18245. if (this._alternateSceneUbo.useUbo) {
  18246. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18247. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18248. this._alternateSceneUbo.update();
  18249. }
  18250. };
  18251. Scene.prototype.getSceneUniformBuffer = function () {
  18252. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18253. };
  18254. // Methods
  18255. Scene.prototype.getUniqueId = function () {
  18256. var result = Scene._uniqueIdCounter;
  18257. Scene._uniqueIdCounter++;
  18258. return result;
  18259. };
  18260. Scene.prototype.addMesh = function (newMesh) {
  18261. var position = this.meshes.push(newMesh);
  18262. //notify the collision coordinator
  18263. if (this.collisionCoordinator) {
  18264. this.collisionCoordinator.onMeshAdded(newMesh);
  18265. }
  18266. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18267. };
  18268. Scene.prototype.removeMesh = function (toRemove) {
  18269. var index = this.meshes.indexOf(toRemove);
  18270. if (index !== -1) {
  18271. // Remove from the scene if mesh found
  18272. this.meshes.splice(index, 1);
  18273. }
  18274. //notify the collision coordinator
  18275. if (this.collisionCoordinator) {
  18276. this.collisionCoordinator.onMeshRemoved(toRemove);
  18277. }
  18278. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18279. return index;
  18280. };
  18281. Scene.prototype.removeSkeleton = function (toRemove) {
  18282. var index = this.skeletons.indexOf(toRemove);
  18283. if (index !== -1) {
  18284. // Remove from the scene if found
  18285. this.skeletons.splice(index, 1);
  18286. }
  18287. return index;
  18288. };
  18289. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18290. var index = this.morphTargetManagers.indexOf(toRemove);
  18291. if (index !== -1) {
  18292. // Remove from the scene if found
  18293. this.morphTargetManagers.splice(index, 1);
  18294. }
  18295. return index;
  18296. };
  18297. Scene.prototype.removeLight = function (toRemove) {
  18298. var index = this.lights.indexOf(toRemove);
  18299. if (index !== -1) {
  18300. // Remove from the scene if mesh found
  18301. this.lights.splice(index, 1);
  18302. this.sortLightsByPriority();
  18303. }
  18304. this.onLightRemovedObservable.notifyObservers(toRemove);
  18305. return index;
  18306. };
  18307. Scene.prototype.removeCamera = function (toRemove) {
  18308. var index = this.cameras.indexOf(toRemove);
  18309. if (index !== -1) {
  18310. // Remove from the scene if mesh found
  18311. this.cameras.splice(index, 1);
  18312. }
  18313. // Remove from activeCameras
  18314. var index2 = this.activeCameras.indexOf(toRemove);
  18315. if (index2 !== -1) {
  18316. // Remove from the scene if mesh found
  18317. this.activeCameras.splice(index2, 1);
  18318. }
  18319. // Reset the activeCamera
  18320. if (this.activeCamera === toRemove) {
  18321. if (this.cameras.length > 0) {
  18322. this.activeCamera = this.cameras[0];
  18323. }
  18324. else {
  18325. this.activeCamera = null;
  18326. }
  18327. }
  18328. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18329. return index;
  18330. };
  18331. Scene.prototype.addLight = function (newLight) {
  18332. this.lights.push(newLight);
  18333. this.sortLightsByPriority();
  18334. this.onNewLightAddedObservable.notifyObservers(newLight);
  18335. };
  18336. Scene.prototype.sortLightsByPriority = function () {
  18337. if (this.requireLightSorting) {
  18338. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18339. }
  18340. };
  18341. Scene.prototype.addCamera = function (newCamera) {
  18342. var position = this.cameras.push(newCamera);
  18343. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18344. };
  18345. /**
  18346. * Switch active camera
  18347. * @param {Camera} newCamera - new active camera
  18348. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18349. */
  18350. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18351. if (attachControl === void 0) { attachControl = true; }
  18352. var canvas = this._engine.getRenderingCanvas();
  18353. this.activeCamera.detachControl(canvas);
  18354. this.activeCamera = newCamera;
  18355. if (attachControl) {
  18356. newCamera.attachControl(canvas);
  18357. }
  18358. };
  18359. /**
  18360. * sets the active camera of the scene using its ID
  18361. * @param {string} id - the camera's ID
  18362. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18363. * @see activeCamera
  18364. */
  18365. Scene.prototype.setActiveCameraByID = function (id) {
  18366. var camera = this.getCameraByID(id);
  18367. if (camera) {
  18368. this.activeCamera = camera;
  18369. return camera;
  18370. }
  18371. return null;
  18372. };
  18373. /**
  18374. * sets the active camera of the scene using its name
  18375. * @param {string} name - the camera's name
  18376. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18377. * @see activeCamera
  18378. */
  18379. Scene.prototype.setActiveCameraByName = function (name) {
  18380. var camera = this.getCameraByName(name);
  18381. if (camera) {
  18382. this.activeCamera = camera;
  18383. return camera;
  18384. }
  18385. return null;
  18386. };
  18387. /**
  18388. * get a material using its id
  18389. * @param {string} the material's ID
  18390. * @return {BABYLON.Material|null} the material or null if none found.
  18391. */
  18392. Scene.prototype.getMaterialByID = function (id) {
  18393. for (var index = 0; index < this.materials.length; index++) {
  18394. if (this.materials[index].id === id) {
  18395. return this.materials[index];
  18396. }
  18397. }
  18398. return null;
  18399. };
  18400. /**
  18401. * get a material using its name
  18402. * @param {string} the material's name
  18403. * @return {BABYLON.Material|null} the material or null if none found.
  18404. */
  18405. Scene.prototype.getMaterialByName = function (name) {
  18406. for (var index = 0; index < this.materials.length; index++) {
  18407. if (this.materials[index].name === name) {
  18408. return this.materials[index];
  18409. }
  18410. }
  18411. return null;
  18412. };
  18413. Scene.prototype.getLensFlareSystemByName = function (name) {
  18414. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18415. if (this.lensFlareSystems[index].name === name) {
  18416. return this.lensFlareSystems[index];
  18417. }
  18418. }
  18419. return null;
  18420. };
  18421. Scene.prototype.getLensFlareSystemByID = function (id) {
  18422. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18423. if (this.lensFlareSystems[index].id === id) {
  18424. return this.lensFlareSystems[index];
  18425. }
  18426. }
  18427. return null;
  18428. };
  18429. Scene.prototype.getCameraByID = function (id) {
  18430. for (var index = 0; index < this.cameras.length; index++) {
  18431. if (this.cameras[index].id === id) {
  18432. return this.cameras[index];
  18433. }
  18434. }
  18435. return null;
  18436. };
  18437. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18438. for (var index = 0; index < this.cameras.length; index++) {
  18439. if (this.cameras[index].uniqueId === uniqueId) {
  18440. return this.cameras[index];
  18441. }
  18442. }
  18443. return null;
  18444. };
  18445. /**
  18446. * get a camera using its name
  18447. * @param {string} the camera's name
  18448. * @return {BABYLON.Camera|null} the camera or null if none found.
  18449. */
  18450. Scene.prototype.getCameraByName = function (name) {
  18451. for (var index = 0; index < this.cameras.length; index++) {
  18452. if (this.cameras[index].name === name) {
  18453. return this.cameras[index];
  18454. }
  18455. }
  18456. return null;
  18457. };
  18458. /**
  18459. * get a bone using its id
  18460. * @param {string} the bone's id
  18461. * @return {BABYLON.Bone|null} the bone or null if not found
  18462. */
  18463. Scene.prototype.getBoneByID = function (id) {
  18464. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18465. var skeleton = this.skeletons[skeletonIndex];
  18466. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18467. if (skeleton.bones[boneIndex].id === id) {
  18468. return skeleton.bones[boneIndex];
  18469. }
  18470. }
  18471. }
  18472. return null;
  18473. };
  18474. /**
  18475. * get a bone using its id
  18476. * @param {string} the bone's name
  18477. * @return {BABYLON.Bone|null} the bone or null if not found
  18478. */
  18479. Scene.prototype.getBoneByName = function (name) {
  18480. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18481. var skeleton = this.skeletons[skeletonIndex];
  18482. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18483. if (skeleton.bones[boneIndex].name === name) {
  18484. return skeleton.bones[boneIndex];
  18485. }
  18486. }
  18487. }
  18488. return null;
  18489. };
  18490. /**
  18491. * get a light node using its name
  18492. * @param {string} the light's name
  18493. * @return {BABYLON.Light|null} the light or null if none found.
  18494. */
  18495. Scene.prototype.getLightByName = function (name) {
  18496. for (var index = 0; index < this.lights.length; index++) {
  18497. if (this.lights[index].name === name) {
  18498. return this.lights[index];
  18499. }
  18500. }
  18501. return null;
  18502. };
  18503. /**
  18504. * get a light node using its ID
  18505. * @param {string} the light's id
  18506. * @return {BABYLON.Light|null} the light or null if none found.
  18507. */
  18508. Scene.prototype.getLightByID = function (id) {
  18509. for (var index = 0; index < this.lights.length; index++) {
  18510. if (this.lights[index].id === id) {
  18511. return this.lights[index];
  18512. }
  18513. }
  18514. return null;
  18515. };
  18516. /**
  18517. * get a light node using its scene-generated unique ID
  18518. * @param {number} the light's unique id
  18519. * @return {BABYLON.Light|null} the light or null if none found.
  18520. */
  18521. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18522. for (var index = 0; index < this.lights.length; index++) {
  18523. if (this.lights[index].uniqueId === uniqueId) {
  18524. return this.lights[index];
  18525. }
  18526. }
  18527. return null;
  18528. };
  18529. /**
  18530. * get a particle system by id
  18531. * @param id {number} the particle system id
  18532. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18533. */
  18534. Scene.prototype.getParticleSystemByID = function (id) {
  18535. for (var index = 0; index < this.particleSystems.length; index++) {
  18536. if (this.particleSystems[index].id === id) {
  18537. return this.particleSystems[index];
  18538. }
  18539. }
  18540. return null;
  18541. };
  18542. /**
  18543. * get a geometry using its ID
  18544. * @param {string} the geometry's id
  18545. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18546. */
  18547. Scene.prototype.getGeometryByID = function (id) {
  18548. for (var index = 0; index < this._geometries.length; index++) {
  18549. if (this._geometries[index].id === id) {
  18550. return this._geometries[index];
  18551. }
  18552. }
  18553. return null;
  18554. };
  18555. /**
  18556. * add a new geometry to this scene.
  18557. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18558. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18559. * @return {boolean} was the geometry added or not
  18560. */
  18561. Scene.prototype.pushGeometry = function (geometry, force) {
  18562. if (!force && this.getGeometryByID(geometry.id)) {
  18563. return false;
  18564. }
  18565. this._geometries.push(geometry);
  18566. //notify the collision coordinator
  18567. if (this.collisionCoordinator) {
  18568. this.collisionCoordinator.onGeometryAdded(geometry);
  18569. }
  18570. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18571. return true;
  18572. };
  18573. /**
  18574. * Removes an existing geometry
  18575. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18576. * @return {boolean} was the geometry removed or not
  18577. */
  18578. Scene.prototype.removeGeometry = function (geometry) {
  18579. var index = this._geometries.indexOf(geometry);
  18580. if (index > -1) {
  18581. this._geometries.splice(index, 1);
  18582. //notify the collision coordinator
  18583. if (this.collisionCoordinator) {
  18584. this.collisionCoordinator.onGeometryDeleted(geometry);
  18585. }
  18586. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18587. return true;
  18588. }
  18589. return false;
  18590. };
  18591. Scene.prototype.getGeometries = function () {
  18592. return this._geometries;
  18593. };
  18594. /**
  18595. * Get the first added mesh found of a given ID
  18596. * @param {string} id - the id to search for
  18597. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18598. */
  18599. Scene.prototype.getMeshByID = function (id) {
  18600. for (var index = 0; index < this.meshes.length; index++) {
  18601. if (this.meshes[index].id === id) {
  18602. return this.meshes[index];
  18603. }
  18604. }
  18605. return null;
  18606. };
  18607. Scene.prototype.getMeshesByID = function (id) {
  18608. return this.meshes.filter(function (m) {
  18609. return m.id === id;
  18610. });
  18611. };
  18612. /**
  18613. * Get a mesh with its auto-generated unique id
  18614. * @param {number} uniqueId - the unique id to search for
  18615. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18616. */
  18617. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18618. for (var index = 0; index < this.meshes.length; index++) {
  18619. if (this.meshes[index].uniqueId === uniqueId) {
  18620. return this.meshes[index];
  18621. }
  18622. }
  18623. return null;
  18624. };
  18625. /**
  18626. * Get a the last added mesh found of a given ID
  18627. * @param {string} id - the id to search for
  18628. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18629. */
  18630. Scene.prototype.getLastMeshByID = function (id) {
  18631. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18632. if (this.meshes[index].id === id) {
  18633. return this.meshes[index];
  18634. }
  18635. }
  18636. return null;
  18637. };
  18638. /**
  18639. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18640. * @param {string} id - the id to search for
  18641. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18642. */
  18643. Scene.prototype.getLastEntryByID = function (id) {
  18644. var index;
  18645. for (index = this.meshes.length - 1; index >= 0; index--) {
  18646. if (this.meshes[index].id === id) {
  18647. return this.meshes[index];
  18648. }
  18649. }
  18650. for (index = this.cameras.length - 1; index >= 0; index--) {
  18651. if (this.cameras[index].id === id) {
  18652. return this.cameras[index];
  18653. }
  18654. }
  18655. for (index = this.lights.length - 1; index >= 0; index--) {
  18656. if (this.lights[index].id === id) {
  18657. return this.lights[index];
  18658. }
  18659. }
  18660. return null;
  18661. };
  18662. Scene.prototype.getNodeByID = function (id) {
  18663. var mesh = this.getMeshByID(id);
  18664. if (mesh) {
  18665. return mesh;
  18666. }
  18667. var light = this.getLightByID(id);
  18668. if (light) {
  18669. return light;
  18670. }
  18671. var camera = this.getCameraByID(id);
  18672. if (camera) {
  18673. return camera;
  18674. }
  18675. var bone = this.getBoneByID(id);
  18676. return bone;
  18677. };
  18678. Scene.prototype.getNodeByName = function (name) {
  18679. var mesh = this.getMeshByName(name);
  18680. if (mesh) {
  18681. return mesh;
  18682. }
  18683. var light = this.getLightByName(name);
  18684. if (light) {
  18685. return light;
  18686. }
  18687. var camera = this.getCameraByName(name);
  18688. if (camera) {
  18689. return camera;
  18690. }
  18691. var bone = this.getBoneByName(name);
  18692. return bone;
  18693. };
  18694. Scene.prototype.getMeshByName = function (name) {
  18695. for (var index = 0; index < this.meshes.length; index++) {
  18696. if (this.meshes[index].name === name) {
  18697. return this.meshes[index];
  18698. }
  18699. }
  18700. return null;
  18701. };
  18702. Scene.prototype.getSoundByName = function (name) {
  18703. var index;
  18704. if (BABYLON.AudioEngine) {
  18705. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18706. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18707. return this.mainSoundTrack.soundCollection[index];
  18708. }
  18709. }
  18710. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18711. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18712. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18713. return this.soundTracks[sdIndex].soundCollection[index];
  18714. }
  18715. }
  18716. }
  18717. }
  18718. return null;
  18719. };
  18720. Scene.prototype.getLastSkeletonByID = function (id) {
  18721. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18722. if (this.skeletons[index].id === id) {
  18723. return this.skeletons[index];
  18724. }
  18725. }
  18726. return null;
  18727. };
  18728. Scene.prototype.getSkeletonById = function (id) {
  18729. for (var index = 0; index < this.skeletons.length; index++) {
  18730. if (this.skeletons[index].id === id) {
  18731. return this.skeletons[index];
  18732. }
  18733. }
  18734. return null;
  18735. };
  18736. Scene.prototype.getSkeletonByName = function (name) {
  18737. for (var index = 0; index < this.skeletons.length; index++) {
  18738. if (this.skeletons[index].name === name) {
  18739. return this.skeletons[index];
  18740. }
  18741. }
  18742. return null;
  18743. };
  18744. Scene.prototype.getMorphTargetManagerById = function (id) {
  18745. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18746. if (this.morphTargetManagers[index].uniqueId === id) {
  18747. return this.morphTargetManagers[index];
  18748. }
  18749. }
  18750. return null;
  18751. };
  18752. Scene.prototype.isActiveMesh = function (mesh) {
  18753. return (this._activeMeshes.indexOf(mesh) !== -1);
  18754. };
  18755. /**
  18756. * Return a the first highlight layer of the scene with a given name.
  18757. * @param name The name of the highlight layer to look for.
  18758. * @return The highlight layer if found otherwise null.
  18759. */
  18760. Scene.prototype.getHighlightLayerByName = function (name) {
  18761. for (var index = 0; index < this.highlightLayers.length; index++) {
  18762. if (this.highlightLayers[index].name === name) {
  18763. return this.highlightLayers[index];
  18764. }
  18765. }
  18766. return null;
  18767. };
  18768. Object.defineProperty(Scene.prototype, "uid", {
  18769. /**
  18770. * Return a unique id as a string which can serve as an identifier for the scene
  18771. */
  18772. get: function () {
  18773. if (!this._uid) {
  18774. this._uid = BABYLON.Tools.RandomId();
  18775. }
  18776. return this._uid;
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. /**
  18782. * Add an externaly attached data from its key.
  18783. * This method call will fail and return false, if such key already exists.
  18784. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18785. * @param key the unique key that identifies the data
  18786. * @param data the data object to associate to the key for this Engine instance
  18787. * @return true if no such key were already present and the data was added successfully, false otherwise
  18788. */
  18789. Scene.prototype.addExternalData = function (key, data) {
  18790. if (!this._externalData) {
  18791. this._externalData = new BABYLON.StringDictionary();
  18792. }
  18793. return this._externalData.add(key, data);
  18794. };
  18795. /**
  18796. * Get an externaly attached data from its key
  18797. * @param key the unique key that identifies the data
  18798. * @return the associated data, if present (can be null), or undefined if not present
  18799. */
  18800. Scene.prototype.getExternalData = function (key) {
  18801. if (!this._externalData) {
  18802. return null;
  18803. }
  18804. return this._externalData.get(key);
  18805. };
  18806. /**
  18807. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18808. * @param key the unique key that identifies the data
  18809. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18810. * @return the associated data, can be null if the factory returned null.
  18811. */
  18812. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18813. if (!this._externalData) {
  18814. this._externalData = new BABYLON.StringDictionary();
  18815. }
  18816. return this._externalData.getOrAddWithFactory(key, factory);
  18817. };
  18818. /**
  18819. * Remove an externaly attached data from the Engine instance
  18820. * @param key the unique key that identifies the data
  18821. * @return true if the data was successfully removed, false if it doesn't exist
  18822. */
  18823. Scene.prototype.removeExternalData = function (key) {
  18824. return this._externalData.remove(key);
  18825. };
  18826. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18827. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18828. var material = subMesh.getMaterial();
  18829. if (mesh.showSubMeshesBoundingBox) {
  18830. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18831. }
  18832. if (material) {
  18833. // Render targets
  18834. if (material.getRenderTargetTextures) {
  18835. if (this._processedMaterials.indexOf(material) === -1) {
  18836. this._processedMaterials.push(material);
  18837. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18838. }
  18839. }
  18840. // Dispatch
  18841. this._activeIndices.addCount(subMesh.indexCount, false);
  18842. this._renderingManager.dispatch(subMesh);
  18843. }
  18844. }
  18845. };
  18846. Scene.prototype._isInIntermediateRendering = function () {
  18847. return this._intermediateRendering;
  18848. };
  18849. /**
  18850. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18851. */
  18852. Scene.prototype.freezeActiveMeshes = function () {
  18853. this._evaluateActiveMeshes();
  18854. this._activeMeshesFrozen = true;
  18855. return this;
  18856. };
  18857. /**
  18858. * Use this function to restart evaluating active meshes on every frame
  18859. */
  18860. Scene.prototype.unfreezeActiveMeshes = function () {
  18861. this._activeMeshesFrozen = false;
  18862. return this;
  18863. };
  18864. Scene.prototype._evaluateActiveMeshes = function () {
  18865. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18866. return;
  18867. }
  18868. this.activeCamera._activeMeshes.reset();
  18869. this._activeMeshes.reset();
  18870. this._renderingManager.reset();
  18871. this._processedMaterials.reset();
  18872. this._activeParticleSystems.reset();
  18873. this._activeSkeletons.reset();
  18874. this._softwareSkinnedMeshes.reset();
  18875. if (this._boundingBoxRenderer) {
  18876. this._boundingBoxRenderer.reset();
  18877. }
  18878. // Meshes
  18879. var meshes;
  18880. var len;
  18881. if (this._selectionOctree) {
  18882. var selection = this._selectionOctree.select(this._frustumPlanes);
  18883. meshes = selection.data;
  18884. len = selection.length;
  18885. }
  18886. else {
  18887. len = this.meshes.length;
  18888. meshes = this.meshes;
  18889. }
  18890. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18891. var mesh = meshes[meshIndex];
  18892. if (mesh.isBlocked) {
  18893. continue;
  18894. }
  18895. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18896. if (!mesh.isReady() || !mesh.isEnabled()) {
  18897. continue;
  18898. }
  18899. mesh.computeWorldMatrix();
  18900. // Intersections
  18901. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18902. this._meshesForIntersections.pushNoDuplicate(mesh);
  18903. }
  18904. // Switch to current LOD
  18905. var meshLOD = mesh.getLOD(this.activeCamera);
  18906. if (!meshLOD) {
  18907. continue;
  18908. }
  18909. mesh._preActivate();
  18910. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18911. this._activeMeshes.push(mesh);
  18912. this.activeCamera._activeMeshes.push(mesh);
  18913. mesh._activate(this._renderId);
  18914. if (meshLOD !== mesh) {
  18915. meshLOD._activate(this._renderId);
  18916. }
  18917. this._activeMesh(mesh, meshLOD);
  18918. }
  18919. }
  18920. // Particle systems
  18921. this._particlesDuration.beginMonitoring();
  18922. var beforeParticlesDate = BABYLON.Tools.Now;
  18923. if (this.particlesEnabled) {
  18924. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18925. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18926. var particleSystem = this.particleSystems[particleIndex];
  18927. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18928. continue;
  18929. }
  18930. var emitter = particleSystem.emitter;
  18931. if (!emitter.position || emitter.isEnabled()) {
  18932. this._activeParticleSystems.push(particleSystem);
  18933. particleSystem.animate();
  18934. this._renderingManager.dispatchParticles(particleSystem);
  18935. }
  18936. }
  18937. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18938. }
  18939. this._particlesDuration.endMonitoring(false);
  18940. };
  18941. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18942. if (mesh.skeleton && this.skeletonsEnabled) {
  18943. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18944. mesh.skeleton.prepare();
  18945. }
  18946. if (!mesh.computeBonesUsingShaders) {
  18947. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18948. }
  18949. }
  18950. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18951. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18952. }
  18953. if (mesh && mesh.subMeshes) {
  18954. // Submeshes Octrees
  18955. var len;
  18956. var subMeshes;
  18957. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18958. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18959. len = intersections.length;
  18960. subMeshes = intersections.data;
  18961. }
  18962. else {
  18963. subMeshes = mesh.subMeshes;
  18964. len = subMeshes.length;
  18965. }
  18966. for (var subIndex = 0; subIndex < len; subIndex++) {
  18967. var subMesh = subMeshes[subIndex];
  18968. this._evaluateSubMesh(subMesh, mesh);
  18969. }
  18970. }
  18971. };
  18972. Scene.prototype.updateTransformMatrix = function (force) {
  18973. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18974. };
  18975. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18976. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18977. };
  18978. Scene.prototype._renderForCamera = function (camera) {
  18979. if (camera && camera._skipRendering) {
  18980. return;
  18981. }
  18982. var engine = this._engine;
  18983. var startTime = BABYLON.Tools.Now;
  18984. this.activeCamera = camera;
  18985. if (!this.activeCamera)
  18986. throw new Error("Active camera not set");
  18987. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18988. // Viewport
  18989. engine.setViewport(this.activeCamera.viewport);
  18990. // Camera
  18991. this.resetCachedMaterial();
  18992. this._renderId++;
  18993. this.activeCamera.update();
  18994. this.updateTransformMatrix();
  18995. if (camera._alternateCamera) {
  18996. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18997. this._alternateRendering = true;
  18998. }
  18999. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19000. // Meshes
  19001. this._evaluateActiveMeshesDuration.beginMonitoring();
  19002. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19003. this._evaluateActiveMeshes();
  19004. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19005. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19006. // Software skinning
  19007. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19008. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19009. mesh.applySkeleton(mesh.skeleton);
  19010. }
  19011. // Render targets
  19012. this._renderTargetsDuration.beginMonitoring();
  19013. var needsRestoreFrameBuffer = false;
  19014. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19015. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19016. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19017. }
  19018. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19019. this._intermediateRendering = true;
  19020. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19021. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19022. var renderTarget = this._renderTargets.data[renderIndex];
  19023. if (renderTarget._shouldRender()) {
  19024. this._renderId++;
  19025. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19026. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19027. }
  19028. }
  19029. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19030. this._intermediateRendering = false;
  19031. this._renderId++;
  19032. needsRestoreFrameBuffer = true; // Restore back buffer
  19033. }
  19034. // Render HighlightLayer Texture
  19035. var stencilState = this._engine.getStencilBuffer();
  19036. var renderhighlights = false;
  19037. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19038. this._intermediateRendering = true;
  19039. for (var i = 0; i < this.highlightLayers.length; i++) {
  19040. var highlightLayer = this.highlightLayers[i];
  19041. if (highlightLayer.shouldRender() &&
  19042. (!highlightLayer.camera ||
  19043. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19044. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19045. renderhighlights = true;
  19046. var renderTarget = highlightLayer._mainTexture;
  19047. if (renderTarget._shouldRender()) {
  19048. this._renderId++;
  19049. renderTarget.render(false, false);
  19050. needsRestoreFrameBuffer = true;
  19051. }
  19052. }
  19053. }
  19054. this._intermediateRendering = false;
  19055. this._renderId++;
  19056. }
  19057. if (needsRestoreFrameBuffer) {
  19058. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19059. }
  19060. this._renderTargetsDuration.endMonitoring(false);
  19061. // Prepare Frame
  19062. this.postProcessManager._prepareFrame();
  19063. this._renderDuration.beginMonitoring();
  19064. // Backgrounds
  19065. var layerIndex;
  19066. var layer;
  19067. if (this.layers.length) {
  19068. engine.setDepthBuffer(false);
  19069. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19070. layer = this.layers[layerIndex];
  19071. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19072. layer.render();
  19073. }
  19074. }
  19075. engine.setDepthBuffer(true);
  19076. }
  19077. // Render
  19078. BABYLON.Tools.StartPerformanceCounter("Main render");
  19079. // Activate HighlightLayer stencil
  19080. if (renderhighlights) {
  19081. this._engine.setStencilBuffer(true);
  19082. }
  19083. this._renderingManager.render(null, null, true, true);
  19084. // Restore HighlightLayer stencil
  19085. if (renderhighlights) {
  19086. this._engine.setStencilBuffer(stencilState);
  19087. }
  19088. BABYLON.Tools.EndPerformanceCounter("Main render");
  19089. // Bounding boxes
  19090. if (this._boundingBoxRenderer) {
  19091. this._boundingBoxRenderer.render();
  19092. }
  19093. // Lens flares
  19094. if (this.lensFlaresEnabled) {
  19095. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19096. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19097. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19098. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19099. lensFlareSystem.render();
  19100. }
  19101. }
  19102. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19103. }
  19104. // Foregrounds
  19105. if (this.layers.length) {
  19106. engine.setDepthBuffer(false);
  19107. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19108. layer = this.layers[layerIndex];
  19109. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19110. layer.render();
  19111. }
  19112. }
  19113. engine.setDepthBuffer(true);
  19114. }
  19115. // Highlight Layer
  19116. if (renderhighlights) {
  19117. engine.setDepthBuffer(false);
  19118. for (var i = 0; i < this.highlightLayers.length; i++) {
  19119. if (this.highlightLayers[i].shouldRender()) {
  19120. this.highlightLayers[i].render();
  19121. }
  19122. }
  19123. engine.setDepthBuffer(true);
  19124. }
  19125. this._renderDuration.endMonitoring(false);
  19126. // Finalize frame
  19127. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19128. // Reset some special arrays
  19129. this._renderTargets.reset();
  19130. this._alternateRendering = false;
  19131. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19132. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19133. };
  19134. Scene.prototype._processSubCameras = function (camera) {
  19135. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19136. this._renderForCamera(camera);
  19137. return;
  19138. }
  19139. // Update camera
  19140. this.activeCamera.update();
  19141. // rig cameras
  19142. for (var index = 0; index < camera._rigCameras.length; index++) {
  19143. this._renderForCamera(camera._rigCameras[index]);
  19144. }
  19145. this.activeCamera = camera;
  19146. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19147. };
  19148. Scene.prototype._checkIntersections = function () {
  19149. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19150. var sourceMesh = this._meshesForIntersections.data[index];
  19151. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19152. var action = sourceMesh.actionManager.actions[actionIndex];
  19153. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19154. var parameters = action.getTriggerParameter();
  19155. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19156. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19157. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19158. if (areIntersecting && currentIntersectionInProgress === -1) {
  19159. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19160. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19161. sourceMesh._intersectionsInProgress.push(otherMesh);
  19162. }
  19163. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19164. sourceMesh._intersectionsInProgress.push(otherMesh);
  19165. }
  19166. }
  19167. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19168. //They intersected, and now they don't.
  19169. //is this trigger an exit trigger? execute an event.
  19170. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19171. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19172. }
  19173. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19174. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19175. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19176. }
  19177. }
  19178. }
  19179. }
  19180. }
  19181. };
  19182. Scene.prototype.render = function () {
  19183. if (this.isDisposed) {
  19184. return;
  19185. }
  19186. this._interFrameDuration.endMonitoring();
  19187. this._lastFrameDuration.beginMonitoring();
  19188. this._particlesDuration.fetchNewFrame();
  19189. this._spritesDuration.fetchNewFrame();
  19190. this._activeParticles.fetchNewFrame();
  19191. this._renderDuration.fetchNewFrame();
  19192. this._renderTargetsDuration.fetchNewFrame();
  19193. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19194. this._totalVertices.fetchNewFrame();
  19195. this._activeIndices.fetchNewFrame();
  19196. this._activeBones.fetchNewFrame();
  19197. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19198. this._meshesForIntersections.reset();
  19199. this.resetCachedMaterial();
  19200. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19201. // Actions
  19202. if (this.actionManager) {
  19203. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19204. }
  19205. //Simplification Queue
  19206. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19207. this.simplificationQueue.executeNext();
  19208. }
  19209. if (this._engine.isDeterministicLockStep()) {
  19210. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19211. var defaultTimeStep = (60.0 / 1000.0);
  19212. if (this._physicsEngine) {
  19213. defaultTimeStep = this._physicsEngine.getTimeStep();
  19214. }
  19215. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19216. this._timeAccumulator += deltaTime;
  19217. // compute the amount of fixed steps we should have taken since the last step
  19218. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19219. internalSteps = Math.min(internalSteps, maxSubSteps);
  19220. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19221. this.onBeforeStepObservable.notifyObservers(this);
  19222. // Animations
  19223. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19224. this._animate();
  19225. // Physics
  19226. if (this._physicsEngine) {
  19227. BABYLON.Tools.StartPerformanceCounter("Physics");
  19228. this._physicsEngine._step(defaultTimeStep);
  19229. BABYLON.Tools.EndPerformanceCounter("Physics");
  19230. }
  19231. this._timeAccumulator -= defaultTimeStep;
  19232. this.onAfterStepObservable.notifyObservers(this);
  19233. this._currentStepId++;
  19234. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19235. this._evaluateActiveMeshes();
  19236. }
  19237. }
  19238. }
  19239. else {
  19240. // Animations
  19241. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19242. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19243. this._animate();
  19244. // Physics
  19245. if (this._physicsEngine) {
  19246. BABYLON.Tools.StartPerformanceCounter("Physics");
  19247. this._physicsEngine._step(deltaTime / 1000.0);
  19248. BABYLON.Tools.EndPerformanceCounter("Physics");
  19249. }
  19250. }
  19251. // Before render
  19252. this.onBeforeRenderObservable.notifyObservers(this);
  19253. // Customs render targets
  19254. this._renderTargetsDuration.beginMonitoring();
  19255. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19256. var engine = this.getEngine();
  19257. var currentActiveCamera = this.activeCamera;
  19258. if (this.renderTargetsEnabled) {
  19259. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19260. this._intermediateRendering = true;
  19261. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19262. var renderTarget = this.customRenderTargets[customIndex];
  19263. if (renderTarget._shouldRender()) {
  19264. this._renderId++;
  19265. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19266. if (!this.activeCamera)
  19267. throw new Error("Active camera not set");
  19268. // Viewport
  19269. engine.setViewport(this.activeCamera.viewport);
  19270. // Camera
  19271. this.updateTransformMatrix();
  19272. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19273. }
  19274. }
  19275. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19276. this._intermediateRendering = false;
  19277. this._renderId++;
  19278. }
  19279. // Restore back buffer
  19280. if (this.customRenderTargets.length > 0) {
  19281. engine.restoreDefaultFramebuffer();
  19282. }
  19283. this._renderTargetsDuration.endMonitoring();
  19284. this.activeCamera = currentActiveCamera;
  19285. // Procedural textures
  19286. if (this.proceduralTexturesEnabled) {
  19287. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19288. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19289. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19290. if (proceduralTexture._shouldRender()) {
  19291. proceduralTexture.render();
  19292. }
  19293. }
  19294. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19295. }
  19296. // Clear
  19297. if (this.autoClearDepthAndStencil || this.autoClear) {
  19298. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19299. }
  19300. // Shadows
  19301. if (this.shadowsEnabled) {
  19302. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19303. var light = this.lights[lightIndex];
  19304. var shadowGenerator = light.getShadowGenerator();
  19305. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19306. var shadowMap = shadowGenerator.getShadowMap();
  19307. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19308. this._renderTargets.push(shadowMap);
  19309. }
  19310. }
  19311. }
  19312. }
  19313. // Depth renderer
  19314. if (this._depthRenderer) {
  19315. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19316. }
  19317. // Geometry renderer
  19318. if (this._geometryBufferRenderer) {
  19319. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19320. }
  19321. // RenderPipeline
  19322. if (this._postProcessRenderPipelineManager) {
  19323. this._postProcessRenderPipelineManager.update();
  19324. }
  19325. // Multi-cameras?
  19326. if (this.activeCameras.length > 0) {
  19327. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19328. if (cameraIndex > 0) {
  19329. this._engine.clear(null, false, true, true);
  19330. }
  19331. this._processSubCameras(this.activeCameras[cameraIndex]);
  19332. }
  19333. }
  19334. else {
  19335. if (!this.activeCamera) {
  19336. throw new Error("No camera defined");
  19337. }
  19338. this._processSubCameras(this.activeCamera);
  19339. }
  19340. // Intersection checks
  19341. this._checkIntersections();
  19342. // Update the audio listener attached to the camera
  19343. if (BABYLON.AudioEngine) {
  19344. this._updateAudioParameters();
  19345. }
  19346. // After render
  19347. if (this.afterRender) {
  19348. this.afterRender();
  19349. }
  19350. this.onAfterRenderObservable.notifyObservers(this);
  19351. // Cleaning
  19352. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19353. this._toBeDisposed.data[index].dispose();
  19354. this._toBeDisposed[index] = null;
  19355. }
  19356. this._toBeDisposed.reset();
  19357. if (this.dumpNextRenderTargets) {
  19358. this.dumpNextRenderTargets = false;
  19359. }
  19360. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19361. this._interFrameDuration.beginMonitoring();
  19362. this._lastFrameDuration.endMonitoring();
  19363. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19364. this._totalLightsCounter.addCount(this.lights.length, true);
  19365. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19366. this._totalTexturesCounter.addCount(this.textures.length, true);
  19367. this._activeBones.addCount(0, true);
  19368. this._activeIndices.addCount(0, true);
  19369. this._activeParticles.addCount(0, true);
  19370. };
  19371. Scene.prototype._updateAudioParameters = function () {
  19372. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19373. return;
  19374. }
  19375. var listeningCamera;
  19376. var audioEngine = BABYLON.Engine.audioEngine;
  19377. if (this.activeCameras.length > 0) {
  19378. listeningCamera = this.activeCameras[0];
  19379. }
  19380. else {
  19381. listeningCamera = this.activeCamera;
  19382. }
  19383. if (listeningCamera && audioEngine.canUseWebAudio) {
  19384. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19385. // for VR cameras
  19386. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19387. listeningCamera = listeningCamera.rigCameras[0];
  19388. }
  19389. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19390. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19391. cameraDirection.normalize();
  19392. // To avoid some errors on GearVR
  19393. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19394. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19395. }
  19396. var i;
  19397. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19398. var sound = this.mainSoundTrack.soundCollection[i];
  19399. if (sound.useCustomAttenuation) {
  19400. sound.updateDistanceFromListener();
  19401. }
  19402. }
  19403. for (i = 0; i < this.soundTracks.length; i++) {
  19404. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19405. sound = this.soundTracks[i].soundCollection[j];
  19406. if (sound.useCustomAttenuation) {
  19407. sound.updateDistanceFromListener();
  19408. }
  19409. }
  19410. }
  19411. }
  19412. };
  19413. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19414. // Audio
  19415. get: function () {
  19416. return this._audioEnabled;
  19417. },
  19418. set: function (value) {
  19419. this._audioEnabled = value;
  19420. if (BABYLON.AudioEngine) {
  19421. if (this._audioEnabled) {
  19422. this._enableAudio();
  19423. }
  19424. else {
  19425. this._disableAudio();
  19426. }
  19427. }
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Scene.prototype._disableAudio = function () {
  19433. var i;
  19434. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19435. this.mainSoundTrack.soundCollection[i].pause();
  19436. }
  19437. for (i = 0; i < this.soundTracks.length; i++) {
  19438. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19439. this.soundTracks[i].soundCollection[j].pause();
  19440. }
  19441. }
  19442. };
  19443. Scene.prototype._enableAudio = function () {
  19444. var i;
  19445. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19446. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19447. this.mainSoundTrack.soundCollection[i].play();
  19448. }
  19449. }
  19450. for (i = 0; i < this.soundTracks.length; i++) {
  19451. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19452. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19453. this.soundTracks[i].soundCollection[j].play();
  19454. }
  19455. }
  19456. }
  19457. };
  19458. Object.defineProperty(Scene.prototype, "headphone", {
  19459. get: function () {
  19460. return this._headphone;
  19461. },
  19462. set: function (value) {
  19463. this._headphone = value;
  19464. if (BABYLON.AudioEngine) {
  19465. if (this._headphone) {
  19466. this._switchAudioModeForHeadphones();
  19467. }
  19468. else {
  19469. this._switchAudioModeForNormalSpeakers();
  19470. }
  19471. }
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Scene.prototype._switchAudioModeForHeadphones = function () {
  19477. this.mainSoundTrack.switchPanningModelToHRTF();
  19478. for (var i = 0; i < this.soundTracks.length; i++) {
  19479. this.soundTracks[i].switchPanningModelToHRTF();
  19480. }
  19481. };
  19482. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19483. this.mainSoundTrack.switchPanningModelToEqualPower();
  19484. for (var i = 0; i < this.soundTracks.length; i++) {
  19485. this.soundTracks[i].switchPanningModelToEqualPower();
  19486. }
  19487. };
  19488. Scene.prototype.enableDepthRenderer = function () {
  19489. if (this._depthRenderer) {
  19490. return this._depthRenderer;
  19491. }
  19492. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19493. return this._depthRenderer;
  19494. };
  19495. Scene.prototype.disableDepthRenderer = function () {
  19496. if (!this._depthRenderer) {
  19497. return;
  19498. }
  19499. this._depthRenderer.dispose();
  19500. this._depthRenderer = null;
  19501. };
  19502. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19503. if (ratio === void 0) { ratio = 1; }
  19504. if (this._geometryBufferRenderer) {
  19505. return this._geometryBufferRenderer;
  19506. }
  19507. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19508. if (!this._geometryBufferRenderer.isSupported) {
  19509. this._geometryBufferRenderer = null;
  19510. }
  19511. return this._geometryBufferRenderer;
  19512. };
  19513. Scene.prototype.disableGeometryBufferRenderer = function () {
  19514. if (!this._geometryBufferRenderer) {
  19515. return;
  19516. }
  19517. this._geometryBufferRenderer.dispose();
  19518. this._geometryBufferRenderer = null;
  19519. };
  19520. Scene.prototype.freezeMaterials = function () {
  19521. for (var i = 0; i < this.materials.length; i++) {
  19522. this.materials[i].freeze();
  19523. }
  19524. };
  19525. Scene.prototype.unfreezeMaterials = function () {
  19526. for (var i = 0; i < this.materials.length; i++) {
  19527. this.materials[i].unfreeze();
  19528. }
  19529. };
  19530. Scene.prototype.dispose = function () {
  19531. this.beforeRender = null;
  19532. this.afterRender = null;
  19533. this.skeletons = [];
  19534. this.morphTargetManagers = [];
  19535. this.importedMeshesFiles = new Array();
  19536. this.resetCachedMaterial();
  19537. if (this._depthRenderer) {
  19538. this._depthRenderer.dispose();
  19539. }
  19540. if (this._gamepadManager) {
  19541. this._gamepadManager.dispose();
  19542. this._gamepadManager = null;
  19543. }
  19544. // Smart arrays
  19545. if (this.activeCamera) {
  19546. this.activeCamera._activeMeshes.dispose();
  19547. this.activeCamera = null;
  19548. }
  19549. this._activeMeshes.dispose();
  19550. this._renderingManager.dispose();
  19551. this._processedMaterials.dispose();
  19552. this._activeParticleSystems.dispose();
  19553. this._activeSkeletons.dispose();
  19554. this._softwareSkinnedMeshes.dispose();
  19555. this._renderTargets.dispose();
  19556. if (this._boundingBoxRenderer) {
  19557. this._boundingBoxRenderer.dispose();
  19558. }
  19559. this._meshesForIntersections.dispose();
  19560. this._toBeDisposed.dispose();
  19561. // Debug layer
  19562. if (this._debugLayer) {
  19563. this._debugLayer.hide();
  19564. }
  19565. // Events
  19566. this.onDisposeObservable.notifyObservers(this);
  19567. this.onDisposeObservable.clear();
  19568. this.onBeforeRenderObservable.clear();
  19569. this.onAfterRenderObservable.clear();
  19570. this.detachControl();
  19571. // Release sounds & sounds tracks
  19572. if (BABYLON.AudioEngine) {
  19573. this.disposeSounds();
  19574. }
  19575. // VR Helper
  19576. if (this.VRHelper) {
  19577. this.VRHelper.dispose();
  19578. }
  19579. // Detach cameras
  19580. var canvas = this._engine.getRenderingCanvas();
  19581. var index;
  19582. for (index = 0; index < this.cameras.length; index++) {
  19583. this.cameras[index].detachControl(canvas);
  19584. }
  19585. // Release lights
  19586. while (this.lights.length) {
  19587. this.lights[0].dispose();
  19588. }
  19589. // Release meshes
  19590. while (this.meshes.length) {
  19591. this.meshes[0].dispose(true);
  19592. }
  19593. // Release cameras
  19594. while (this.cameras.length) {
  19595. this.cameras[0].dispose();
  19596. }
  19597. // Release materials
  19598. if (this.defaultMaterial) {
  19599. this.defaultMaterial.dispose();
  19600. }
  19601. while (this.multiMaterials.length) {
  19602. this.multiMaterials[0].dispose();
  19603. }
  19604. while (this.materials.length) {
  19605. this.materials[0].dispose();
  19606. }
  19607. // Release particles
  19608. while (this.particleSystems.length) {
  19609. this.particleSystems[0].dispose();
  19610. }
  19611. // Release sprites
  19612. while (this.spriteManagers.length) {
  19613. this.spriteManagers[0].dispose();
  19614. }
  19615. // Release postProcesses
  19616. while (this.postProcesses.length) {
  19617. this.postProcesses[0].dispose();
  19618. }
  19619. // Release layers
  19620. while (this.layers.length) {
  19621. this.layers[0].dispose();
  19622. }
  19623. while (this.highlightLayers.length) {
  19624. this.highlightLayers[0].dispose();
  19625. }
  19626. // Release textures
  19627. while (this.textures.length) {
  19628. this.textures[0].dispose();
  19629. }
  19630. // Release UBO
  19631. this._sceneUbo.dispose();
  19632. if (this._alternateSceneUbo) {
  19633. this._alternateSceneUbo.dispose();
  19634. }
  19635. // Post-processes
  19636. this.postProcessManager.dispose();
  19637. if (this._postProcessRenderPipelineManager) {
  19638. this._postProcessRenderPipelineManager.dispose();
  19639. }
  19640. // Physics
  19641. if (this._physicsEngine) {
  19642. this.disablePhysicsEngine();
  19643. }
  19644. // Remove from engine
  19645. index = this._engine.scenes.indexOf(this);
  19646. if (index > -1) {
  19647. this._engine.scenes.splice(index, 1);
  19648. }
  19649. this._engine.wipeCaches();
  19650. this._engine = null;
  19651. this.defaultMaterial = null;
  19652. this.multiMaterials = null;
  19653. this.materials = null;
  19654. };
  19655. Object.defineProperty(Scene.prototype, "isDisposed", {
  19656. get: function () {
  19657. return !this._engine;
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. // Release sounds & sounds tracks
  19663. Scene.prototype.disposeSounds = function () {
  19664. if (!this._mainSoundTrack) {
  19665. return;
  19666. }
  19667. this.mainSoundTrack.dispose();
  19668. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19669. this.soundTracks[scIndex].dispose();
  19670. }
  19671. };
  19672. // Octrees
  19673. Scene.prototype.getWorldExtends = function () {
  19674. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19675. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19676. for (var index = 0; index < this.meshes.length; index++) {
  19677. var mesh = this.meshes[index];
  19678. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19679. continue;
  19680. }
  19681. mesh.computeWorldMatrix(true);
  19682. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19683. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19684. BABYLON.Tools.CheckExtends(minBox, min, max);
  19685. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19686. }
  19687. return {
  19688. min: min,
  19689. max: max
  19690. };
  19691. };
  19692. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19693. if (maxCapacity === void 0) { maxCapacity = 64; }
  19694. if (maxDepth === void 0) { maxDepth = 2; }
  19695. if (!this._selectionOctree) {
  19696. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19697. }
  19698. var worldExtends = this.getWorldExtends();
  19699. // Update octree
  19700. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19701. return this._selectionOctree;
  19702. };
  19703. // Picking
  19704. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19705. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19706. var engine = this._engine;
  19707. if (!camera) {
  19708. if (!this.activeCamera)
  19709. throw new Error("Active camera not set");
  19710. camera = this.activeCamera;
  19711. }
  19712. var cameraViewport = camera.viewport;
  19713. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19714. // Moving coordinates to local viewport world
  19715. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19716. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19717. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19718. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19719. };
  19720. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19721. if (!BABYLON.PickingInfo) {
  19722. return null;
  19723. }
  19724. var engine = this._engine;
  19725. if (!camera) {
  19726. if (!this.activeCamera)
  19727. throw new Error("Active camera not set");
  19728. camera = this.activeCamera;
  19729. }
  19730. var cameraViewport = camera.viewport;
  19731. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19732. var identity = BABYLON.Matrix.Identity();
  19733. // Moving coordinates to local viewport world
  19734. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19735. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19736. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19737. };
  19738. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19739. if (!BABYLON.PickingInfo) {
  19740. return null;
  19741. }
  19742. var pickingInfo = null;
  19743. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19744. var mesh = this.meshes[meshIndex];
  19745. if (predicate) {
  19746. if (!predicate(mesh)) {
  19747. continue;
  19748. }
  19749. }
  19750. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19751. continue;
  19752. }
  19753. var world = mesh.getWorldMatrix();
  19754. var ray = rayFunction(world);
  19755. var result = mesh.intersects(ray, fastCheck);
  19756. if (!result || !result.hit)
  19757. continue;
  19758. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19759. continue;
  19760. pickingInfo = result;
  19761. if (fastCheck) {
  19762. break;
  19763. }
  19764. }
  19765. return pickingInfo || new BABYLON.PickingInfo();
  19766. };
  19767. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19768. if (!BABYLON.PickingInfo) {
  19769. return null;
  19770. }
  19771. var pickingInfos = new Array();
  19772. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19773. var mesh = this.meshes[meshIndex];
  19774. if (predicate) {
  19775. if (!predicate(mesh)) {
  19776. continue;
  19777. }
  19778. }
  19779. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19780. continue;
  19781. }
  19782. var world = mesh.getWorldMatrix();
  19783. var ray = rayFunction(world);
  19784. var result = mesh.intersects(ray, false);
  19785. if (!result || !result.hit)
  19786. continue;
  19787. pickingInfos.push(result);
  19788. }
  19789. return pickingInfos;
  19790. };
  19791. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19792. if (!BABYLON.PickingInfo) {
  19793. return null;
  19794. }
  19795. var pickingInfo = null;
  19796. camera = camera || this.activeCamera;
  19797. if (this.spriteManagers.length > 0) {
  19798. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19799. var spriteManager = this.spriteManagers[spriteIndex];
  19800. if (!spriteManager.isPickable) {
  19801. continue;
  19802. }
  19803. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19804. if (!result || !result.hit)
  19805. continue;
  19806. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19807. continue;
  19808. pickingInfo = result;
  19809. if (fastCheck) {
  19810. break;
  19811. }
  19812. }
  19813. }
  19814. return pickingInfo || new BABYLON.PickingInfo();
  19815. };
  19816. /** Launch a ray to try to pick a mesh in the scene
  19817. * @param x position on screen
  19818. * @param y position on screen
  19819. * @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
  19820. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19821. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19822. */
  19823. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19824. var _this = this;
  19825. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19826. };
  19827. /** Launch a ray to try to pick a sprite in the scene
  19828. * @param x position on screen
  19829. * @param y position on screen
  19830. * @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
  19831. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19832. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19833. */
  19834. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19835. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19836. };
  19837. /** Use the given ray to pick a mesh in the scene
  19838. * @param ray The ray to use to pick meshes
  19839. * @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
  19840. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19841. */
  19842. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19843. var _this = this;
  19844. return this._internalPick(function (world) {
  19845. if (!_this._pickWithRayInverseMatrix) {
  19846. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19847. }
  19848. world.invertToRef(_this._pickWithRayInverseMatrix);
  19849. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19850. }, predicate, fastCheck);
  19851. };
  19852. /**
  19853. * Launch a ray to try to pick a mesh in the scene
  19854. * @param x X position on screen
  19855. * @param y Y position on screen
  19856. * @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
  19857. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19858. */
  19859. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19860. var _this = this;
  19861. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19862. };
  19863. /**
  19864. * Launch a ray to try to pick a mesh in the scene
  19865. * @param ray Ray to use
  19866. * @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
  19867. */
  19868. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19869. var _this = this;
  19870. return this._internalMultiPick(function (world) {
  19871. if (!_this._pickWithRayInverseMatrix) {
  19872. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19873. }
  19874. world.invertToRef(_this._pickWithRayInverseMatrix);
  19875. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19876. }, predicate);
  19877. };
  19878. Scene.prototype.setPointerOverMesh = function (mesh) {
  19879. if (this._pointerOverMesh === mesh) {
  19880. return;
  19881. }
  19882. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19883. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19884. }
  19885. this._pointerOverMesh = mesh;
  19886. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19887. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19888. }
  19889. };
  19890. Scene.prototype.getPointerOverMesh = function () {
  19891. return this._pointerOverMesh;
  19892. };
  19893. Scene.prototype.setPointerOverSprite = function (sprite) {
  19894. if (this._pointerOverSprite === sprite) {
  19895. return;
  19896. }
  19897. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19898. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19899. }
  19900. this._pointerOverSprite = sprite;
  19901. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19902. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19903. }
  19904. };
  19905. Scene.prototype.getPointerOverSprite = function () {
  19906. return this._pointerOverSprite;
  19907. };
  19908. // Physics
  19909. Scene.prototype.getPhysicsEngine = function () {
  19910. return this._physicsEngine;
  19911. };
  19912. /**
  19913. * Enables physics to the current scene
  19914. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19915. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19916. * @return {boolean} was the physics engine initialized
  19917. */
  19918. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19919. if (this._physicsEngine) {
  19920. return true;
  19921. }
  19922. try {
  19923. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19924. return true;
  19925. }
  19926. catch (e) {
  19927. BABYLON.Tools.Error(e.message);
  19928. return false;
  19929. }
  19930. };
  19931. Scene.prototype.disablePhysicsEngine = function () {
  19932. if (!this._physicsEngine) {
  19933. return;
  19934. }
  19935. this._physicsEngine.dispose();
  19936. this._physicsEngine = undefined;
  19937. };
  19938. Scene.prototype.isPhysicsEnabled = function () {
  19939. return this._physicsEngine !== undefined;
  19940. };
  19941. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19942. var mesh = compound.parts[0].mesh;
  19943. mesh.physicsImpostor.dispose();
  19944. mesh.physicsImpostor = null;
  19945. };
  19946. // Misc.
  19947. Scene.prototype._rebuildGeometries = function () {
  19948. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19949. var geometry = _a[_i];
  19950. geometry._rebuild();
  19951. }
  19952. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19953. var mesh = _c[_b];
  19954. mesh._rebuild();
  19955. }
  19956. if (this.postProcessManager) {
  19957. this.postProcessManager._rebuild();
  19958. }
  19959. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19960. var layer = _e[_d];
  19961. layer._rebuild();
  19962. }
  19963. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19964. var highlightLayer = _g[_f];
  19965. highlightLayer._rebuild();
  19966. }
  19967. if (this._boundingBoxRenderer) {
  19968. this._boundingBoxRenderer._rebuild();
  19969. }
  19970. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19971. var system = _j[_h];
  19972. system.rebuild();
  19973. }
  19974. if (this._postProcessRenderPipelineManager) {
  19975. this._postProcessRenderPipelineManager._rebuild();
  19976. }
  19977. };
  19978. Scene.prototype._rebuildTextures = function () {
  19979. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19980. var texture = _a[_i];
  19981. texture._rebuild();
  19982. }
  19983. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19984. };
  19985. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19986. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19987. if (replace === void 0) { replace = false; }
  19988. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19989. // Dispose existing camera or light in replace mode.
  19990. if (replace) {
  19991. if (this.activeCamera) {
  19992. this.activeCamera.dispose();
  19993. this.activeCamera = null;
  19994. }
  19995. if (this.lights) {
  19996. for (var i = 0; i < this.lights.length; i++) {
  19997. this.lights[i].dispose();
  19998. }
  19999. }
  20000. }
  20001. // Light
  20002. if (this.lights.length === 0) {
  20003. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20004. }
  20005. // Camera
  20006. if (!this.activeCamera) {
  20007. var worldExtends = this.getWorldExtends();
  20008. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20009. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20010. var camera;
  20011. var radius = worldSize.length() * 1.5;
  20012. if (createArcRotateCamera) {
  20013. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20014. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20015. arcRotateCamera.wheelPrecision = 100 / radius;
  20016. camera = arcRotateCamera;
  20017. }
  20018. else {
  20019. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20020. freeCamera.setTarget(worldCenter);
  20021. camera = freeCamera;
  20022. }
  20023. camera.minZ = radius * 0.01;
  20024. camera.maxZ = radius * 100;
  20025. camera.speed = radius * 0.2;
  20026. this.activeCamera = camera;
  20027. if (attachCameraControls) {
  20028. camera.attachControl(this.getEngine().getRenderingCanvas());
  20029. }
  20030. }
  20031. };
  20032. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20033. if (pbr === void 0) { pbr = false; }
  20034. if (scale === void 0) { scale = 1000; }
  20035. if (blur === void 0) { blur = 0; }
  20036. if (environmentTexture) {
  20037. this.environmentTexture = environmentTexture;
  20038. }
  20039. if (!this.environmentTexture) {
  20040. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20041. return;
  20042. }
  20043. // Skybox
  20044. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20045. if (pbr) {
  20046. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20047. hdrSkyboxMaterial.backFaceCulling = false;
  20048. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20049. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20050. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20051. hdrSkyboxMaterial.disableLighting = true;
  20052. hdrSkyboxMaterial.twoSidedLighting = true;
  20053. hdrSkybox.infiniteDistance = true;
  20054. hdrSkybox.material = hdrSkyboxMaterial;
  20055. }
  20056. else {
  20057. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20058. skyboxMaterial.backFaceCulling = false;
  20059. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20060. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20061. skyboxMaterial.disableLighting = true;
  20062. hdrSkybox.infiniteDistance = true;
  20063. hdrSkybox.material = skyboxMaterial;
  20064. }
  20065. return hdrSkybox;
  20066. };
  20067. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20068. if (webVROptions === void 0) { webVROptions = {}; }
  20069. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20070. };
  20071. // Tags
  20072. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20073. if (tagsQuery === undefined) {
  20074. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20075. return list;
  20076. }
  20077. var listByTags = [];
  20078. forEach = forEach || (function (item) { return; });
  20079. for (var i in list) {
  20080. var item = list[i];
  20081. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20082. listByTags.push(item);
  20083. forEach(item);
  20084. }
  20085. }
  20086. return listByTags;
  20087. };
  20088. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20089. return this._getByTags(this.meshes, tagsQuery, forEach);
  20090. };
  20091. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20092. return this._getByTags(this.cameras, tagsQuery, forEach);
  20093. };
  20094. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20095. return this._getByTags(this.lights, tagsQuery, forEach);
  20096. };
  20097. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20098. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20099. };
  20100. /**
  20101. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20102. * This allowed control for front to back rendering or reversly depending of the special needs.
  20103. *
  20104. * @param renderingGroupId The rendering group id corresponding to its index
  20105. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20106. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20107. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20108. */
  20109. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20110. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20111. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20112. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20113. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20114. };
  20115. /**
  20116. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20117. *
  20118. * @param renderingGroupId The rendering group id corresponding to its index
  20119. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20120. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20121. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20122. */
  20123. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20124. if (depth === void 0) { depth = true; }
  20125. if (stencil === void 0) { stencil = true; }
  20126. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20127. };
  20128. /**
  20129. * Will flag all materials as dirty to trigger new shader compilation
  20130. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20131. */
  20132. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20133. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20134. var material = _a[_i];
  20135. if (predicate && !predicate(material)) {
  20136. continue;
  20137. }
  20138. material.markAsDirty(flag);
  20139. }
  20140. };
  20141. // Statics
  20142. Scene._FOGMODE_NONE = 0;
  20143. Scene._FOGMODE_EXP = 1;
  20144. Scene._FOGMODE_EXP2 = 2;
  20145. Scene._FOGMODE_LINEAR = 3;
  20146. Scene._uniqueIdCounter = 0;
  20147. Scene.MinDeltaTime = 1.0;
  20148. Scene.MaxDeltaTime = 1000.0;
  20149. /** The distance in pixel that you have to move to prevent some events */
  20150. Scene.DragMovementThreshold = 10; // in pixels
  20151. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20152. Scene.LongPressDelay = 500; // in milliseconds
  20153. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20154. Scene.DoubleClickDelay = 300; // in milliseconds
  20155. /** If you need to check double click without raising a single click at first click, enable this flag */
  20156. Scene.ExclusiveDoubleClickMode = false;
  20157. return Scene;
  20158. }());
  20159. BABYLON.Scene = Scene;
  20160. })(BABYLON || (BABYLON = {}));
  20161. //# sourceMappingURL=babylon.scene.js.map
  20162. var BABYLON;
  20163. (function (BABYLON) {
  20164. var Buffer = (function () {
  20165. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20166. if (engine instanceof BABYLON.Mesh) {
  20167. this._engine = engine.getScene().getEngine();
  20168. }
  20169. else {
  20170. this._engine = engine;
  20171. }
  20172. this._updatable = updatable;
  20173. this._data = data;
  20174. this._strideSize = stride;
  20175. if (!postponeInternalCreation) {
  20176. this.create();
  20177. }
  20178. this._instanced = instanced;
  20179. this._instanceDivisor = instanced ? 1 : 0;
  20180. }
  20181. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20182. // a lot of these parameters are ignored as they are overriden by the buffer
  20183. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20184. };
  20185. // Properties
  20186. Buffer.prototype.isUpdatable = function () {
  20187. return this._updatable;
  20188. };
  20189. Buffer.prototype.getData = function () {
  20190. return this._data;
  20191. };
  20192. Buffer.prototype.getBuffer = function () {
  20193. return this._buffer;
  20194. };
  20195. Buffer.prototype.getStrideSize = function () {
  20196. return this._strideSize;
  20197. };
  20198. Buffer.prototype.getIsInstanced = function () {
  20199. return this._instanced;
  20200. };
  20201. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20202. get: function () {
  20203. return this._instanceDivisor;
  20204. },
  20205. set: function (value) {
  20206. this._instanceDivisor = value;
  20207. if (value == 0) {
  20208. this._instanced = false;
  20209. }
  20210. else {
  20211. this._instanced = true;
  20212. }
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. // Methods
  20218. Buffer.prototype.create = function (data) {
  20219. if (!data && this._buffer) {
  20220. return; // nothing to do
  20221. }
  20222. data = data || this._data;
  20223. if (!this._buffer) {
  20224. if (this._updatable) {
  20225. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20226. this._data = data;
  20227. }
  20228. else {
  20229. this._buffer = this._engine.createVertexBuffer(data);
  20230. }
  20231. }
  20232. else if (this._updatable) {
  20233. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20234. this._data = data;
  20235. }
  20236. };
  20237. Buffer.prototype._rebuild = function () {
  20238. this._buffer = null;
  20239. this.create(this._data);
  20240. };
  20241. Buffer.prototype.update = function (data) {
  20242. this.create(data);
  20243. };
  20244. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20245. if (!this._buffer) {
  20246. return;
  20247. }
  20248. if (this._updatable) {
  20249. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20250. this._data = null;
  20251. }
  20252. };
  20253. Buffer.prototype.dispose = function () {
  20254. if (!this._buffer) {
  20255. return;
  20256. }
  20257. if (this._engine._releaseBuffer(this._buffer)) {
  20258. this._buffer = null;
  20259. }
  20260. };
  20261. return Buffer;
  20262. }());
  20263. BABYLON.Buffer = Buffer;
  20264. })(BABYLON || (BABYLON = {}));
  20265. //# sourceMappingURL=babylon.buffer.js.map
  20266. var BABYLON;
  20267. (function (BABYLON) {
  20268. var VertexBuffer = (function () {
  20269. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20270. if (!stride) {
  20271. // Deduce stride from kind
  20272. switch (kind) {
  20273. case VertexBuffer.PositionKind:
  20274. stride = 3;
  20275. break;
  20276. case VertexBuffer.NormalKind:
  20277. stride = 3;
  20278. break;
  20279. case VertexBuffer.UVKind:
  20280. case VertexBuffer.UV2Kind:
  20281. case VertexBuffer.UV3Kind:
  20282. case VertexBuffer.UV4Kind:
  20283. case VertexBuffer.UV5Kind:
  20284. case VertexBuffer.UV6Kind:
  20285. stride = 2;
  20286. break;
  20287. case VertexBuffer.TangentKind:
  20288. case VertexBuffer.ColorKind:
  20289. stride = 4;
  20290. break;
  20291. case VertexBuffer.MatricesIndicesKind:
  20292. case VertexBuffer.MatricesIndicesExtraKind:
  20293. stride = 4;
  20294. break;
  20295. case VertexBuffer.MatricesWeightsKind:
  20296. case VertexBuffer.MatricesWeightsExtraKind:
  20297. stride = 4;
  20298. break;
  20299. }
  20300. }
  20301. if (data instanceof BABYLON.Buffer) {
  20302. if (!stride) {
  20303. stride = data.getStrideSize();
  20304. }
  20305. this._buffer = data;
  20306. this._ownsBuffer = false;
  20307. }
  20308. else {
  20309. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20310. this._ownsBuffer = true;
  20311. }
  20312. this._stride = stride;
  20313. this._offset = offset ? offset : 0;
  20314. this._size = size ? size : stride;
  20315. this._kind = kind;
  20316. }
  20317. VertexBuffer.prototype._rebuild = function () {
  20318. if (!this._buffer) {
  20319. return;
  20320. }
  20321. this._buffer._rebuild();
  20322. };
  20323. /**
  20324. * Returns the kind of the VertexBuffer (string).
  20325. */
  20326. VertexBuffer.prototype.getKind = function () {
  20327. return this._kind;
  20328. };
  20329. // Properties
  20330. /**
  20331. * Boolean : is the VertexBuffer updatable ?
  20332. */
  20333. VertexBuffer.prototype.isUpdatable = function () {
  20334. return this._buffer.isUpdatable();
  20335. };
  20336. /**
  20337. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20338. */
  20339. VertexBuffer.prototype.getData = function () {
  20340. return this._buffer.getData();
  20341. };
  20342. /**
  20343. * Returns the WebGLBuffer associated to the VertexBuffer.
  20344. */
  20345. VertexBuffer.prototype.getBuffer = function () {
  20346. return this._buffer.getBuffer();
  20347. };
  20348. /**
  20349. * Returns the stride of the VertexBuffer (integer).
  20350. */
  20351. VertexBuffer.prototype.getStrideSize = function () {
  20352. return this._stride;
  20353. };
  20354. /**
  20355. * Returns the offset (integer).
  20356. */
  20357. VertexBuffer.prototype.getOffset = function () {
  20358. return this._offset;
  20359. };
  20360. /**
  20361. * Returns the VertexBuffer total size (integer).
  20362. */
  20363. VertexBuffer.prototype.getSize = function () {
  20364. return this._size;
  20365. };
  20366. /**
  20367. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20368. */
  20369. VertexBuffer.prototype.getIsInstanced = function () {
  20370. return this._buffer.getIsInstanced();
  20371. };
  20372. /**
  20373. * Returns the instancing divisor, zero for non-instanced (integer).
  20374. */
  20375. VertexBuffer.prototype.getInstanceDivisor = function () {
  20376. return this._buffer.instanceDivisor;
  20377. };
  20378. // Methods
  20379. /**
  20380. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20381. * Returns the created WebGLBuffer.
  20382. */
  20383. VertexBuffer.prototype.create = function (data) {
  20384. return this._buffer.create(data);
  20385. };
  20386. /**
  20387. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20388. * Returns the updated WebGLBuffer.
  20389. */
  20390. VertexBuffer.prototype.update = function (data) {
  20391. return this._buffer.update(data);
  20392. };
  20393. /**
  20394. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20395. * Returns the directly updated WebGLBuffer.
  20396. */
  20397. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20398. return this._buffer.updateDirectly(data, offset);
  20399. };
  20400. /**
  20401. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20402. */
  20403. VertexBuffer.prototype.dispose = function () {
  20404. if (this._ownsBuffer) {
  20405. this._buffer.dispose();
  20406. }
  20407. };
  20408. Object.defineProperty(VertexBuffer, "PositionKind", {
  20409. get: function () {
  20410. return VertexBuffer._PositionKind;
  20411. },
  20412. enumerable: true,
  20413. configurable: true
  20414. });
  20415. Object.defineProperty(VertexBuffer, "NormalKind", {
  20416. get: function () {
  20417. return VertexBuffer._NormalKind;
  20418. },
  20419. enumerable: true,
  20420. configurable: true
  20421. });
  20422. Object.defineProperty(VertexBuffer, "TangentKind", {
  20423. get: function () {
  20424. return VertexBuffer._TangentKind;
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. Object.defineProperty(VertexBuffer, "UVKind", {
  20430. get: function () {
  20431. return VertexBuffer._UVKind;
  20432. },
  20433. enumerable: true,
  20434. configurable: true
  20435. });
  20436. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20437. get: function () {
  20438. return VertexBuffer._UV2Kind;
  20439. },
  20440. enumerable: true,
  20441. configurable: true
  20442. });
  20443. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20444. get: function () {
  20445. return VertexBuffer._UV3Kind;
  20446. },
  20447. enumerable: true,
  20448. configurable: true
  20449. });
  20450. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20451. get: function () {
  20452. return VertexBuffer._UV4Kind;
  20453. },
  20454. enumerable: true,
  20455. configurable: true
  20456. });
  20457. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20458. get: function () {
  20459. return VertexBuffer._UV5Kind;
  20460. },
  20461. enumerable: true,
  20462. configurable: true
  20463. });
  20464. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20465. get: function () {
  20466. return VertexBuffer._UV6Kind;
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. Object.defineProperty(VertexBuffer, "ColorKind", {
  20472. get: function () {
  20473. return VertexBuffer._ColorKind;
  20474. },
  20475. enumerable: true,
  20476. configurable: true
  20477. });
  20478. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20479. get: function () {
  20480. return VertexBuffer._MatricesIndicesKind;
  20481. },
  20482. enumerable: true,
  20483. configurable: true
  20484. });
  20485. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20486. get: function () {
  20487. return VertexBuffer._MatricesWeightsKind;
  20488. },
  20489. enumerable: true,
  20490. configurable: true
  20491. });
  20492. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20493. get: function () {
  20494. return VertexBuffer._MatricesIndicesExtraKind;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20500. get: function () {
  20501. return VertexBuffer._MatricesWeightsExtraKind;
  20502. },
  20503. enumerable: true,
  20504. configurable: true
  20505. });
  20506. // Enums
  20507. VertexBuffer._PositionKind = "position";
  20508. VertexBuffer._NormalKind = "normal";
  20509. VertexBuffer._TangentKind = "tangent";
  20510. VertexBuffer._UVKind = "uv";
  20511. VertexBuffer._UV2Kind = "uv2";
  20512. VertexBuffer._UV3Kind = "uv3";
  20513. VertexBuffer._UV4Kind = "uv4";
  20514. VertexBuffer._UV5Kind = "uv5";
  20515. VertexBuffer._UV6Kind = "uv6";
  20516. VertexBuffer._ColorKind = "color";
  20517. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20518. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20519. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20520. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20521. return VertexBuffer;
  20522. }());
  20523. BABYLON.VertexBuffer = VertexBuffer;
  20524. })(BABYLON || (BABYLON = {}));
  20525. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20526. var BABYLON;
  20527. (function (BABYLON) {
  20528. var InternalTexture = (function () {
  20529. function InternalTexture(engine, dataSource) {
  20530. this.onLoadedObservable = new BABYLON.Observable();
  20531. // Private
  20532. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20533. this._references = 1;
  20534. this._engine = engine;
  20535. this._dataSource = dataSource;
  20536. this._webGLTexture = engine._createTexture();
  20537. }
  20538. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20539. get: function () {
  20540. return this._dataSource;
  20541. },
  20542. enumerable: true,
  20543. configurable: true
  20544. });
  20545. InternalTexture.prototype.incrementReferences = function () {
  20546. this._references++;
  20547. };
  20548. InternalTexture.prototype.updateSize = function (width, height) {
  20549. this.width = width;
  20550. this.height = height;
  20551. this._size = width * height;
  20552. this.baseWidth = width;
  20553. this.baseHeight = height;
  20554. };
  20555. InternalTexture.prototype._rebuild = function () {
  20556. var _this = this;
  20557. var proxy;
  20558. this.isReady = false;
  20559. this._cachedCoordinatesMode = null;
  20560. this._cachedWrapU = null;
  20561. this._cachedWrapV = null;
  20562. this._cachedAnisotropicFilteringLevel = null;
  20563. switch (this._dataSource) {
  20564. case InternalTexture.DATASOURCE_TEMP:
  20565. return;
  20566. case InternalTexture.DATASOURCE_URL:
  20567. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20568. _this.isReady = true;
  20569. }, null, this._buffer, null, this.format);
  20570. proxy._swapAndDie(this);
  20571. return;
  20572. case InternalTexture.DATASOURCE_RAW:
  20573. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20574. proxy._swapAndDie(this);
  20575. this.isReady = true;
  20576. return;
  20577. case InternalTexture.DATASOURCE_DYNAMIC:
  20578. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20579. proxy._swapAndDie(this);
  20580. // The engine will make sure to update content so no need to flag it as isReady = true
  20581. return;
  20582. case InternalTexture.DATASOURCE_RENDERTARGET:
  20583. var options = new BABYLON.RenderTargetCreationOptions();
  20584. options.generateDepthBuffer = this._generateDepthBuffer;
  20585. options.generateMipMaps = this.generateMipMaps;
  20586. options.generateStencilBuffer = this._generateStencilBuffer;
  20587. options.samplingMode = this.samplingMode;
  20588. options.type = this.type;
  20589. if (this.isCube) {
  20590. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20591. }
  20592. else {
  20593. var size = {
  20594. width: this.width,
  20595. height: this.height
  20596. };
  20597. proxy = this._engine.createRenderTargetTexture(size, options);
  20598. }
  20599. proxy._swapAndDie(this);
  20600. this.isReady = true;
  20601. return;
  20602. case InternalTexture.DATASOURCE_CUBE:
  20603. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20604. _this.isReady = true;
  20605. }, null, this.format, this._extension);
  20606. proxy._swapAndDie(this);
  20607. return;
  20608. case InternalTexture.DATASOURCE_CUBERAW:
  20609. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20610. proxy._swapAndDie(this);
  20611. this.isReady = true;
  20612. return;
  20613. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20614. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20615. proxy._swapAndDie(_this);
  20616. _this.isReady = true;
  20617. }, null, this.format, this._extension);
  20618. return;
  20619. }
  20620. };
  20621. InternalTexture.prototype._swapAndDie = function (target) {
  20622. target._webGLTexture = this._webGLTexture;
  20623. if (this._framebuffer) {
  20624. target._framebuffer = this._framebuffer;
  20625. }
  20626. if (this._depthStencilBuffer) {
  20627. target._depthStencilBuffer = this._depthStencilBuffer;
  20628. }
  20629. if (this._lodTextureHigh) {
  20630. if (target._lodTextureHigh) {
  20631. target._lodTextureHigh.dispose();
  20632. }
  20633. target._lodTextureHigh = this._lodTextureHigh;
  20634. }
  20635. if (this._lodTextureMid) {
  20636. if (target._lodTextureMid) {
  20637. target._lodTextureMid.dispose();
  20638. }
  20639. target._lodTextureMid = this._lodTextureMid;
  20640. }
  20641. if (this._lodTextureLow) {
  20642. if (target._lodTextureLow) {
  20643. target._lodTextureLow.dispose();
  20644. }
  20645. target._lodTextureLow = this._lodTextureLow;
  20646. }
  20647. var cache = this._engine.getLoadedTexturesCache();
  20648. var index = cache.indexOf(this);
  20649. if (index !== -1) {
  20650. cache.splice(index, 1);
  20651. }
  20652. };
  20653. InternalTexture.prototype.dispose = function () {
  20654. if (!this._webGLTexture) {
  20655. return;
  20656. }
  20657. this._references--;
  20658. if (this._references === 0) {
  20659. this._engine._releaseTexture(this);
  20660. this._webGLTexture = null;
  20661. }
  20662. };
  20663. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20664. InternalTexture.DATASOURCE_URL = 1;
  20665. InternalTexture.DATASOURCE_TEMP = 2;
  20666. InternalTexture.DATASOURCE_RAW = 3;
  20667. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20668. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20669. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20670. InternalTexture.DATASOURCE_CUBE = 7;
  20671. InternalTexture.DATASOURCE_CUBERAW = 8;
  20672. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20673. return InternalTexture;
  20674. }());
  20675. BABYLON.InternalTexture = InternalTexture;
  20676. })(BABYLON || (BABYLON = {}));
  20677. //# sourceMappingURL=babylon.internalTexture.js.map
  20678. var BABYLON;
  20679. (function (BABYLON) {
  20680. var BaseTexture = (function () {
  20681. function BaseTexture(scene) {
  20682. this._hasAlpha = false;
  20683. this.getAlphaFromRGB = false;
  20684. this.level = 1;
  20685. this.coordinatesIndex = 0;
  20686. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20687. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20688. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20689. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20690. this.isCube = false;
  20691. this.gammaSpace = true;
  20692. this.invertZ = false;
  20693. this.lodLevelInAlpha = false;
  20694. this.lodGenerationOffset = 0.0;
  20695. this.lodGenerationScale = 0.8;
  20696. this.isRenderTarget = false;
  20697. this.animations = new Array();
  20698. /**
  20699. * An event triggered when the texture is disposed.
  20700. * @type {BABYLON.Observable}
  20701. */
  20702. this.onDisposeObservable = new BABYLON.Observable();
  20703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20704. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20705. this._scene.textures.push(this);
  20706. this._uid = null;
  20707. }
  20708. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20709. get: function () {
  20710. return this._hasAlpha;
  20711. },
  20712. set: function (value) {
  20713. if (this._hasAlpha === value) {
  20714. return;
  20715. }
  20716. this._hasAlpha = value;
  20717. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20718. },
  20719. enumerable: true,
  20720. configurable: true
  20721. });
  20722. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20723. get: function () {
  20724. return this._coordinatesMode;
  20725. },
  20726. set: function (value) {
  20727. if (this._coordinatesMode === value) {
  20728. return;
  20729. }
  20730. this._coordinatesMode = value;
  20731. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20732. },
  20733. enumerable: true,
  20734. configurable: true
  20735. });
  20736. Object.defineProperty(BaseTexture.prototype, "uid", {
  20737. get: function () {
  20738. if (!this._uid) {
  20739. this._uid = BABYLON.Tools.RandomId();
  20740. }
  20741. return this._uid;
  20742. },
  20743. enumerable: true,
  20744. configurable: true
  20745. });
  20746. BaseTexture.prototype.toString = function () {
  20747. return this.name;
  20748. };
  20749. BaseTexture.prototype.getClassName = function () {
  20750. return "BaseTexture";
  20751. };
  20752. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20753. set: function (callback) {
  20754. if (this._onDisposeObserver) {
  20755. this.onDisposeObservable.remove(this._onDisposeObserver);
  20756. }
  20757. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20758. },
  20759. enumerable: true,
  20760. configurable: true
  20761. });
  20762. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20763. get: function () {
  20764. return true;
  20765. },
  20766. enumerable: true,
  20767. configurable: true
  20768. });
  20769. BaseTexture.prototype.getScene = function () {
  20770. return this._scene;
  20771. };
  20772. BaseTexture.prototype.getTextureMatrix = function () {
  20773. return null;
  20774. };
  20775. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20776. return null;
  20777. };
  20778. BaseTexture.prototype.getInternalTexture = function () {
  20779. return this._texture;
  20780. };
  20781. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20782. return !this.isBlocking || this.isReady();
  20783. };
  20784. BaseTexture.prototype.isReady = function () {
  20785. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20786. this.delayLoad();
  20787. return false;
  20788. }
  20789. if (this._texture) {
  20790. return this._texture.isReady;
  20791. }
  20792. return false;
  20793. };
  20794. BaseTexture.prototype.getSize = function () {
  20795. if (this._texture.width) {
  20796. return new BABYLON.Size(this._texture.width, this._texture.height);
  20797. }
  20798. if (this._texture._size) {
  20799. return new BABYLON.Size(this._texture._size, this._texture._size);
  20800. }
  20801. return BABYLON.Size.Zero();
  20802. };
  20803. BaseTexture.prototype.getBaseSize = function () {
  20804. if (!this.isReady() || !this._texture)
  20805. return BABYLON.Size.Zero();
  20806. if (this._texture._size) {
  20807. return new BABYLON.Size(this._texture._size, this._texture._size);
  20808. }
  20809. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20810. };
  20811. BaseTexture.prototype.scale = function (ratio) {
  20812. };
  20813. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20814. get: function () {
  20815. return false;
  20816. },
  20817. enumerable: true,
  20818. configurable: true
  20819. });
  20820. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20821. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20822. for (var index = 0; index < texturesCache.length; index++) {
  20823. var texturesCacheEntry = texturesCache[index];
  20824. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20825. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20826. texturesCacheEntry.incrementReferences();
  20827. return texturesCacheEntry;
  20828. }
  20829. }
  20830. }
  20831. return null;
  20832. };
  20833. BaseTexture.prototype._rebuild = function () {
  20834. };
  20835. BaseTexture.prototype.delayLoad = function () {
  20836. };
  20837. BaseTexture.prototype.clone = function () {
  20838. return null;
  20839. };
  20840. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20841. get: function () {
  20842. if (!this._texture) {
  20843. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20844. }
  20845. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20846. },
  20847. enumerable: true,
  20848. configurable: true
  20849. });
  20850. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20851. get: function () {
  20852. if (!this._texture) {
  20853. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20854. }
  20855. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20856. },
  20857. enumerable: true,
  20858. configurable: true
  20859. });
  20860. BaseTexture.prototype.readPixels = function (faceIndex) {
  20861. if (faceIndex === void 0) { faceIndex = 0; }
  20862. if (!this._texture) {
  20863. return null;
  20864. }
  20865. var size = this.getSize();
  20866. var engine = this.getScene().getEngine();
  20867. if (this._texture.isCube) {
  20868. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20869. }
  20870. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20871. };
  20872. BaseTexture.prototype.releaseInternalTexture = function () {
  20873. if (this._texture) {
  20874. this._texture.dispose();
  20875. this._texture = null;
  20876. }
  20877. };
  20878. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20879. get: function () {
  20880. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20881. return null;
  20882. }
  20883. if (!this._texture._sphericalPolynomial) {
  20884. this._texture._sphericalPolynomial =
  20885. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20886. }
  20887. return this._texture._sphericalPolynomial;
  20888. },
  20889. set: function (value) {
  20890. if (this._texture) {
  20891. this._texture._sphericalPolynomial = value;
  20892. }
  20893. },
  20894. enumerable: true,
  20895. configurable: true
  20896. });
  20897. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20898. get: function () {
  20899. if (this._texture) {
  20900. return this._texture._lodTextureHigh;
  20901. }
  20902. return null;
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20908. get: function () {
  20909. if (this._texture) {
  20910. return this._texture._lodTextureMid;
  20911. }
  20912. return null;
  20913. },
  20914. enumerable: true,
  20915. configurable: true
  20916. });
  20917. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20918. get: function () {
  20919. if (this._texture) {
  20920. return this._texture._lodTextureLow;
  20921. }
  20922. return null;
  20923. },
  20924. enumerable: true,
  20925. configurable: true
  20926. });
  20927. BaseTexture.prototype.dispose = function () {
  20928. // Animations
  20929. this.getScene().stopAnimation(this);
  20930. // Remove from scene
  20931. this._scene._removePendingData(this);
  20932. var index = this._scene.textures.indexOf(this);
  20933. if (index >= 0) {
  20934. this._scene.textures.splice(index, 1);
  20935. }
  20936. if (this._texture === undefined) {
  20937. return;
  20938. }
  20939. // Release
  20940. this.releaseInternalTexture();
  20941. // Callback
  20942. this.onDisposeObservable.notifyObservers(this);
  20943. this.onDisposeObservable.clear();
  20944. };
  20945. BaseTexture.prototype.serialize = function () {
  20946. if (!this.name) {
  20947. return null;
  20948. }
  20949. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20950. // Animations
  20951. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20952. return serializationObject;
  20953. };
  20954. BaseTexture.WhenAllReady = function (textures, callback) {
  20955. var numRemaining = textures.length;
  20956. if (numRemaining === 0) {
  20957. callback();
  20958. return;
  20959. }
  20960. var _loop_1 = function () {
  20961. texture = textures[i];
  20962. if (texture.isReady()) {
  20963. if (--numRemaining === 0) {
  20964. callback();
  20965. }
  20966. }
  20967. else {
  20968. onLoadObservable = texture.onLoadObservable;
  20969. var onLoadCallback_1 = function () {
  20970. onLoadObservable.removeCallback(onLoadCallback_1);
  20971. if (--numRemaining === 0) {
  20972. callback();
  20973. }
  20974. };
  20975. onLoadObservable.add(onLoadCallback_1);
  20976. }
  20977. };
  20978. var texture, onLoadObservable;
  20979. for (var i = 0; i < textures.length; i++) {
  20980. _loop_1();
  20981. }
  20982. };
  20983. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20984. __decorate([
  20985. BABYLON.serialize()
  20986. ], BaseTexture.prototype, "name", void 0);
  20987. __decorate([
  20988. BABYLON.serialize("hasAlpha")
  20989. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20990. __decorate([
  20991. BABYLON.serialize()
  20992. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20993. __decorate([
  20994. BABYLON.serialize()
  20995. ], BaseTexture.prototype, "level", void 0);
  20996. __decorate([
  20997. BABYLON.serialize()
  20998. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20999. __decorate([
  21000. BABYLON.serialize("coordinatesMode")
  21001. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21002. __decorate([
  21003. BABYLON.serialize()
  21004. ], BaseTexture.prototype, "wrapU", void 0);
  21005. __decorate([
  21006. BABYLON.serialize()
  21007. ], BaseTexture.prototype, "wrapV", void 0);
  21008. __decorate([
  21009. BABYLON.serialize()
  21010. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21011. __decorate([
  21012. BABYLON.serialize()
  21013. ], BaseTexture.prototype, "isCube", void 0);
  21014. __decorate([
  21015. BABYLON.serialize()
  21016. ], BaseTexture.prototype, "gammaSpace", void 0);
  21017. __decorate([
  21018. BABYLON.serialize()
  21019. ], BaseTexture.prototype, "invertZ", void 0);
  21020. __decorate([
  21021. BABYLON.serialize()
  21022. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21023. __decorate([
  21024. BABYLON.serialize()
  21025. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21026. __decorate([
  21027. BABYLON.serialize()
  21028. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21029. __decorate([
  21030. BABYLON.serialize()
  21031. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21032. return BaseTexture;
  21033. }());
  21034. BABYLON.BaseTexture = BaseTexture;
  21035. })(BABYLON || (BABYLON = {}));
  21036. //# sourceMappingURL=babylon.baseTexture.js.map
  21037. var BABYLON;
  21038. (function (BABYLON) {
  21039. var Texture = (function (_super) {
  21040. __extends(Texture, _super);
  21041. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21042. if (noMipmap === void 0) { noMipmap = false; }
  21043. if (invertY === void 0) { invertY = true; }
  21044. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21045. if (onLoad === void 0) { onLoad = null; }
  21046. if (onError === void 0) { onError = null; }
  21047. if (buffer === void 0) { buffer = null; }
  21048. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21049. var _this = _super.call(this, scene) || this;
  21050. _this.uOffset = 0;
  21051. _this.vOffset = 0;
  21052. _this.uScale = 1.0;
  21053. _this.vScale = 1.0;
  21054. _this.uAng = 0;
  21055. _this.vAng = 0;
  21056. _this.wAng = 0;
  21057. _this._isBlocking = true;
  21058. _this.name = url;
  21059. _this.url = url;
  21060. _this._noMipmap = noMipmap;
  21061. _this._invertY = invertY;
  21062. _this._samplingMode = samplingMode;
  21063. _this._buffer = buffer;
  21064. _this._deleteBuffer = deleteBuffer;
  21065. _this._format = format;
  21066. scene = _this.getScene();
  21067. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21068. var load = function () {
  21069. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21070. _this.onLoadObservable.notifyObservers(_this);
  21071. }
  21072. if (onLoad) {
  21073. onLoad();
  21074. }
  21075. if (!_this.isBlocking) {
  21076. scene.resetCachedMaterial();
  21077. }
  21078. };
  21079. if (!_this.url) {
  21080. _this._delayedOnLoad = load;
  21081. _this._delayedOnError = onError;
  21082. return _this;
  21083. }
  21084. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21085. if (!_this._texture) {
  21086. if (!scene.useDelayedTextureLoading) {
  21087. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  21088. if (deleteBuffer) {
  21089. delete _this._buffer;
  21090. }
  21091. }
  21092. else {
  21093. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21094. _this._delayedOnLoad = load;
  21095. _this._delayedOnError = onError;
  21096. }
  21097. }
  21098. else {
  21099. if (_this._texture.isReady) {
  21100. BABYLON.Tools.SetImmediate(function () { return load(); });
  21101. }
  21102. else {
  21103. _this._texture.onLoadedObservable.add(load);
  21104. }
  21105. }
  21106. return _this;
  21107. }
  21108. Object.defineProperty(Texture.prototype, "noMipmap", {
  21109. get: function () {
  21110. return this._noMipmap;
  21111. },
  21112. enumerable: true,
  21113. configurable: true
  21114. });
  21115. Object.defineProperty(Texture.prototype, "isBlocking", {
  21116. get: function () {
  21117. return this._isBlocking;
  21118. },
  21119. set: function (value) {
  21120. this._isBlocking = value;
  21121. },
  21122. enumerable: true,
  21123. configurable: true
  21124. });
  21125. Object.defineProperty(Texture.prototype, "samplingMode", {
  21126. get: function () {
  21127. return this._samplingMode;
  21128. },
  21129. enumerable: true,
  21130. configurable: true
  21131. });
  21132. Texture.prototype.updateURL = function (url) {
  21133. this.url = url;
  21134. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21135. this.delayLoad();
  21136. };
  21137. Texture.prototype.delayLoad = function () {
  21138. var _this = this;
  21139. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21140. return;
  21141. }
  21142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21143. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21144. if (!this._texture) {
  21145. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  21146. if (this._deleteBuffer) {
  21147. delete this._buffer;
  21148. }
  21149. }
  21150. else {
  21151. if (this._texture.isReady) {
  21152. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  21153. }
  21154. else {
  21155. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21156. }
  21157. }
  21158. };
  21159. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21160. if (!this._texture) {
  21161. return;
  21162. }
  21163. this._samplingMode = samplingMode;
  21164. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21165. };
  21166. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21167. x *= this.uScale;
  21168. y *= this.vScale;
  21169. x -= 0.5 * this.uScale;
  21170. y -= 0.5 * this.vScale;
  21171. z -= 0.5;
  21172. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21173. t.x += 0.5 * this.uScale + this.uOffset;
  21174. t.y += 0.5 * this.vScale + this.vOffset;
  21175. t.z += 0.5;
  21176. };
  21177. Texture.prototype.getTextureMatrix = function () {
  21178. var _this = this;
  21179. if (this.uOffset === this._cachedUOffset &&
  21180. this.vOffset === this._cachedVOffset &&
  21181. this.uScale === this._cachedUScale &&
  21182. this.vScale === this._cachedVScale &&
  21183. this.uAng === this._cachedUAng &&
  21184. this.vAng === this._cachedVAng &&
  21185. this.wAng === this._cachedWAng) {
  21186. return this._cachedTextureMatrix;
  21187. }
  21188. this._cachedUOffset = this.uOffset;
  21189. this._cachedVOffset = this.vOffset;
  21190. this._cachedUScale = this.uScale;
  21191. this._cachedVScale = this.vScale;
  21192. this._cachedUAng = this.uAng;
  21193. this._cachedVAng = this.vAng;
  21194. this._cachedWAng = this.wAng;
  21195. if (!this._cachedTextureMatrix) {
  21196. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21197. this._rowGenerationMatrix = new BABYLON.Matrix();
  21198. this._t0 = BABYLON.Vector3.Zero();
  21199. this._t1 = BABYLON.Vector3.Zero();
  21200. this._t2 = BABYLON.Vector3.Zero();
  21201. }
  21202. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21203. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21204. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21205. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21206. this._t1.subtractInPlace(this._t0);
  21207. this._t2.subtractInPlace(this._t0);
  21208. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21209. this._cachedTextureMatrix.m[0] = this._t1.x;
  21210. this._cachedTextureMatrix.m[1] = this._t1.y;
  21211. this._cachedTextureMatrix.m[2] = this._t1.z;
  21212. this._cachedTextureMatrix.m[4] = this._t2.x;
  21213. this._cachedTextureMatrix.m[5] = this._t2.y;
  21214. this._cachedTextureMatrix.m[6] = this._t2.z;
  21215. this._cachedTextureMatrix.m[8] = this._t0.x;
  21216. this._cachedTextureMatrix.m[9] = this._t0.y;
  21217. this._cachedTextureMatrix.m[10] = this._t0.z;
  21218. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21219. return mat.hasTexture(_this);
  21220. });
  21221. return this._cachedTextureMatrix;
  21222. };
  21223. Texture.prototype.getReflectionTextureMatrix = function () {
  21224. var _this = this;
  21225. var scene = this.getScene();
  21226. if (this.uOffset === this._cachedUOffset &&
  21227. this.vOffset === this._cachedVOffset &&
  21228. this.uScale === this._cachedUScale &&
  21229. this.vScale === this._cachedVScale &&
  21230. this.coordinatesMode === this._cachedCoordinatesMode) {
  21231. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21232. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21233. return this._cachedTextureMatrix;
  21234. }
  21235. }
  21236. else {
  21237. return this._cachedTextureMatrix;
  21238. }
  21239. }
  21240. if (!this._cachedTextureMatrix) {
  21241. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21242. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21243. }
  21244. this._cachedUOffset = this.uOffset;
  21245. this._cachedVOffset = this.vOffset;
  21246. this._cachedUScale = this.uScale;
  21247. this._cachedVScale = this.vScale;
  21248. this._cachedCoordinatesMode = this.coordinatesMode;
  21249. switch (this.coordinatesMode) {
  21250. case Texture.PLANAR_MODE:
  21251. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21252. this._cachedTextureMatrix[0] = this.uScale;
  21253. this._cachedTextureMatrix[5] = this.vScale;
  21254. this._cachedTextureMatrix[12] = this.uOffset;
  21255. this._cachedTextureMatrix[13] = this.vOffset;
  21256. break;
  21257. case Texture.PROJECTION_MODE:
  21258. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21259. this._projectionModeMatrix.m[0] = 0.5;
  21260. this._projectionModeMatrix.m[5] = -0.5;
  21261. this._projectionModeMatrix.m[10] = 0.0;
  21262. this._projectionModeMatrix.m[12] = 0.5;
  21263. this._projectionModeMatrix.m[13] = 0.5;
  21264. this._projectionModeMatrix.m[14] = 1.0;
  21265. this._projectionModeMatrix.m[15] = 1.0;
  21266. var projectionMatrix = scene.getProjectionMatrix();
  21267. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21268. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21269. break;
  21270. default:
  21271. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21272. break;
  21273. }
  21274. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21275. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21276. });
  21277. return this._cachedTextureMatrix;
  21278. };
  21279. Texture.prototype.clone = function () {
  21280. var _this = this;
  21281. return BABYLON.SerializationHelper.Clone(function () {
  21282. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21283. }, this);
  21284. };
  21285. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21286. get: function () {
  21287. if (!this._onLoadObservable) {
  21288. this._onLoadObservable = new BABYLON.Observable();
  21289. }
  21290. return this._onLoadObservable;
  21291. },
  21292. enumerable: true,
  21293. configurable: true
  21294. });
  21295. Texture.prototype.serialize = function () {
  21296. var serializationObject = _super.prototype.serialize.call(this);
  21297. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21298. serializationObject.base64String = this._buffer;
  21299. serializationObject.name = serializationObject.name.replace("data:", "");
  21300. }
  21301. return serializationObject;
  21302. };
  21303. Texture.prototype.getClassName = function () {
  21304. return "Texture";
  21305. };
  21306. Texture.prototype.dispose = function () {
  21307. _super.prototype.dispose.call(this);
  21308. if (this.onLoadObservable) {
  21309. this.onLoadObservable.clear();
  21310. this._onLoadObservable = null;
  21311. }
  21312. this._delayedOnLoad = null;
  21313. this._delayedOnError = null;
  21314. };
  21315. // Statics
  21316. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21317. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21318. if (onLoad === void 0) { onLoad = null; }
  21319. if (onError === void 0) { onError = null; }
  21320. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21321. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21322. };
  21323. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21324. if (parsedTexture.customType) {
  21325. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21326. // Update Sampling Mode
  21327. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21328. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21329. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21330. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21331. }
  21332. }
  21333. return parsedCustomTexture;
  21334. }
  21335. if (parsedTexture.isCube) {
  21336. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21337. }
  21338. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21339. return null;
  21340. }
  21341. var texture = BABYLON.SerializationHelper.Parse(function () {
  21342. if (parsedTexture.mirrorPlane) {
  21343. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21344. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21345. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21346. return mirrorTexture;
  21347. }
  21348. else if (parsedTexture.isRenderTarget) {
  21349. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21350. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21351. return renderTargetTexture;
  21352. }
  21353. else {
  21354. var texture;
  21355. if (parsedTexture.base64String) {
  21356. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21357. }
  21358. else {
  21359. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21360. }
  21361. return texture;
  21362. }
  21363. }, parsedTexture, scene);
  21364. // Update Sampling Mode
  21365. if (parsedTexture.samplingMode) {
  21366. var sampling = parsedTexture.samplingMode;
  21367. if (texture._samplingMode !== sampling) {
  21368. texture.updateSamplingMode(sampling);
  21369. }
  21370. }
  21371. // Animations
  21372. if (parsedTexture.animations) {
  21373. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21374. var parsedAnimation = parsedTexture.animations[animationIndex];
  21375. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21376. }
  21377. }
  21378. return texture;
  21379. };
  21380. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21381. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21382. if (noMipmap === void 0) { noMipmap = false; }
  21383. if (invertY === void 0) { invertY = true; }
  21384. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21385. if (onLoad === void 0) { onLoad = null; }
  21386. if (onError === void 0) { onError = null; }
  21387. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21388. if (name.substr(0, 5) !== "data:") {
  21389. name = "data:" + name;
  21390. }
  21391. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21392. };
  21393. // Constants
  21394. Texture.NEAREST_SAMPLINGMODE = 1;
  21395. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21396. Texture.BILINEAR_SAMPLINGMODE = 2;
  21397. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21398. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21399. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21400. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21401. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21402. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21403. Texture.NEAREST_LINEAR = 7;
  21404. Texture.NEAREST_NEAREST = 8;
  21405. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21406. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21407. Texture.LINEAR_LINEAR = 11;
  21408. Texture.LINEAR_NEAREST = 12;
  21409. Texture.EXPLICIT_MODE = 0;
  21410. Texture.SPHERICAL_MODE = 1;
  21411. Texture.PLANAR_MODE = 2;
  21412. Texture.CUBIC_MODE = 3;
  21413. Texture.PROJECTION_MODE = 4;
  21414. Texture.SKYBOX_MODE = 5;
  21415. Texture.INVCUBIC_MODE = 6;
  21416. Texture.EQUIRECTANGULAR_MODE = 7;
  21417. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21418. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21419. Texture.CLAMP_ADDRESSMODE = 0;
  21420. Texture.WRAP_ADDRESSMODE = 1;
  21421. Texture.MIRROR_ADDRESSMODE = 2;
  21422. __decorate([
  21423. BABYLON.serialize()
  21424. ], Texture.prototype, "url", void 0);
  21425. __decorate([
  21426. BABYLON.serialize()
  21427. ], Texture.prototype, "uOffset", void 0);
  21428. __decorate([
  21429. BABYLON.serialize()
  21430. ], Texture.prototype, "vOffset", void 0);
  21431. __decorate([
  21432. BABYLON.serialize()
  21433. ], Texture.prototype, "uScale", void 0);
  21434. __decorate([
  21435. BABYLON.serialize()
  21436. ], Texture.prototype, "vScale", void 0);
  21437. __decorate([
  21438. BABYLON.serialize()
  21439. ], Texture.prototype, "uAng", void 0);
  21440. __decorate([
  21441. BABYLON.serialize()
  21442. ], Texture.prototype, "vAng", void 0);
  21443. __decorate([
  21444. BABYLON.serialize()
  21445. ], Texture.prototype, "wAng", void 0);
  21446. __decorate([
  21447. BABYLON.serialize()
  21448. ], Texture.prototype, "isBlocking", null);
  21449. return Texture;
  21450. }(BABYLON.BaseTexture));
  21451. BABYLON.Texture = Texture;
  21452. })(BABYLON || (BABYLON = {}));
  21453. //# sourceMappingURL=babylon.texture.js.map
  21454. var BABYLON;
  21455. (function (BABYLON) {
  21456. var _InstancesBatch = (function () {
  21457. function _InstancesBatch() {
  21458. this.mustReturn = false;
  21459. this.visibleInstances = new Array();
  21460. this.renderSelf = new Array();
  21461. }
  21462. return _InstancesBatch;
  21463. }());
  21464. BABYLON._InstancesBatch = _InstancesBatch;
  21465. var Mesh = (function (_super) {
  21466. __extends(Mesh, _super);
  21467. /**
  21468. * @constructor
  21469. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21470. * @param {Scene} scene The scene to add this mesh to.
  21471. * @param {Node} parent The parent of this mesh, if it has one
  21472. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21473. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21474. * When false, achieved by calling a clone(), also passing False.
  21475. * This will make creation of children, recursive.
  21476. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21477. */
  21478. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21479. if (parent === void 0) { parent = null; }
  21480. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21481. var _this = _super.call(this, name, scene) || this;
  21482. // Events
  21483. /**
  21484. * An event triggered before rendering the mesh
  21485. * @type {BABYLON.Observable}
  21486. */
  21487. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21488. /**
  21489. * An event triggered after rendering the mesh
  21490. * @type {BABYLON.Observable}
  21491. */
  21492. _this.onAfterRenderObservable = new BABYLON.Observable();
  21493. /**
  21494. * An event triggered before drawing the mesh
  21495. * @type {BABYLON.Observable}
  21496. */
  21497. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21498. // Members
  21499. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21500. _this.instances = new Array();
  21501. _this._LODLevels = new Array();
  21502. _this._visibleInstances = {};
  21503. _this._renderIdForInstances = new Array();
  21504. _this._batchCache = new _InstancesBatch();
  21505. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21506. // Use by builder only to know what orientation were the mesh build in.
  21507. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21508. _this.overrideMaterialSideOrientation = null;
  21509. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21510. // Will be used to save a source mesh reference, If any
  21511. _this._source = null;
  21512. if (source) {
  21513. // Source mesh
  21514. _this._source = source;
  21515. // Geometry
  21516. if (source._geometry) {
  21517. source._geometry.applyToMesh(_this);
  21518. }
  21519. // Deep copy
  21520. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21521. // Parent
  21522. _this.parent = source.parent;
  21523. // Pivot
  21524. _this.setPivotMatrix(source.getPivotMatrix());
  21525. _this.id = name + "." + source.id;
  21526. // Material
  21527. _this.material = source.material;
  21528. var index;
  21529. if (!doNotCloneChildren) {
  21530. // Children
  21531. for (index = 0; index < scene.meshes.length; index++) {
  21532. var mesh = scene.meshes[index];
  21533. if (mesh.parent === source) {
  21534. // doNotCloneChildren is always going to be False
  21535. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21536. }
  21537. }
  21538. }
  21539. // Physics clone
  21540. var physicsEngine = _this.getScene().getPhysicsEngine();
  21541. if (clonePhysicsImpostor && physicsEngine) {
  21542. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21543. if (impostor) {
  21544. _this.physicsImpostor = impostor.clone(_this);
  21545. }
  21546. }
  21547. // Particles
  21548. for (index = 0; index < scene.particleSystems.length; index++) {
  21549. var system = scene.particleSystems[index];
  21550. if (system.emitter === source) {
  21551. system.clone(system.name, _this);
  21552. }
  21553. }
  21554. _this.computeWorldMatrix(true);
  21555. }
  21556. // Parent
  21557. if (parent !== null) {
  21558. _this.parent = parent;
  21559. }
  21560. return _this;
  21561. }
  21562. Object.defineProperty(Mesh, "FRONTSIDE", {
  21563. /**
  21564. * Mesh side orientation : usually the external or front surface
  21565. */
  21566. get: function () {
  21567. return Mesh._FRONTSIDE;
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Mesh, "BACKSIDE", {
  21573. /**
  21574. * Mesh side orientation : usually the internal or back surface
  21575. */
  21576. get: function () {
  21577. return Mesh._BACKSIDE;
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21583. /**
  21584. * Mesh side orientation : both internal and external or front and back surfaces
  21585. */
  21586. get: function () {
  21587. return Mesh._DOUBLESIDE;
  21588. },
  21589. enumerable: true,
  21590. configurable: true
  21591. });
  21592. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21593. /**
  21594. * Mesh side orientation : by default, `FRONTSIDE`
  21595. */
  21596. get: function () {
  21597. return Mesh._DEFAULTSIDE;
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(Mesh, "NO_CAP", {
  21603. /**
  21604. * Mesh cap setting : no cap
  21605. */
  21606. get: function () {
  21607. return Mesh._NO_CAP;
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Mesh, "CAP_START", {
  21613. /**
  21614. * Mesh cap setting : one cap at the beginning of the mesh
  21615. */
  21616. get: function () {
  21617. return Mesh._CAP_START;
  21618. },
  21619. enumerable: true,
  21620. configurable: true
  21621. });
  21622. Object.defineProperty(Mesh, "CAP_END", {
  21623. /**
  21624. * Mesh cap setting : one cap at the end of the mesh
  21625. */
  21626. get: function () {
  21627. return Mesh._CAP_END;
  21628. },
  21629. enumerable: true,
  21630. configurable: true
  21631. });
  21632. Object.defineProperty(Mesh, "CAP_ALL", {
  21633. /**
  21634. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21635. */
  21636. get: function () {
  21637. return Mesh._CAP_ALL;
  21638. },
  21639. enumerable: true,
  21640. configurable: true
  21641. });
  21642. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21643. set: function (callback) {
  21644. if (this._onBeforeDrawObserver) {
  21645. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21646. }
  21647. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21648. },
  21649. enumerable: true,
  21650. configurable: true
  21651. });
  21652. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21653. get: function () {
  21654. return this._morphTargetManager;
  21655. },
  21656. set: function (value) {
  21657. if (this._morphTargetManager === value) {
  21658. return;
  21659. }
  21660. this._morphTargetManager = value;
  21661. this._syncGeometryWithMorphTargetManager();
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Mesh.prototype, "source", {
  21667. get: function () {
  21668. return this._source;
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. // Methods
  21674. /**
  21675. * Returns the string "Mesh".
  21676. */
  21677. Mesh.prototype.getClassName = function () {
  21678. return "Mesh";
  21679. };
  21680. /**
  21681. * Returns a string.
  21682. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21683. */
  21684. Mesh.prototype.toString = function (fullDetails) {
  21685. var ret = _super.prototype.toString.call(this, fullDetails);
  21686. ret += ", n vertices: " + this.getTotalVertices();
  21687. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21688. if (this.animations) {
  21689. for (var i = 0; i < this.animations.length; i++) {
  21690. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21691. }
  21692. }
  21693. if (fullDetails) {
  21694. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21695. }
  21696. return ret;
  21697. };
  21698. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21699. /**
  21700. * True if the mesh has some Levels Of Details (LOD).
  21701. * Returns a boolean.
  21702. */
  21703. get: function () {
  21704. return this._LODLevels.length > 0;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Mesh.prototype._sortLODLevels = function () {
  21710. this._LODLevels.sort(function (a, b) {
  21711. if (a.distance < b.distance) {
  21712. return 1;
  21713. }
  21714. if (a.distance > b.distance) {
  21715. return -1;
  21716. }
  21717. return 0;
  21718. });
  21719. };
  21720. /**
  21721. * Add a mesh as LOD level triggered at the given distance.
  21722. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21723. * @param {number} distance The distance from the center of the object to show this level
  21724. * @param {Mesh} mesh The mesh to be added as LOD level
  21725. * @return {Mesh} This mesh (for chaining)
  21726. */
  21727. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21728. if (mesh && mesh._masterMesh) {
  21729. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21730. return this;
  21731. }
  21732. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21733. this._LODLevels.push(level);
  21734. if (mesh) {
  21735. mesh._masterMesh = this;
  21736. }
  21737. this._sortLODLevels();
  21738. return this;
  21739. };
  21740. /**
  21741. * Returns the LOD level mesh at the passed distance or null if not found.
  21742. * It is related to the method `addLODLevel(distance, mesh)`.
  21743. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21744. * Returns an object Mesh or `null`.
  21745. */
  21746. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21747. for (var index = 0; index < this._LODLevels.length; index++) {
  21748. var level = this._LODLevels[index];
  21749. if (level.distance === distance) {
  21750. return level.mesh;
  21751. }
  21752. }
  21753. return null;
  21754. };
  21755. /**
  21756. * Remove a mesh from the LOD array
  21757. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21758. * @param {Mesh} mesh The mesh to be removed.
  21759. * @return {Mesh} This mesh (for chaining)
  21760. */
  21761. Mesh.prototype.removeLODLevel = function (mesh) {
  21762. for (var index = 0; index < this._LODLevels.length; index++) {
  21763. if (this._LODLevels[index].mesh === mesh) {
  21764. this._LODLevels.splice(index, 1);
  21765. if (mesh) {
  21766. mesh._masterMesh = null;
  21767. }
  21768. }
  21769. }
  21770. this._sortLODLevels();
  21771. return this;
  21772. };
  21773. /**
  21774. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21775. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21776. */
  21777. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21778. if (!this._LODLevels || this._LODLevels.length === 0) {
  21779. return this;
  21780. }
  21781. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21782. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21783. if (this.onLODLevelSelection) {
  21784. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21785. }
  21786. return this;
  21787. }
  21788. for (var index = 0; index < this._LODLevels.length; index++) {
  21789. var level = this._LODLevels[index];
  21790. if (level.distance < distanceToCamera) {
  21791. if (level.mesh) {
  21792. level.mesh._preActivate();
  21793. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21794. }
  21795. if (this.onLODLevelSelection) {
  21796. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21797. }
  21798. return level.mesh;
  21799. }
  21800. }
  21801. if (this.onLODLevelSelection) {
  21802. this.onLODLevelSelection(distanceToCamera, this, this);
  21803. }
  21804. return this;
  21805. };
  21806. Object.defineProperty(Mesh.prototype, "geometry", {
  21807. /**
  21808. * Returns the mesh internal Geometry object.
  21809. */
  21810. get: function () {
  21811. return this._geometry;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. /**
  21817. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21818. */
  21819. Mesh.prototype.getTotalVertices = function () {
  21820. if (!this._geometry) {
  21821. return 0;
  21822. }
  21823. return this._geometry.getTotalVertices();
  21824. };
  21825. /**
  21826. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21827. * 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.
  21828. * You can force the copy with forceCopy === true
  21829. * Returns null if the mesh has no geometry or no vertex buffer.
  21830. * Possible `kind` values :
  21831. * - BABYLON.VertexBuffer.PositionKind
  21832. * - BABYLON.VertexBuffer.UVKind
  21833. * - BABYLON.VertexBuffer.UV2Kind
  21834. * - BABYLON.VertexBuffer.UV3Kind
  21835. * - BABYLON.VertexBuffer.UV4Kind
  21836. * - BABYLON.VertexBuffer.UV5Kind
  21837. * - BABYLON.VertexBuffer.UV6Kind
  21838. * - BABYLON.VertexBuffer.ColorKind
  21839. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21840. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21841. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21842. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21843. */
  21844. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21845. if (!this._geometry) {
  21846. return null;
  21847. }
  21848. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21849. };
  21850. /**
  21851. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21852. * Returns `undefined` if the mesh has no geometry.
  21853. * Possible `kind` values :
  21854. * - BABYLON.VertexBuffer.PositionKind
  21855. * - BABYLON.VertexBuffer.UVKind
  21856. * - BABYLON.VertexBuffer.UV2Kind
  21857. * - BABYLON.VertexBuffer.UV3Kind
  21858. * - BABYLON.VertexBuffer.UV4Kind
  21859. * - BABYLON.VertexBuffer.UV5Kind
  21860. * - BABYLON.VertexBuffer.UV6Kind
  21861. * - BABYLON.VertexBuffer.ColorKind
  21862. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21863. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21864. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21865. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21866. */
  21867. Mesh.prototype.getVertexBuffer = function (kind) {
  21868. if (!this._geometry) {
  21869. return undefined;
  21870. }
  21871. return this._geometry.getVertexBuffer(kind);
  21872. };
  21873. /**
  21874. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21875. * Possible `kind` values :
  21876. * - BABYLON.VertexBuffer.PositionKind
  21877. * - BABYLON.VertexBuffer.UVKind
  21878. * - BABYLON.VertexBuffer.UV2Kind
  21879. * - BABYLON.VertexBuffer.UV3Kind
  21880. * - BABYLON.VertexBuffer.UV4Kind
  21881. * - BABYLON.VertexBuffer.UV5Kind
  21882. * - BABYLON.VertexBuffer.UV6Kind
  21883. * - BABYLON.VertexBuffer.ColorKind
  21884. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21885. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21886. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21887. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21888. */
  21889. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21890. if (!this._geometry) {
  21891. if (this._delayInfo) {
  21892. return this._delayInfo.indexOf(kind) !== -1;
  21893. }
  21894. return false;
  21895. }
  21896. return this._geometry.isVerticesDataPresent(kind);
  21897. };
  21898. /**
  21899. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21900. * Possible `kind` values :
  21901. * - BABYLON.VertexBuffer.PositionKind
  21902. * - BABYLON.VertexBuffer.UVKind
  21903. * - BABYLON.VertexBuffer.UV2Kind
  21904. * - BABYLON.VertexBuffer.UV3Kind
  21905. * - BABYLON.VertexBuffer.UV4Kind
  21906. * - BABYLON.VertexBuffer.UV5Kind
  21907. * - BABYLON.VertexBuffer.UV6Kind
  21908. * - BABYLON.VertexBuffer.ColorKind
  21909. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21910. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21911. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21912. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21913. */
  21914. Mesh.prototype.getVerticesDataKinds = function () {
  21915. if (!this._geometry) {
  21916. var result = new Array();
  21917. if (this._delayInfo) {
  21918. this._delayInfo.forEach(function (kind, index, array) {
  21919. result.push(kind);
  21920. });
  21921. }
  21922. return result;
  21923. }
  21924. return this._geometry.getVerticesDataKinds();
  21925. };
  21926. /**
  21927. * Returns a positive integer : the total number of indices in this mesh geometry.
  21928. * Returns zero if the mesh has no geometry.
  21929. */
  21930. Mesh.prototype.getTotalIndices = function () {
  21931. if (!this._geometry) {
  21932. return 0;
  21933. }
  21934. return this._geometry.getTotalIndices();
  21935. };
  21936. /**
  21937. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21938. * 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.
  21939. * Returns an empty array if the mesh has no geometry.
  21940. */
  21941. Mesh.prototype.getIndices = function (copyWhenShared) {
  21942. if (!this._geometry) {
  21943. return [];
  21944. }
  21945. return this._geometry.getIndices(copyWhenShared);
  21946. };
  21947. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21948. get: function () {
  21949. return this._masterMesh !== null && this._masterMesh !== undefined;
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. /**
  21955. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21956. */
  21957. Mesh.prototype.isReady = function () {
  21958. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21959. return false;
  21960. }
  21961. return _super.prototype.isReady.call(this);
  21962. };
  21963. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21964. /**
  21965. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21966. * This property is pertinent only for updatable parametric shapes.
  21967. */
  21968. get: function () {
  21969. return this._areNormalsFrozen;
  21970. },
  21971. enumerable: true,
  21972. configurable: true
  21973. });
  21974. /**
  21975. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21976. * It has no effect at all on other shapes.
  21977. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21978. * Returns the Mesh.
  21979. */
  21980. Mesh.prototype.freezeNormals = function () {
  21981. this._areNormalsFrozen = true;
  21982. return this;
  21983. };
  21984. /**
  21985. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21986. * It has no effect at all on other shapes.
  21987. * It reactivates the mesh normals computation if it was previously frozen.
  21988. * Returns the Mesh.
  21989. */
  21990. Mesh.prototype.unfreezeNormals = function () {
  21991. this._areNormalsFrozen = false;
  21992. return this;
  21993. };
  21994. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21995. /**
  21996. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21997. */
  21998. set: function (count) {
  21999. this._overridenInstanceCount = count;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. // Methods
  22005. Mesh.prototype._preActivate = function () {
  22006. var sceneRenderId = this.getScene().getRenderId();
  22007. if (this._preActivateId === sceneRenderId) {
  22008. return this;
  22009. }
  22010. this._preActivateId = sceneRenderId;
  22011. this._visibleInstances = null;
  22012. return this;
  22013. };
  22014. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22015. if (this._visibleInstances) {
  22016. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22017. }
  22018. return this;
  22019. };
  22020. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22021. if (!this._visibleInstances) {
  22022. this._visibleInstances = {};
  22023. this._visibleInstances.defaultRenderId = renderId;
  22024. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22025. }
  22026. if (!this._visibleInstances[renderId]) {
  22027. this._visibleInstances[renderId] = new Array();
  22028. }
  22029. this._visibleInstances[renderId].push(instance);
  22030. return this;
  22031. };
  22032. /**
  22033. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22034. * This means the mesh underlying bounding box and sphere are recomputed.
  22035. * Returns the Mesh.
  22036. */
  22037. Mesh.prototype.refreshBoundingInfo = function () {
  22038. if (this._boundingInfo.isLocked) {
  22039. return;
  22040. }
  22041. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22042. if (data) {
  22043. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22044. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22045. }
  22046. if (this.subMeshes) {
  22047. for (var index = 0; index < this.subMeshes.length; index++) {
  22048. this.subMeshes[index].refreshBoundingInfo();
  22049. }
  22050. }
  22051. this._updateBoundingInfo();
  22052. return this;
  22053. };
  22054. Mesh.prototype._createGlobalSubMesh = function (force) {
  22055. var totalVertices = this.getTotalVertices();
  22056. if (!totalVertices || !this.getIndices()) {
  22057. return null;
  22058. }
  22059. // Check if we need to recreate the submeshes
  22060. if (this.subMeshes && this.subMeshes.length > 0) {
  22061. var totalIndices = this.getIndices().length;
  22062. var needToRecreate = false;
  22063. if (force) {
  22064. needToRecreate = true;
  22065. }
  22066. else {
  22067. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22068. var submesh = _a[_i];
  22069. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22070. needToRecreate = true;
  22071. break;
  22072. }
  22073. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22074. needToRecreate = true;
  22075. break;
  22076. }
  22077. }
  22078. }
  22079. if (!needToRecreate) {
  22080. return;
  22081. }
  22082. }
  22083. this.releaseSubMeshes();
  22084. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22085. };
  22086. Mesh.prototype.subdivide = function (count) {
  22087. if (count < 1) {
  22088. return;
  22089. }
  22090. var totalIndices = this.getTotalIndices();
  22091. var subdivisionSize = (totalIndices / count) | 0;
  22092. var offset = 0;
  22093. // Ensure that subdivisionSize is a multiple of 3
  22094. while (subdivisionSize % 3 !== 0) {
  22095. subdivisionSize++;
  22096. }
  22097. this.releaseSubMeshes();
  22098. for (var index = 0; index < count; index++) {
  22099. if (offset >= totalIndices) {
  22100. break;
  22101. }
  22102. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22103. offset += subdivisionSize;
  22104. }
  22105. this.synchronizeInstances();
  22106. };
  22107. /**
  22108. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22109. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22110. * The `data` are either a numeric array either a Float32Array.
  22111. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22112. * 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).
  22113. * Note that a new underlying VertexBuffer object is created each call.
  22114. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22115. *
  22116. * Possible `kind` values :
  22117. * - BABYLON.VertexBuffer.PositionKind
  22118. * - BABYLON.VertexBuffer.UVKind
  22119. * - BABYLON.VertexBuffer.UV2Kind
  22120. * - BABYLON.VertexBuffer.UV3Kind
  22121. * - BABYLON.VertexBuffer.UV4Kind
  22122. * - BABYLON.VertexBuffer.UV5Kind
  22123. * - BABYLON.VertexBuffer.UV6Kind
  22124. * - BABYLON.VertexBuffer.ColorKind
  22125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22129. *
  22130. * Returns the Mesh.
  22131. */
  22132. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22133. if (!this._geometry) {
  22134. var vertexData = new BABYLON.VertexData();
  22135. vertexData.set(data, kind);
  22136. var scene = this.getScene();
  22137. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22138. }
  22139. else {
  22140. this._geometry.setVerticesData(kind, data, updatable, stride);
  22141. }
  22142. return this;
  22143. };
  22144. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22145. if (updatable === void 0) { updatable = true; }
  22146. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22147. return;
  22148. }
  22149. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22150. };
  22151. /**
  22152. * Sets the mesh VertexBuffer.
  22153. * Returns the Mesh.
  22154. */
  22155. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22156. if (!this._geometry) {
  22157. var scene = this.getScene();
  22158. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22159. }
  22160. this._geometry.setVerticesBuffer(buffer);
  22161. return this;
  22162. };
  22163. /**
  22164. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22165. * If the mesh has no geometry, it is simply returned as it is.
  22166. * The `data` are either a numeric array either a Float32Array.
  22167. * No new underlying VertexBuffer object is created.
  22168. * 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.
  22169. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22170. *
  22171. * Possible `kind` values :
  22172. * - BABYLON.VertexBuffer.PositionKind
  22173. * - BABYLON.VertexBuffer.UVKind
  22174. * - BABYLON.VertexBuffer.UV2Kind
  22175. * - BABYLON.VertexBuffer.UV3Kind
  22176. * - BABYLON.VertexBuffer.UV4Kind
  22177. * - BABYLON.VertexBuffer.UV5Kind
  22178. * - BABYLON.VertexBuffer.UV6Kind
  22179. * - BABYLON.VertexBuffer.ColorKind
  22180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22184. *
  22185. * Returns the Mesh.
  22186. */
  22187. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22188. if (!this._geometry) {
  22189. return;
  22190. }
  22191. if (!makeItUnique) {
  22192. this._geometry.updateVerticesData(kind, data, updateExtends);
  22193. }
  22194. else {
  22195. this.makeGeometryUnique();
  22196. this.updateVerticesData(kind, data, updateExtends, false);
  22197. }
  22198. return this;
  22199. };
  22200. /**
  22201. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22202. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22203. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22204. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22205. * Returns the Mesh.
  22206. */
  22207. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22208. if (computeNormals === void 0) { computeNormals = true; }
  22209. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22210. positionFunction(positions);
  22211. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22212. if (computeNormals) {
  22213. var indices = this.getIndices();
  22214. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22215. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22216. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22217. }
  22218. return this;
  22219. };
  22220. /**
  22221. * Creates a un-shared specific occurence of the geometry for the mesh.
  22222. * Returns the Mesh.
  22223. */
  22224. Mesh.prototype.makeGeometryUnique = function () {
  22225. if (!this._geometry) {
  22226. return;
  22227. }
  22228. var oldGeometry = this._geometry;
  22229. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22230. oldGeometry.releaseForMesh(this, true);
  22231. geometry.applyToMesh(this);
  22232. return this;
  22233. };
  22234. /**
  22235. * Sets the mesh indices.
  22236. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22237. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22238. * This method creates a new index buffer each call.
  22239. * Returns the Mesh.
  22240. */
  22241. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  22242. if (!this._geometry) {
  22243. var vertexData = new BABYLON.VertexData();
  22244. vertexData.indices = indices;
  22245. var scene = this.getScene();
  22246. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22247. }
  22248. else {
  22249. this._geometry.setIndices(indices, totalVertices, updatable);
  22250. }
  22251. return this;
  22252. };
  22253. /**
  22254. * Update the current index buffer
  22255. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  22256. * Returns the Mesh.
  22257. */
  22258. Mesh.prototype.updateIndices = function (indices, offset) {
  22259. if (!this._geometry) {
  22260. return;
  22261. }
  22262. this._geometry.updateIndices(indices, offset);
  22263. return this;
  22264. };
  22265. /**
  22266. * Invert the geometry to move from a right handed system to a left handed one.
  22267. * Returns the Mesh.
  22268. */
  22269. Mesh.prototype.toLeftHanded = function () {
  22270. if (!this._geometry) {
  22271. return;
  22272. }
  22273. this._geometry.toLeftHanded();
  22274. return this;
  22275. };
  22276. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22277. var engine = this.getScene().getEngine();
  22278. // Wireframe
  22279. var indexToBind;
  22280. if (this._unIndexed) {
  22281. indexToBind = null;
  22282. }
  22283. else {
  22284. switch (fillMode) {
  22285. case BABYLON.Material.PointFillMode:
  22286. indexToBind = null;
  22287. break;
  22288. case BABYLON.Material.WireFrameFillMode:
  22289. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22290. break;
  22291. default:
  22292. case BABYLON.Material.TriangleFillMode:
  22293. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22294. break;
  22295. }
  22296. }
  22297. // VBOs
  22298. this._geometry._bind(effect, indexToBind);
  22299. return this;
  22300. };
  22301. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22302. if (alternate === void 0) { alternate = false; }
  22303. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22304. return this;
  22305. }
  22306. this.onBeforeDrawObservable.notifyObservers(this);
  22307. var scene = this.getScene();
  22308. var engine = scene.getEngine();
  22309. // Draw order
  22310. switch (fillMode) {
  22311. case BABYLON.Material.PointFillMode:
  22312. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22313. break;
  22314. case BABYLON.Material.WireFrameFillMode:
  22315. if (this._unIndexed) {
  22316. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22317. }
  22318. else {
  22319. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22320. }
  22321. break;
  22322. default:
  22323. if (this._unIndexed) {
  22324. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22325. }
  22326. else {
  22327. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22328. }
  22329. }
  22330. if (scene._isAlternateRenderingEnabled && !alternate) {
  22331. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22332. scene._switchToAlternateCameraConfiguration(true);
  22333. this._effectiveMaterial.bindView(effect);
  22334. this._effectiveMaterial.bindViewProjection(effect);
  22335. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22336. this._draw(subMesh, fillMode, instancesCount, true);
  22337. engine.setViewport(scene.activeCamera.viewport);
  22338. scene._switchToAlternateCameraConfiguration(false);
  22339. this._effectiveMaterial.bindView(effect);
  22340. this._effectiveMaterial.bindViewProjection(effect);
  22341. }
  22342. return this;
  22343. };
  22344. /**
  22345. * Registers for this mesh a javascript function called just before the rendering process.
  22346. * This function is passed the current mesh.
  22347. * Return the Mesh.
  22348. */
  22349. Mesh.prototype.registerBeforeRender = function (func) {
  22350. this.onBeforeRenderObservable.add(func);
  22351. return this;
  22352. };
  22353. /**
  22354. * Disposes a previously registered javascript function called before the rendering.
  22355. * This function is passed the current mesh.
  22356. * Returns the Mesh.
  22357. */
  22358. Mesh.prototype.unregisterBeforeRender = function (func) {
  22359. this.onBeforeRenderObservable.removeCallback(func);
  22360. return this;
  22361. };
  22362. /**
  22363. * Registers for this mesh a javascript function called just after the rendering is complete.
  22364. * This function is passed the current mesh.
  22365. * Returns the Mesh.
  22366. */
  22367. Mesh.prototype.registerAfterRender = function (func) {
  22368. this.onAfterRenderObservable.add(func);
  22369. return this;
  22370. };
  22371. /**
  22372. * Disposes a previously registered javascript function called after the rendering.
  22373. * This function is passed the current mesh.
  22374. * Return the Mesh.
  22375. */
  22376. Mesh.prototype.unregisterAfterRender = function (func) {
  22377. this.onAfterRenderObservable.removeCallback(func);
  22378. return this;
  22379. };
  22380. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22381. var scene = this.getScene();
  22382. this._batchCache.mustReturn = false;
  22383. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22384. this._batchCache.visibleInstances[subMeshId] = null;
  22385. if (this._visibleInstances) {
  22386. var currentRenderId = scene.getRenderId();
  22387. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22388. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22389. var selfRenderId = this._renderId;
  22390. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22391. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22392. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22393. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22394. }
  22395. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22396. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22397. this._batchCache.mustReturn = true;
  22398. return this._batchCache;
  22399. }
  22400. if (currentRenderId !== selfRenderId) {
  22401. this._batchCache.renderSelf[subMeshId] = false;
  22402. }
  22403. }
  22404. this._renderIdForInstances[subMeshId] = currentRenderId;
  22405. }
  22406. return this._batchCache;
  22407. };
  22408. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22409. var visibleInstances = batch.visibleInstances[subMesh._id];
  22410. var matricesCount = visibleInstances.length + 1;
  22411. var bufferSize = matricesCount * 16 * 4;
  22412. var currentInstancesBufferSize = this._instancesBufferSize;
  22413. var instancesBuffer = this._instancesBuffer;
  22414. while (this._instancesBufferSize < bufferSize) {
  22415. this._instancesBufferSize *= 2;
  22416. }
  22417. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22418. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22419. }
  22420. var offset = 0;
  22421. var instancesCount = 0;
  22422. var world = this.getWorldMatrix();
  22423. if (batch.renderSelf[subMesh._id]) {
  22424. world.copyToArray(this._instancesData, offset);
  22425. offset += 16;
  22426. instancesCount++;
  22427. }
  22428. if (visibleInstances) {
  22429. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22430. var instance = visibleInstances[instanceIndex];
  22431. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22432. offset += 16;
  22433. instancesCount++;
  22434. }
  22435. }
  22436. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22437. if (instancesBuffer) {
  22438. instancesBuffer.dispose();
  22439. }
  22440. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22441. this._instancesBuffer = instancesBuffer;
  22442. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22443. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22444. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22445. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22446. }
  22447. else {
  22448. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22449. }
  22450. this._bind(subMesh, effect, fillMode);
  22451. this._draw(subMesh, fillMode, instancesCount);
  22452. engine.unbindInstanceAttributes();
  22453. return this;
  22454. };
  22455. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22456. var scene = this.getScene();
  22457. var engine = scene.getEngine();
  22458. if (hardwareInstancedRendering) {
  22459. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22460. }
  22461. else {
  22462. if (batch.renderSelf[subMesh._id]) {
  22463. // Draw
  22464. if (onBeforeDraw) {
  22465. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22466. }
  22467. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22468. }
  22469. if (batch.visibleInstances[subMesh._id]) {
  22470. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22471. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22472. // World
  22473. var world = instance.getWorldMatrix();
  22474. if (onBeforeDraw) {
  22475. onBeforeDraw(true, world, effectiveMaterial);
  22476. }
  22477. // Draw
  22478. this._draw(subMesh, fillMode);
  22479. }
  22480. }
  22481. }
  22482. return this;
  22483. };
  22484. /**
  22485. * Triggers the draw call for the mesh.
  22486. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22487. * Returns the Mesh.
  22488. */
  22489. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22490. this.checkOcclusionQuery();
  22491. if (this._isOccluded) {
  22492. return;
  22493. }
  22494. var scene = this.getScene();
  22495. // Managing instances
  22496. var batch = this._getInstancesRenderList(subMesh._id);
  22497. if (batch.mustReturn) {
  22498. return this;
  22499. }
  22500. // Checking geometry state
  22501. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22502. return this;
  22503. }
  22504. var callbackIndex;
  22505. this.onBeforeRenderObservable.notifyObservers(this);
  22506. var engine = scene.getEngine();
  22507. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22508. // Material
  22509. this._effectiveMaterial = subMesh.getMaterial();
  22510. if (!this._effectiveMaterial) {
  22511. return this;
  22512. }
  22513. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22514. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22515. return this;
  22516. }
  22517. }
  22518. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22519. return this;
  22520. }
  22521. // Alpha mode
  22522. if (enableAlphaMode) {
  22523. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22524. }
  22525. // Outline - step 1
  22526. var savedDepthWrite = engine.getDepthWrite();
  22527. if (this.renderOutline) {
  22528. engine.setDepthWrite(false);
  22529. scene.getOutlineRenderer().render(subMesh, batch);
  22530. engine.setDepthWrite(savedDepthWrite);
  22531. }
  22532. var effect;
  22533. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22534. effect = subMesh.effect;
  22535. }
  22536. else {
  22537. effect = this._effectiveMaterial.getEffect();
  22538. }
  22539. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22540. if (this._effectiveMaterial.forceDepthWrite) {
  22541. engine.setDepthWrite(true);
  22542. }
  22543. // Bind
  22544. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22545. if (!hardwareInstancedRendering) {
  22546. this._bind(subMesh, effect, fillMode);
  22547. }
  22548. var world = this.getWorldMatrix();
  22549. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22550. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22551. }
  22552. else {
  22553. this._effectiveMaterial.bind(world, this);
  22554. }
  22555. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22556. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22557. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22558. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22559. }
  22560. // Draw
  22561. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22562. // Unbind
  22563. this._effectiveMaterial.unbind();
  22564. // Outline - step 2
  22565. if (this.renderOutline && savedDepthWrite) {
  22566. engine.setDepthWrite(true);
  22567. engine.setColorWrite(false);
  22568. scene.getOutlineRenderer().render(subMesh, batch);
  22569. engine.setColorWrite(true);
  22570. }
  22571. // Overlay
  22572. if (this.renderOverlay) {
  22573. var currentMode = engine.getAlphaMode();
  22574. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22575. scene.getOutlineRenderer().render(subMesh, batch, true);
  22576. engine.setAlphaMode(currentMode);
  22577. }
  22578. this.onAfterRenderObservable.notifyObservers(this);
  22579. return this;
  22580. };
  22581. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22582. if (isInstance) {
  22583. effectiveMaterial.bindOnlyWorldMatrix(world);
  22584. }
  22585. return this;
  22586. };
  22587. /**
  22588. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22589. */
  22590. Mesh.prototype.getEmittedParticleSystems = function () {
  22591. var results = new Array();
  22592. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22593. var particleSystem = this.getScene().particleSystems[index];
  22594. if (particleSystem.emitter === this) {
  22595. results.push(particleSystem);
  22596. }
  22597. }
  22598. return results;
  22599. };
  22600. /**
  22601. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22602. */
  22603. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22604. var results = new Array();
  22605. var descendants = this.getDescendants();
  22606. descendants.push(this);
  22607. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22608. var particleSystem = this.getScene().particleSystems[index];
  22609. var emitter = particleSystem.emitter;
  22610. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22611. results.push(particleSystem);
  22612. }
  22613. }
  22614. return results;
  22615. };
  22616. Mesh.prototype._checkDelayState = function () {
  22617. var scene = this.getScene();
  22618. if (this._geometry) {
  22619. this._geometry.load(scene);
  22620. }
  22621. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22622. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22623. this._queueLoad(this, scene);
  22624. }
  22625. return this;
  22626. };
  22627. Mesh.prototype._queueLoad = function (mesh, scene) {
  22628. var _this = this;
  22629. scene._addPendingData(mesh);
  22630. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22631. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22632. if (data instanceof ArrayBuffer) {
  22633. _this._delayLoadingFunction(data, _this);
  22634. }
  22635. else {
  22636. _this._delayLoadingFunction(JSON.parse(data), _this);
  22637. }
  22638. _this.instances.forEach(function (instance) {
  22639. instance._syncSubMeshes();
  22640. });
  22641. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22642. scene._removePendingData(_this);
  22643. }, function () { }, scene.database, getBinaryData);
  22644. return this;
  22645. };
  22646. /**
  22647. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22648. */
  22649. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22650. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22651. return false;
  22652. }
  22653. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22654. return false;
  22655. }
  22656. this._checkDelayState();
  22657. return true;
  22658. };
  22659. /**
  22660. * Sets the mesh material by the material or multiMaterial `id` property.
  22661. * The material `id` is a string identifying the material or the multiMaterial.
  22662. * This method returns the Mesh.
  22663. */
  22664. Mesh.prototype.setMaterialByID = function (id) {
  22665. var materials = this.getScene().materials;
  22666. var index;
  22667. for (index = materials.length - 1; index > -1; index--) {
  22668. if (materials[index].id === id) {
  22669. this.material = materials[index];
  22670. return this;
  22671. }
  22672. }
  22673. // Multi
  22674. var multiMaterials = this.getScene().multiMaterials;
  22675. for (index = multiMaterials.length - 1; index > -1; index--) {
  22676. if (multiMaterials[index].id === id) {
  22677. this.material = multiMaterials[index];
  22678. return this;
  22679. }
  22680. }
  22681. return this;
  22682. };
  22683. /**
  22684. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22685. */
  22686. Mesh.prototype.getAnimatables = function () {
  22687. var results = new Array();
  22688. if (this.material) {
  22689. results.push(this.material);
  22690. }
  22691. if (this.skeleton) {
  22692. results.push(this.skeleton);
  22693. }
  22694. return results;
  22695. };
  22696. /**
  22697. * Modifies the mesh geometry according to the passed transformation matrix.
  22698. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22699. * The mesh normals are modified accordingly the same transformation.
  22700. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22701. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22702. * Returns the Mesh.
  22703. */
  22704. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22705. // Position
  22706. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22707. return this;
  22708. }
  22709. var submeshes = this.subMeshes.splice(0);
  22710. this._resetPointsArrayCache();
  22711. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22712. var temp = new Array();
  22713. var index;
  22714. for (index = 0; index < data.length; index += 3) {
  22715. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22716. }
  22717. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22718. // Normals
  22719. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22720. return this;
  22721. }
  22722. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22723. temp = [];
  22724. for (index = 0; index < data.length; index += 3) {
  22725. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22726. }
  22727. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22728. // flip faces?
  22729. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22730. this.flipFaces();
  22731. }
  22732. // Restore submeshes
  22733. this.releaseSubMeshes();
  22734. this.subMeshes = submeshes;
  22735. return this;
  22736. };
  22737. /**
  22738. * Modifies the mesh geometry according to its own current World Matrix.
  22739. * The mesh World Matrix is then reset.
  22740. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22741. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22742. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22743. * Returns the Mesh.
  22744. */
  22745. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22746. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22747. this.scaling.copyFromFloats(1, 1, 1);
  22748. this.position.copyFromFloats(0, 0, 0);
  22749. this.rotation.copyFromFloats(0, 0, 0);
  22750. //only if quaternion is already set
  22751. if (this.rotationQuaternion) {
  22752. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22753. }
  22754. this._worldMatrix = BABYLON.Matrix.Identity();
  22755. return this;
  22756. };
  22757. Object.defineProperty(Mesh.prototype, "_positions", {
  22758. // Cache
  22759. get: function () {
  22760. if (this._geometry) {
  22761. return this._geometry._positions;
  22762. }
  22763. return null;
  22764. },
  22765. enumerable: true,
  22766. configurable: true
  22767. });
  22768. Mesh.prototype._resetPointsArrayCache = function () {
  22769. if (this._geometry) {
  22770. this._geometry._resetPointsArrayCache();
  22771. }
  22772. return this;
  22773. };
  22774. Mesh.prototype._generatePointsArray = function () {
  22775. if (this._geometry) {
  22776. return this._geometry._generatePointsArray();
  22777. }
  22778. return false;
  22779. };
  22780. /**
  22781. * Returns a new Mesh object generated from the current mesh properties.
  22782. * This method must not get confused with createInstance().
  22783. * The parameter `name` is a string, the name given to the new mesh.
  22784. * The optional parameter `newParent` can be any Node object (default `null`).
  22785. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22786. * 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.
  22787. */
  22788. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22789. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22790. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22791. };
  22792. /**
  22793. * Disposes the mesh.
  22794. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22795. */
  22796. Mesh.prototype.dispose = function (doNotRecurse) {
  22797. var _this = this;
  22798. this.morphTargetManager = undefined;
  22799. if (this._geometry) {
  22800. this._geometry.releaseForMesh(this, true);
  22801. }
  22802. // Sources
  22803. var meshes = this.getScene().meshes;
  22804. meshes.forEach(function (mesh) {
  22805. if (mesh._source && mesh._source === _this) {
  22806. mesh._source = null;
  22807. }
  22808. });
  22809. this._source = null;
  22810. // Instances
  22811. if (this._instancesBuffer) {
  22812. this._instancesBuffer.dispose();
  22813. this._instancesBuffer = null;
  22814. }
  22815. while (this.instances.length) {
  22816. this.instances[0].dispose();
  22817. }
  22818. // Highlight layers.
  22819. var highlightLayers = this.getScene().highlightLayers;
  22820. for (var i = 0; i < highlightLayers.length; i++) {
  22821. var highlightLayer = highlightLayers[i];
  22822. if (highlightLayer) {
  22823. highlightLayer.removeMesh(this);
  22824. highlightLayer.removeExcludedMesh(this);
  22825. }
  22826. }
  22827. _super.prototype.dispose.call(this, doNotRecurse);
  22828. };
  22829. /**
  22830. * Modifies the mesh geometry according to a displacement map.
  22831. * 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.
  22832. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22833. * This method returns nothing.
  22834. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22835. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22836. * 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.
  22837. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22838. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22839. *
  22840. * Returns the Mesh.
  22841. */
  22842. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22843. var _this = this;
  22844. var scene = this.getScene();
  22845. var onload = function (img) {
  22846. // Getting height map data
  22847. var canvas = document.createElement("canvas");
  22848. var context = canvas.getContext("2d");
  22849. var heightMapWidth = img.width;
  22850. var heightMapHeight = img.height;
  22851. canvas.width = heightMapWidth;
  22852. canvas.height = heightMapHeight;
  22853. context.drawImage(img, 0, 0);
  22854. // Create VertexData from map data
  22855. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22856. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22857. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22858. //execute success callback, if set
  22859. if (onSuccess) {
  22860. onSuccess(_this);
  22861. }
  22862. };
  22863. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22864. return this;
  22865. };
  22866. /**
  22867. * Modifies the mesh geometry according to a displacementMap buffer.
  22868. * 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.
  22869. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22870. * This method returns nothing.
  22871. * 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.
  22872. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22873. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22874. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22875. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22876. *
  22877. * Returns the Mesh.
  22878. */
  22879. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22880. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22881. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22882. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22883. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22884. return this;
  22885. }
  22886. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22887. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22888. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22889. var position = BABYLON.Vector3.Zero();
  22890. var normal = BABYLON.Vector3.Zero();
  22891. var uv = BABYLON.Vector2.Zero();
  22892. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22893. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22894. for (var index = 0; index < positions.length; index += 3) {
  22895. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22896. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22897. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22898. // Compute height
  22899. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22900. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22901. var pos = (u + v * heightMapWidth) * 4;
  22902. var r = buffer[pos] / 255.0;
  22903. var g = buffer[pos + 1] / 255.0;
  22904. var b = buffer[pos + 2] / 255.0;
  22905. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22906. normal.normalize();
  22907. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22908. position = position.add(normal);
  22909. position.toArray(positions, index);
  22910. }
  22911. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22912. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22913. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22914. return this;
  22915. };
  22916. /**
  22917. * Modify the mesh to get a flat shading rendering.
  22918. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22919. * This method returns the Mesh.
  22920. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22921. */
  22922. Mesh.prototype.convertToFlatShadedMesh = function () {
  22923. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22924. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22925. var kinds = this.getVerticesDataKinds();
  22926. var vbs = {};
  22927. var data = {};
  22928. var newdata = {};
  22929. var updatableNormals = false;
  22930. var kindIndex;
  22931. var kind;
  22932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22933. kind = kinds[kindIndex];
  22934. var vertexBuffer = this.getVertexBuffer(kind);
  22935. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22936. updatableNormals = vertexBuffer.isUpdatable();
  22937. kinds.splice(kindIndex, 1);
  22938. kindIndex--;
  22939. continue;
  22940. }
  22941. vbs[kind] = vertexBuffer;
  22942. data[kind] = vbs[kind].getData();
  22943. newdata[kind] = [];
  22944. }
  22945. // Save previous submeshes
  22946. var previousSubmeshes = this.subMeshes.slice(0);
  22947. var indices = this.getIndices();
  22948. var totalIndices = this.getTotalIndices();
  22949. // Generating unique vertices per face
  22950. var index;
  22951. for (index = 0; index < totalIndices; index++) {
  22952. var vertexIndex = indices[index];
  22953. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22954. kind = kinds[kindIndex];
  22955. var stride = vbs[kind].getStrideSize();
  22956. for (var offset = 0; offset < stride; offset++) {
  22957. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22958. }
  22959. }
  22960. }
  22961. // Updating faces & normal
  22962. var normals = [];
  22963. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22964. for (index = 0; index < totalIndices; index += 3) {
  22965. indices[index] = index;
  22966. indices[index + 1] = index + 1;
  22967. indices[index + 2] = index + 2;
  22968. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22969. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22970. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22971. var p1p2 = p1.subtract(p2);
  22972. var p3p2 = p3.subtract(p2);
  22973. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22974. // Store same normals for every vertex
  22975. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22976. normals.push(normal.x);
  22977. normals.push(normal.y);
  22978. normals.push(normal.z);
  22979. }
  22980. }
  22981. this.setIndices(indices);
  22982. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22983. // Updating vertex buffers
  22984. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22985. kind = kinds[kindIndex];
  22986. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22987. }
  22988. // Updating submeshes
  22989. this.releaseSubMeshes();
  22990. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22991. var previousOne = previousSubmeshes[submeshIndex];
  22992. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22993. }
  22994. this.synchronizeInstances();
  22995. return this;
  22996. };
  22997. /**
  22998. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22999. * In other words, more vertices, no more indices and a single bigger VBO.
  23000. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23001. * Returns the Mesh.
  23002. */
  23003. Mesh.prototype.convertToUnIndexedMesh = function () {
  23004. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23005. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23006. var kinds = this.getVerticesDataKinds();
  23007. var vbs = {};
  23008. var data = {};
  23009. var newdata = {};
  23010. var updatableNormals = false;
  23011. var kindIndex;
  23012. var kind;
  23013. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23014. kind = kinds[kindIndex];
  23015. var vertexBuffer = this.getVertexBuffer(kind);
  23016. vbs[kind] = vertexBuffer;
  23017. data[kind] = vbs[kind].getData();
  23018. newdata[kind] = [];
  23019. }
  23020. // Save previous submeshes
  23021. var previousSubmeshes = this.subMeshes.slice(0);
  23022. var indices = this.getIndices();
  23023. var totalIndices = this.getTotalIndices();
  23024. // Generating unique vertices per face
  23025. var index;
  23026. for (index = 0; index < totalIndices; index++) {
  23027. var vertexIndex = indices[index];
  23028. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23029. kind = kinds[kindIndex];
  23030. var stride = vbs[kind].getStrideSize();
  23031. for (var offset = 0; offset < stride; offset++) {
  23032. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23033. }
  23034. }
  23035. }
  23036. // Updating indices
  23037. for (index = 0; index < totalIndices; index += 3) {
  23038. indices[index] = index;
  23039. indices[index + 1] = index + 1;
  23040. indices[index + 2] = index + 2;
  23041. }
  23042. this.setIndices(indices);
  23043. // Updating vertex buffers
  23044. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23045. kind = kinds[kindIndex];
  23046. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23047. }
  23048. // Updating submeshes
  23049. this.releaseSubMeshes();
  23050. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23051. var previousOne = previousSubmeshes[submeshIndex];
  23052. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23053. }
  23054. this._unIndexed = true;
  23055. this.synchronizeInstances();
  23056. return this;
  23057. };
  23058. /**
  23059. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23060. * This method returns the Mesh.
  23061. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23062. */
  23063. Mesh.prototype.flipFaces = function (flipNormals) {
  23064. if (flipNormals === void 0) { flipNormals = false; }
  23065. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23066. var i;
  23067. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23068. for (i = 0; i < vertex_data.normals.length; i++) {
  23069. vertex_data.normals[i] *= -1;
  23070. }
  23071. }
  23072. var temp;
  23073. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23074. // reassign indices
  23075. temp = vertex_data.indices[i + 1];
  23076. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23077. vertex_data.indices[i + 2] = temp;
  23078. }
  23079. vertex_data.applyToMesh(this);
  23080. return this;
  23081. };
  23082. // Instances
  23083. /**
  23084. * Creates a new InstancedMesh object from the mesh model.
  23085. * An instance shares the same properties and the same material than its model.
  23086. * Only these properties of each instance can then be set individually :
  23087. * - position
  23088. * - rotation
  23089. * - rotationQuaternion
  23090. * - setPivotMatrix
  23091. * - scaling
  23092. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23093. * Warning : this method is not supported for Line mesh and LineSystem
  23094. */
  23095. Mesh.prototype.createInstance = function (name) {
  23096. return new BABYLON.InstancedMesh(name, this);
  23097. };
  23098. /**
  23099. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23100. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23101. * This method returns the Mesh.
  23102. */
  23103. Mesh.prototype.synchronizeInstances = function () {
  23104. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23105. var instance = this.instances[instanceIndex];
  23106. instance._syncSubMeshes();
  23107. }
  23108. return this;
  23109. };
  23110. /**
  23111. * Simplify the mesh according to the given array of settings.
  23112. * Function will return immediately and will simplify async. It returns the Mesh.
  23113. * @param settings a collection of simplification settings.
  23114. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23115. * @param type the type of simplification to run.
  23116. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23117. */
  23118. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23119. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23120. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23121. this.getScene().simplificationQueue.addTask({
  23122. settings: settings,
  23123. parallelProcessing: parallelProcessing,
  23124. mesh: this,
  23125. simplificationType: simplificationType,
  23126. successCallback: successCallback
  23127. });
  23128. return this;
  23129. };
  23130. /**
  23131. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23132. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23133. * This should be used together with the simplification to avoid disappearing triangles.
  23134. * Returns the Mesh.
  23135. * @param successCallback an optional success callback to be called after the optimization finished.
  23136. */
  23137. Mesh.prototype.optimizeIndices = function (successCallback) {
  23138. var _this = this;
  23139. var indices = this.getIndices();
  23140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23141. var vectorPositions = new Array();
  23142. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23143. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23144. }
  23145. var dupes = new Array();
  23146. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23147. var realPos = vectorPositions.length - 1 - iteration;
  23148. var testedPosition = vectorPositions[realPos];
  23149. for (var j = 0; j < realPos; ++j) {
  23150. var againstPosition = vectorPositions[j];
  23151. if (testedPosition.equals(againstPosition)) {
  23152. dupes[realPos] = j;
  23153. break;
  23154. }
  23155. }
  23156. }, function () {
  23157. for (var i = 0; i < indices.length; ++i) {
  23158. indices[i] = dupes[indices[i]] || indices[i];
  23159. }
  23160. //indices are now reordered
  23161. var originalSubMeshes = _this.subMeshes.slice(0);
  23162. _this.setIndices(indices);
  23163. _this.subMeshes = originalSubMeshes;
  23164. if (successCallback) {
  23165. successCallback(_this);
  23166. }
  23167. });
  23168. return this;
  23169. };
  23170. Mesh.prototype.serialize = function (serializationObject) {
  23171. serializationObject.name = this.name;
  23172. serializationObject.id = this.id;
  23173. serializationObject.type = this.getClassName();
  23174. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23175. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23176. }
  23177. serializationObject.position = this.position.asArray();
  23178. if (this.rotationQuaternion) {
  23179. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23180. }
  23181. else if (this.rotation) {
  23182. serializationObject.rotation = this.rotation.asArray();
  23183. }
  23184. serializationObject.scaling = this.scaling.asArray();
  23185. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23186. serializationObject.isEnabled = this.isEnabled();
  23187. serializationObject.isVisible = this.isVisible;
  23188. serializationObject.infiniteDistance = this.infiniteDistance;
  23189. serializationObject.pickable = this.isPickable;
  23190. serializationObject.receiveShadows = this.receiveShadows;
  23191. serializationObject.billboardMode = this.billboardMode;
  23192. serializationObject.visibility = this.visibility;
  23193. serializationObject.checkCollisions = this.checkCollisions;
  23194. serializationObject.isBlocker = this.isBlocker;
  23195. // Parent
  23196. if (this.parent) {
  23197. serializationObject.parentId = this.parent.id;
  23198. }
  23199. // Geometry
  23200. var geometry = this._geometry;
  23201. if (geometry) {
  23202. var geometryId = geometry.id;
  23203. serializationObject.geometryId = geometryId;
  23204. // SubMeshes
  23205. serializationObject.subMeshes = [];
  23206. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23207. var subMesh = this.subMeshes[subIndex];
  23208. serializationObject.subMeshes.push({
  23209. materialIndex: subMesh.materialIndex,
  23210. verticesStart: subMesh.verticesStart,
  23211. verticesCount: subMesh.verticesCount,
  23212. indexStart: subMesh.indexStart,
  23213. indexCount: subMesh.indexCount
  23214. });
  23215. }
  23216. }
  23217. // Material
  23218. if (this.material) {
  23219. serializationObject.materialId = this.material.id;
  23220. }
  23221. else {
  23222. this.material = null;
  23223. }
  23224. // Morph targets
  23225. if (this.morphTargetManager) {
  23226. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23227. }
  23228. // Skeleton
  23229. if (this.skeleton) {
  23230. serializationObject.skeletonId = this.skeleton.id;
  23231. }
  23232. // Physics
  23233. //TODO implement correct serialization for physics impostors.
  23234. if (this.getPhysicsImpostor()) {
  23235. var impostor = this.getPhysicsImpostor();
  23236. serializationObject.physicsMass = impostor.getParam("mass");
  23237. serializationObject.physicsFriction = impostor.getParam("friction");
  23238. serializationObject.physicsRestitution = impostor.getParam("mass");
  23239. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23240. }
  23241. // Metadata
  23242. if (this.metadata) {
  23243. serializationObject.metadata = this.metadata;
  23244. }
  23245. // Instances
  23246. serializationObject.instances = [];
  23247. for (var index = 0; index < this.instances.length; index++) {
  23248. var instance = this.instances[index];
  23249. var serializationInstance = {
  23250. name: instance.name,
  23251. position: instance.position.asArray(),
  23252. scaling: instance.scaling.asArray()
  23253. };
  23254. if (instance.rotationQuaternion) {
  23255. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23256. }
  23257. else if (instance.rotation) {
  23258. serializationInstance.rotation = instance.rotation.asArray();
  23259. }
  23260. serializationObject.instances.push(serializationInstance);
  23261. // Animations
  23262. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23263. serializationInstance.ranges = instance.serializeAnimationRanges();
  23264. }
  23265. //
  23266. // Animations
  23267. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23268. serializationObject.ranges = this.serializeAnimationRanges();
  23269. // Layer mask
  23270. serializationObject.layerMask = this.layerMask;
  23271. // Alpha
  23272. serializationObject.alphaIndex = this.alphaIndex;
  23273. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23274. // Overlay
  23275. serializationObject.overlayAlpha = this.overlayAlpha;
  23276. serializationObject.overlayColor = this.overlayColor.asArray();
  23277. serializationObject.renderOverlay = this.renderOverlay;
  23278. // Fog
  23279. serializationObject.applyFog = this.applyFog;
  23280. // Action Manager
  23281. if (this.actionManager) {
  23282. serializationObject.actions = this.actionManager.serialize(this.name);
  23283. }
  23284. };
  23285. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23286. if (!this.geometry) {
  23287. return;
  23288. }
  23289. this._markSubMeshesAsAttributesDirty();
  23290. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23291. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23292. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23293. this.morphTargetManager = undefined;
  23294. return;
  23295. }
  23296. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23297. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23298. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23299. if (morphTarget.hasNormals) {
  23300. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23301. }
  23302. if (morphTarget.hasTangents) {
  23303. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23304. }
  23305. }
  23306. }
  23307. else {
  23308. var index = 0;
  23309. // Positions
  23310. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23311. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23312. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23313. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23314. }
  23315. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23316. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23317. }
  23318. index++;
  23319. }
  23320. }
  23321. };
  23322. // Statics
  23323. /**
  23324. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23325. * The parameter `parsedMesh` is the mesh to be copied.
  23326. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23327. */
  23328. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23329. var mesh;
  23330. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23331. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23332. }
  23333. else {
  23334. mesh = new Mesh(parsedMesh.name, scene);
  23335. }
  23336. mesh.id = parsedMesh.id;
  23337. if (BABYLON.Tags) {
  23338. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23339. }
  23340. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23341. if (parsedMesh.metadata !== undefined) {
  23342. mesh.metadata = parsedMesh.metadata;
  23343. }
  23344. if (parsedMesh.rotationQuaternion) {
  23345. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23346. }
  23347. else if (parsedMesh.rotation) {
  23348. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23349. }
  23350. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23351. if (parsedMesh.localMatrix) {
  23352. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23353. }
  23354. else if (parsedMesh.pivotMatrix) {
  23355. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23356. }
  23357. mesh.setEnabled(parsedMesh.isEnabled);
  23358. mesh.isVisible = parsedMesh.isVisible;
  23359. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23360. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23361. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23362. if (parsedMesh.applyFog !== undefined) {
  23363. mesh.applyFog = parsedMesh.applyFog;
  23364. }
  23365. if (parsedMesh.pickable !== undefined) {
  23366. mesh.isPickable = parsedMesh.pickable;
  23367. }
  23368. if (parsedMesh.alphaIndex !== undefined) {
  23369. mesh.alphaIndex = parsedMesh.alphaIndex;
  23370. }
  23371. mesh.receiveShadows = parsedMesh.receiveShadows;
  23372. mesh.billboardMode = parsedMesh.billboardMode;
  23373. if (parsedMesh.visibility !== undefined) {
  23374. mesh.visibility = parsedMesh.visibility;
  23375. }
  23376. mesh.checkCollisions = parsedMesh.checkCollisions;
  23377. if (parsedMesh.isBlocker !== undefined) {
  23378. mesh.isBlocker = parsedMesh.isBlocker;
  23379. }
  23380. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23381. // freezeWorldMatrix
  23382. if (parsedMesh.freezeWorldMatrix) {
  23383. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23384. }
  23385. // Parent
  23386. if (parsedMesh.parentId) {
  23387. mesh._waitingParentId = parsedMesh.parentId;
  23388. }
  23389. // Actions
  23390. if (parsedMesh.actions !== undefined) {
  23391. mesh._waitingActions = parsedMesh.actions;
  23392. }
  23393. // Overlay
  23394. if (parsedMesh.overlayAlpha !== undefined) {
  23395. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23396. }
  23397. if (parsedMesh.overlayColor !== undefined) {
  23398. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23399. }
  23400. if (parsedMesh.renderOverlay !== undefined) {
  23401. mesh.renderOverlay = parsedMesh.renderOverlay;
  23402. }
  23403. // Geometry
  23404. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23405. if (parsedMesh.delayLoadingFile) {
  23406. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23407. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23408. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23409. if (parsedMesh._binaryInfo) {
  23410. mesh._binaryInfo = parsedMesh._binaryInfo;
  23411. }
  23412. mesh._delayInfo = [];
  23413. if (parsedMesh.hasUVs) {
  23414. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23415. }
  23416. if (parsedMesh.hasUVs2) {
  23417. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23418. }
  23419. if (parsedMesh.hasUVs3) {
  23420. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23421. }
  23422. if (parsedMesh.hasUVs4) {
  23423. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23424. }
  23425. if (parsedMesh.hasUVs5) {
  23426. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23427. }
  23428. if (parsedMesh.hasUVs6) {
  23429. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23430. }
  23431. if (parsedMesh.hasColors) {
  23432. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23433. }
  23434. if (parsedMesh.hasMatricesIndices) {
  23435. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23436. }
  23437. if (parsedMesh.hasMatricesWeights) {
  23438. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23439. }
  23440. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23441. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23442. mesh._checkDelayState();
  23443. }
  23444. }
  23445. else {
  23446. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23447. }
  23448. // Material
  23449. if (parsedMesh.materialId) {
  23450. mesh.setMaterialByID(parsedMesh.materialId);
  23451. }
  23452. else {
  23453. mesh.material = null;
  23454. }
  23455. // Morph targets
  23456. if (parsedMesh.morphTargetManagerId > -1) {
  23457. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23458. }
  23459. // Skeleton
  23460. if (parsedMesh.skeletonId > -1) {
  23461. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23462. if (parsedMesh.numBoneInfluencers) {
  23463. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23464. }
  23465. }
  23466. // Animations
  23467. if (parsedMesh.animations) {
  23468. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23469. var parsedAnimation = parsedMesh.animations[animationIndex];
  23470. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23471. }
  23472. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23473. }
  23474. if (parsedMesh.autoAnimate) {
  23475. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23476. }
  23477. // Layer Mask
  23478. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23479. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23480. }
  23481. else {
  23482. mesh.layerMask = 0x0FFFFFFF;
  23483. }
  23484. // Physics
  23485. if (parsedMesh.physicsImpostor) {
  23486. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23487. mass: parsedMesh.physicsMass,
  23488. friction: parsedMesh.physicsFriction,
  23489. restitution: parsedMesh.physicsRestitution
  23490. }, scene);
  23491. }
  23492. // Instances
  23493. if (parsedMesh.instances) {
  23494. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23495. var parsedInstance = parsedMesh.instances[index];
  23496. var instance = mesh.createInstance(parsedInstance.name);
  23497. if (BABYLON.Tags) {
  23498. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23499. }
  23500. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23501. if (parsedInstance.parentId) {
  23502. instance._waitingParentId = parsedInstance.parentId;
  23503. }
  23504. if (parsedInstance.rotationQuaternion) {
  23505. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23506. }
  23507. else if (parsedInstance.rotation) {
  23508. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23509. }
  23510. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23511. instance.checkCollisions = mesh.checkCollisions;
  23512. if (parsedMesh.animations) {
  23513. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23514. parsedAnimation = parsedMesh.animations[animationIndex];
  23515. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23516. }
  23517. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23518. }
  23519. }
  23520. }
  23521. return mesh;
  23522. };
  23523. /**
  23524. * Creates a ribbon mesh.
  23525. * Please consider using the same method from the MeshBuilder class instead.
  23526. * 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.
  23527. *
  23528. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23529. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23530. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23531. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23532. * 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.
  23533. * 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.
  23534. * 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
  23535. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23536. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23538. */
  23539. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23540. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23541. pathArray: pathArray,
  23542. closeArray: closeArray,
  23543. closePath: closePath,
  23544. offset: offset,
  23545. updatable: updatable,
  23546. sideOrientation: sideOrientation,
  23547. instance: instance
  23548. }, scene);
  23549. };
  23550. /**
  23551. * Creates a plane polygonal mesh. By default, this is a disc.
  23552. * Please consider using the same method from the MeshBuilder class instead.
  23553. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23554. * 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.
  23555. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23558. */
  23559. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23560. var options = {
  23561. radius: radius,
  23562. tessellation: tessellation,
  23563. sideOrientation: sideOrientation,
  23564. updatable: updatable
  23565. };
  23566. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23567. };
  23568. /**
  23569. * Creates a box mesh.
  23570. * Please consider using the same method from the MeshBuilder class instead.
  23571. * The parameter `size` sets the size (float) of each box side (default 1).
  23572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23575. */
  23576. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23577. var options = {
  23578. size: size,
  23579. sideOrientation: sideOrientation,
  23580. updatable: updatable
  23581. };
  23582. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23583. };
  23584. /**
  23585. * Creates a sphere mesh.
  23586. * Please consider using the same method from the MeshBuilder class instead.
  23587. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23588. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23592. */
  23593. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23594. var options = {
  23595. segments: segments,
  23596. diameterX: diameter,
  23597. diameterY: diameter,
  23598. diameterZ: diameter,
  23599. sideOrientation: sideOrientation,
  23600. updatable: updatable
  23601. };
  23602. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23603. };
  23604. /**
  23605. * Creates a cylinder or a cone mesh.
  23606. * Please consider using the same method from the MeshBuilder class instead.
  23607. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23608. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23609. * 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.
  23610. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23611. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23615. */
  23616. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23617. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23618. if (scene !== undefined) {
  23619. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23620. updatable = scene;
  23621. }
  23622. scene = subdivisions;
  23623. subdivisions = 1;
  23624. }
  23625. var options = {
  23626. height: height,
  23627. diameterTop: diameterTop,
  23628. diameterBottom: diameterBottom,
  23629. tessellation: tessellation,
  23630. subdivisions: subdivisions,
  23631. sideOrientation: sideOrientation,
  23632. updatable: updatable
  23633. };
  23634. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23635. };
  23636. // Torus (Code from SharpDX.org)
  23637. /**
  23638. * Creates a torus mesh.
  23639. * Please consider using the same method from the MeshBuilder class instead.
  23640. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23641. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23642. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23646. */
  23647. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23648. var options = {
  23649. diameter: diameter,
  23650. thickness: thickness,
  23651. tessellation: tessellation,
  23652. sideOrientation: sideOrientation,
  23653. updatable: updatable
  23654. };
  23655. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23656. };
  23657. /**
  23658. * Creates a torus knot mesh.
  23659. * Please consider using the same method from the MeshBuilder class instead.
  23660. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23661. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23662. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23663. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23664. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23665. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23666. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23667. */
  23668. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23669. var options = {
  23670. radius: radius,
  23671. tube: tube,
  23672. radialSegments: radialSegments,
  23673. tubularSegments: tubularSegments,
  23674. p: p,
  23675. q: q,
  23676. sideOrientation: sideOrientation,
  23677. updatable: updatable
  23678. };
  23679. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23680. };
  23681. /**
  23682. * Creates a line mesh.
  23683. * Please consider using the same method from the MeshBuilder class instead.
  23684. * 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.
  23685. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23686. * The parameter `points` is an array successive Vector3.
  23687. * 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
  23688. * When updating an instance, remember that only point positions can change, not the number of points.
  23689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23690. */
  23691. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23692. var options = {
  23693. points: points,
  23694. updatable: updatable,
  23695. instance: instance
  23696. };
  23697. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23698. };
  23699. /**
  23700. * Creates a dashed line mesh.
  23701. * Please consider using the same method from the MeshBuilder class instead.
  23702. * 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.
  23703. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23704. * The parameter `points` is an array successive Vector3.
  23705. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23706. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23707. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23708. * 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
  23709. * When updating an instance, remember that only point positions can change, not the number of points.
  23710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23711. */
  23712. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23713. var options = {
  23714. points: points,
  23715. dashSize: dashSize,
  23716. gapSize: gapSize,
  23717. dashNb: dashNb,
  23718. updatable: updatable,
  23719. instance: instance
  23720. };
  23721. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23722. };
  23723. /**
  23724. * Creates a polygon mesh.
  23725. * Please consider using the same method from the MeshBuilder class instead.
  23726. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23727. * 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.
  23728. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23730. * Remember you can only change the shape positions, not their number when updating a polygon.
  23731. */
  23732. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23733. var options = {
  23734. shape: shape,
  23735. holes: holes,
  23736. updatable: updatable,
  23737. sideOrientation: sideOrientation
  23738. };
  23739. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23740. };
  23741. /**
  23742. * Creates an extruded polygon mesh, with depth in the Y direction.
  23743. * Please consider using the same method from the MeshBuilder class instead.
  23744. */
  23745. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23746. var options = {
  23747. shape: shape,
  23748. holes: holes,
  23749. depth: depth,
  23750. updatable: updatable,
  23751. sideOrientation: sideOrientation
  23752. };
  23753. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23754. };
  23755. /**
  23756. * Creates an extruded shape mesh.
  23757. * 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.
  23758. * Please consider using the same method from the MeshBuilder class instead.
  23759. *
  23760. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23761. * 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
  23762. * extruded along the Z axis.
  23763. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23764. * 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.
  23765. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23766. * 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
  23767. * 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
  23768. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23769. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23770. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23772. */
  23773. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23774. var options = {
  23775. shape: shape,
  23776. path: path,
  23777. scale: scale,
  23778. rotation: rotation,
  23779. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23780. sideOrientation: sideOrientation,
  23781. instance: instance,
  23782. updatable: updatable
  23783. };
  23784. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23785. };
  23786. /**
  23787. * Creates an custom extruded shape mesh.
  23788. * 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.
  23789. * Please consider using the same method from the MeshBuilder class instead.
  23790. *
  23791. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23792. * 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
  23793. * extruded along the Z axis.
  23794. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23795. * 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
  23796. * and the distance of this point from the begining of the path :
  23797. * ```javascript
  23798. * var rotationFunction = function(i, distance) {
  23799. * // do things
  23800. * return rotationValue; }
  23801. * ```
  23802. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23803. * 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
  23804. * and the distance of this point from the begining of the path :
  23805. * ```javascript
  23806. * var scaleFunction = function(i, distance) {
  23807. * // do things
  23808. * return scaleValue;}
  23809. * ```
  23810. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23811. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23812. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23813. * 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
  23814. * 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
  23815. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23819. */
  23820. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23821. var options = {
  23822. shape: shape,
  23823. path: path,
  23824. scaleFunction: scaleFunction,
  23825. rotationFunction: rotationFunction,
  23826. ribbonCloseArray: ribbonCloseArray,
  23827. ribbonClosePath: ribbonClosePath,
  23828. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23829. sideOrientation: sideOrientation,
  23830. instance: instance,
  23831. updatable: updatable
  23832. };
  23833. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23834. };
  23835. /**
  23836. * Creates lathe mesh.
  23837. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23838. * Please consider using the same method from the MeshBuilder class instead.
  23839. * 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
  23840. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23841. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23842. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23846. */
  23847. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23848. var options = {
  23849. shape: shape,
  23850. radius: radius,
  23851. tessellation: tessellation,
  23852. sideOrientation: sideOrientation,
  23853. updatable: updatable
  23854. };
  23855. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23856. };
  23857. /**
  23858. * Creates a plane mesh.
  23859. * Please consider using the same method from the MeshBuilder class instead.
  23860. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23864. */
  23865. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23866. var options = {
  23867. size: size,
  23868. width: size,
  23869. height: size,
  23870. sideOrientation: sideOrientation,
  23871. updatable: updatable
  23872. };
  23873. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23874. };
  23875. /**
  23876. * Creates a ground mesh.
  23877. * Please consider using the same method from the MeshBuilder class instead.
  23878. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23879. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23881. */
  23882. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23883. var options = {
  23884. width: width,
  23885. height: height,
  23886. subdivisions: subdivisions,
  23887. updatable: updatable
  23888. };
  23889. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23890. };
  23891. /**
  23892. * Creates a tiled ground mesh.
  23893. * Please consider using the same method from the MeshBuilder class instead.
  23894. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23895. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23896. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23897. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23898. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23899. * numbers of subdivisions on the ground width and height of each tile.
  23900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23901. */
  23902. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23903. var options = {
  23904. xmin: xmin,
  23905. zmin: zmin,
  23906. xmax: xmax,
  23907. zmax: zmax,
  23908. subdivisions: subdivisions,
  23909. precision: precision,
  23910. updatable: updatable
  23911. };
  23912. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23913. };
  23914. /**
  23915. * Creates a ground mesh from a height map.
  23916. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23917. * Please consider using the same method from the MeshBuilder class instead.
  23918. * The parameter `url` sets the URL of the height map image resource.
  23919. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23920. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23921. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23922. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23923. * 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).
  23924. * This function is passed the newly built mesh :
  23925. * ```javascript
  23926. * function(mesh) { // do things
  23927. * return; }
  23928. * ```
  23929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23930. */
  23931. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23932. var options = {
  23933. width: width,
  23934. height: height,
  23935. subdivisions: subdivisions,
  23936. minHeight: minHeight,
  23937. maxHeight: maxHeight,
  23938. updatable: updatable,
  23939. onReady: onReady
  23940. };
  23941. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23942. };
  23943. /**
  23944. * Creates a tube mesh.
  23945. * 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.
  23946. * Please consider using the same method from the MeshBuilder class instead.
  23947. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23948. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23949. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23950. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23951. * 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.
  23952. * It must return a radius value (positive float) :
  23953. * ```javascript
  23954. * var radiusFunction = function(i, distance) {
  23955. * // do things
  23956. * return radius; }
  23957. * ```
  23958. * 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
  23959. * 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
  23960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23961. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23963. */
  23964. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23965. var options = {
  23966. path: path,
  23967. radius: radius,
  23968. tessellation: tessellation,
  23969. radiusFunction: radiusFunction,
  23970. arc: 1,
  23971. cap: cap,
  23972. updatable: updatable,
  23973. sideOrientation: sideOrientation,
  23974. instance: instance
  23975. };
  23976. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23977. };
  23978. /**
  23979. * Creates a polyhedron mesh.
  23980. * Please consider using the same method from the MeshBuilder class instead.
  23981. * 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
  23982. * to choose the wanted type.
  23983. * The parameter `size` (positive float, default 1) sets the polygon size.
  23984. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23985. * 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`.
  23986. * 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
  23987. * 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)`).
  23988. * 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
  23989. * 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.
  23990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23993. */
  23994. Mesh.CreatePolyhedron = function (name, options, scene) {
  23995. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23996. };
  23997. /**
  23998. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23999. * Please consider using the same method from the MeshBuilder class instead.
  24000. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24001. * 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`).
  24002. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24003. * 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.
  24004. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24005. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24007. */
  24008. Mesh.CreateIcoSphere = function (name, options, scene) {
  24009. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24010. };
  24011. /**
  24012. * Creates a decal mesh.
  24013. * Please consider using the same method from the MeshBuilder class instead.
  24014. * 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.
  24015. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24016. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24017. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24018. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24019. */
  24020. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24021. var options = {
  24022. position: position,
  24023. normal: normal,
  24024. size: size,
  24025. angle: angle
  24026. };
  24027. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24028. };
  24029. // Skeletons
  24030. /**
  24031. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24032. */
  24033. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24034. var source;
  24035. if (!this._sourcePositions) {
  24036. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24037. this._sourcePositions = new Float32Array(source);
  24038. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24039. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24040. }
  24041. }
  24042. return this._sourcePositions;
  24043. };
  24044. /**
  24045. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24046. */
  24047. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24048. var source;
  24049. if (!this._sourceNormals) {
  24050. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24051. this._sourceNormals = new Float32Array(source);
  24052. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24053. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24054. }
  24055. }
  24056. return this._sourceNormals;
  24057. };
  24058. /**
  24059. * Updates the vertex buffer by applying transformation from the bones.
  24060. * Returns the Mesh.
  24061. *
  24062. * @param {skeleton} skeleton to apply
  24063. */
  24064. Mesh.prototype.applySkeleton = function (skeleton) {
  24065. if (!this.geometry) {
  24066. return this;
  24067. }
  24068. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24069. return this;
  24070. }
  24071. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24072. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24073. return this;
  24074. }
  24075. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24076. return this;
  24077. }
  24078. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24079. return this;
  24080. }
  24081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24082. return this;
  24083. }
  24084. if (!this._sourcePositions) {
  24085. var submeshes = this.subMeshes.slice();
  24086. this.setPositionsForCPUSkinning();
  24087. this.subMeshes = submeshes;
  24088. }
  24089. if (!this._sourceNormals) {
  24090. this.setNormalsForCPUSkinning();
  24091. }
  24092. // positionsData checks for not being Float32Array will only pass at most once
  24093. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24094. if (!(positionsData instanceof Float32Array)) {
  24095. positionsData = new Float32Array(positionsData);
  24096. }
  24097. // normalsData checks for not being Float32Array will only pass at most once
  24098. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24099. if (!(normalsData instanceof Float32Array)) {
  24100. normalsData = new Float32Array(normalsData);
  24101. }
  24102. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24103. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24104. var needExtras = this.numBoneInfluencers > 4;
  24105. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24106. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24107. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24108. var tempVector3 = BABYLON.Vector3.Zero();
  24109. var finalMatrix = new BABYLON.Matrix();
  24110. var tempMatrix = new BABYLON.Matrix();
  24111. var matWeightIdx = 0;
  24112. var inf;
  24113. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24114. var weight;
  24115. for (inf = 0; inf < 4; inf++) {
  24116. weight = matricesWeightsData[matWeightIdx + inf];
  24117. if (weight > 0) {
  24118. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24119. finalMatrix.addToSelf(tempMatrix);
  24120. }
  24121. else
  24122. break;
  24123. }
  24124. if (needExtras) {
  24125. for (inf = 0; inf < 4; inf++) {
  24126. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24127. if (weight > 0) {
  24128. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24129. finalMatrix.addToSelf(tempMatrix);
  24130. }
  24131. else
  24132. break;
  24133. }
  24134. }
  24135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24136. tempVector3.toArray(positionsData, index);
  24137. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24138. tempVector3.toArray(normalsData, index);
  24139. finalMatrix.reset();
  24140. }
  24141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24142. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24143. return this;
  24144. };
  24145. // Tools
  24146. /**
  24147. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24148. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24149. */
  24150. Mesh.MinMax = function (meshes) {
  24151. var minVector = null;
  24152. var maxVector = null;
  24153. meshes.forEach(function (mesh, index, array) {
  24154. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24155. if (!minVector) {
  24156. minVector = boundingBox.minimumWorld;
  24157. maxVector = boundingBox.maximumWorld;
  24158. }
  24159. else {
  24160. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24161. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24162. }
  24163. });
  24164. return {
  24165. min: minVector,
  24166. max: maxVector
  24167. };
  24168. };
  24169. /**
  24170. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24171. */
  24172. Mesh.Center = function (meshesOrMinMaxVector) {
  24173. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24174. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24175. };
  24176. /**
  24177. * Merge the array of meshes into a single mesh for performance reasons.
  24178. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24179. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24180. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24181. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24182. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24183. */
  24184. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24185. if (disposeSource === void 0) { disposeSource = true; }
  24186. var index;
  24187. if (!allow32BitsIndices) {
  24188. var totalVertices = 0;
  24189. // Counting vertices
  24190. for (index = 0; index < meshes.length; index++) {
  24191. if (meshes[index]) {
  24192. totalVertices += meshes[index].getTotalVertices();
  24193. if (totalVertices > 65536) {
  24194. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24195. return null;
  24196. }
  24197. }
  24198. }
  24199. }
  24200. // Merge
  24201. var vertexData;
  24202. var otherVertexData;
  24203. var indiceArray = new Array();
  24204. var source;
  24205. for (index = 0; index < meshes.length; index++) {
  24206. if (meshes[index]) {
  24207. meshes[index].computeWorldMatrix(true);
  24208. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24209. otherVertexData.transform(meshes[index].getWorldMatrix());
  24210. if (vertexData) {
  24211. vertexData.merge(otherVertexData);
  24212. }
  24213. else {
  24214. vertexData = otherVertexData;
  24215. source = meshes[index];
  24216. }
  24217. if (subdivideWithSubMeshes) {
  24218. indiceArray.push(meshes[index].getTotalIndices());
  24219. }
  24220. }
  24221. }
  24222. if (!meshSubclass) {
  24223. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24224. }
  24225. vertexData.applyToMesh(meshSubclass);
  24226. // Setting properties
  24227. meshSubclass.material = source.material;
  24228. meshSubclass.checkCollisions = source.checkCollisions;
  24229. // Cleaning
  24230. if (disposeSource) {
  24231. for (index = 0; index < meshes.length; index++) {
  24232. if (meshes[index]) {
  24233. meshes[index].dispose();
  24234. }
  24235. }
  24236. }
  24237. // Subdivide
  24238. if (subdivideWithSubMeshes) {
  24239. //-- Suppresions du submesh global
  24240. meshSubclass.releaseSubMeshes();
  24241. index = 0;
  24242. var offset = 0;
  24243. //-- aplique la subdivision en fonction du tableau d'indices
  24244. while (index < indiceArray.length) {
  24245. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24246. offset += indiceArray[index];
  24247. index++;
  24248. }
  24249. }
  24250. return meshSubclass;
  24251. };
  24252. // Consts
  24253. Mesh._FRONTSIDE = 0;
  24254. Mesh._BACKSIDE = 1;
  24255. Mesh._DOUBLESIDE = 2;
  24256. Mesh._DEFAULTSIDE = 0;
  24257. Mesh._NO_CAP = 0;
  24258. Mesh._CAP_START = 1;
  24259. Mesh._CAP_END = 2;
  24260. Mesh._CAP_ALL = 3;
  24261. return Mesh;
  24262. }(BABYLON.AbstractMesh));
  24263. BABYLON.Mesh = Mesh;
  24264. })(BABYLON || (BABYLON = {}));
  24265. //# sourceMappingURL=babylon.mesh.js.map
  24266. var BABYLON;
  24267. (function (BABYLON) {
  24268. var BaseSubMesh = (function () {
  24269. function BaseSubMesh() {
  24270. }
  24271. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24272. get: function () {
  24273. return this._materialEffect;
  24274. },
  24275. enumerable: true,
  24276. configurable: true
  24277. });
  24278. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24279. if (this._materialEffect === effect) {
  24280. if (!effect) {
  24281. this._materialDefines = undefined;
  24282. }
  24283. return;
  24284. }
  24285. this._materialDefines = defines;
  24286. this._materialEffect = effect;
  24287. };
  24288. return BaseSubMesh;
  24289. }());
  24290. BABYLON.BaseSubMesh = BaseSubMesh;
  24291. var SubMesh = (function (_super) {
  24292. __extends(SubMesh, _super);
  24293. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24294. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24295. var _this = _super.call(this) || this;
  24296. _this.materialIndex = materialIndex;
  24297. _this.verticesStart = verticesStart;
  24298. _this.verticesCount = verticesCount;
  24299. _this.indexStart = indexStart;
  24300. _this.indexCount = indexCount;
  24301. _this._renderId = 0;
  24302. _this._mesh = mesh;
  24303. _this._renderingMesh = renderingMesh || mesh;
  24304. mesh.subMeshes.push(_this);
  24305. _this._trianglePlanes = [];
  24306. _this._id = mesh.subMeshes.length - 1;
  24307. if (createBoundingBox) {
  24308. _this.refreshBoundingInfo();
  24309. mesh.computeWorldMatrix(true);
  24310. }
  24311. return _this;
  24312. }
  24313. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24314. get: function () {
  24315. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. /**
  24321. * Returns the submesh BoudingInfo object.
  24322. */
  24323. SubMesh.prototype.getBoundingInfo = function () {
  24324. if (this.IsGlobal) {
  24325. return this._mesh.getBoundingInfo();
  24326. }
  24327. return this._boundingInfo;
  24328. };
  24329. /**
  24330. * Sets the submesh BoundingInfo.
  24331. * Return the SubMesh.
  24332. */
  24333. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24334. this._boundingInfo = boundingInfo;
  24335. return this;
  24336. };
  24337. /**
  24338. * Returns the mesh of the current submesh.
  24339. */
  24340. SubMesh.prototype.getMesh = function () {
  24341. return this._mesh;
  24342. };
  24343. /**
  24344. * Returns the rendering mesh of the submesh.
  24345. */
  24346. SubMesh.prototype.getRenderingMesh = function () {
  24347. return this._renderingMesh;
  24348. };
  24349. /**
  24350. * Returns the submesh material.
  24351. */
  24352. SubMesh.prototype.getMaterial = function () {
  24353. var rootMaterial = this._renderingMesh.material;
  24354. if (rootMaterial && rootMaterial.getSubMaterial) {
  24355. var multiMaterial = rootMaterial;
  24356. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24357. if (this._currentMaterial !== effectiveMaterial) {
  24358. this._currentMaterial = effectiveMaterial;
  24359. this._materialDefines = undefined;
  24360. }
  24361. return effectiveMaterial;
  24362. }
  24363. if (!rootMaterial) {
  24364. return this._mesh.getScene().defaultMaterial;
  24365. }
  24366. return rootMaterial;
  24367. };
  24368. // Methods
  24369. /**
  24370. * Sets a new updated BoundingInfo object to the submesh.
  24371. * Returns the SubMesh.
  24372. */
  24373. SubMesh.prototype.refreshBoundingInfo = function () {
  24374. this._lastColliderWorldVertices = null;
  24375. if (this.IsGlobal) {
  24376. return;
  24377. }
  24378. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24379. if (!data) {
  24380. this._boundingInfo = this._mesh._boundingInfo;
  24381. return;
  24382. }
  24383. var indices = this._renderingMesh.getIndices();
  24384. var extend;
  24385. //is this the only submesh?
  24386. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24387. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24388. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24389. }
  24390. else {
  24391. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24392. }
  24393. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24394. return this;
  24395. };
  24396. SubMesh.prototype._checkCollision = function (collider) {
  24397. return this.getBoundingInfo()._checkCollision(collider);
  24398. };
  24399. /**
  24400. * Updates the submesh BoundingInfo.
  24401. * Returns the Submesh.
  24402. */
  24403. SubMesh.prototype.updateBoundingInfo = function (world) {
  24404. if (!this.getBoundingInfo()) {
  24405. this.refreshBoundingInfo();
  24406. }
  24407. this.getBoundingInfo().update(world);
  24408. return this;
  24409. };
  24410. /**
  24411. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24412. * Boolean returned.
  24413. */
  24414. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24415. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24416. };
  24417. /**
  24418. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24419. * Boolean returned.
  24420. */
  24421. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24422. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24423. };
  24424. /**
  24425. * Renders the submesh.
  24426. * Returns it.
  24427. */
  24428. SubMesh.prototype.render = function (enableAlphaMode) {
  24429. this._renderingMesh.render(this, enableAlphaMode);
  24430. return this;
  24431. };
  24432. /**
  24433. * Returns a new Index Buffer.
  24434. * Type returned : WebGLBuffer.
  24435. */
  24436. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24437. if (!this._linesIndexBuffer) {
  24438. var linesIndices = [];
  24439. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24440. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24441. }
  24442. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24443. this.linesIndexCount = linesIndices.length;
  24444. }
  24445. return this._linesIndexBuffer;
  24446. };
  24447. /**
  24448. * True is the passed Ray intersects the submesh bounding box.
  24449. * Boolean returned.
  24450. */
  24451. SubMesh.prototype.canIntersects = function (ray) {
  24452. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24453. };
  24454. /**
  24455. * Returns an object IntersectionInfo.
  24456. */
  24457. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24458. var intersectInfo = null;
  24459. // LineMesh first as it's also a Mesh...
  24460. if (this._mesh instanceof BABYLON.LinesMesh) {
  24461. var lineMesh = this._mesh;
  24462. // Line test
  24463. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24464. var p0 = positions[indices[index]];
  24465. var p1 = positions[indices[index + 1]];
  24466. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24467. if (length < 0) {
  24468. continue;
  24469. }
  24470. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24471. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24472. if (fastCheck) {
  24473. break;
  24474. }
  24475. }
  24476. }
  24477. }
  24478. else {
  24479. // Triangles test
  24480. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24481. var p0 = positions[indices[index]];
  24482. var p1 = positions[indices[index + 1]];
  24483. var p2 = positions[indices[index + 2]];
  24484. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24485. if (currentIntersectInfo) {
  24486. if (currentIntersectInfo.distance < 0) {
  24487. continue;
  24488. }
  24489. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24490. intersectInfo = currentIntersectInfo;
  24491. intersectInfo.faceId = index / 3;
  24492. if (fastCheck) {
  24493. break;
  24494. }
  24495. }
  24496. }
  24497. }
  24498. }
  24499. return intersectInfo;
  24500. };
  24501. SubMesh.prototype._rebuild = function () {
  24502. if (this._linesIndexBuffer) {
  24503. this._linesIndexBuffer = null;
  24504. }
  24505. };
  24506. // Clone
  24507. /**
  24508. * Creates a new Submesh from the passed Mesh.
  24509. */
  24510. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24511. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24512. if (!this.IsGlobal) {
  24513. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24514. }
  24515. return result;
  24516. };
  24517. // Dispose
  24518. /**
  24519. * Disposes the Submesh.
  24520. * Returns nothing.
  24521. */
  24522. SubMesh.prototype.dispose = function () {
  24523. if (this._linesIndexBuffer) {
  24524. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24525. this._linesIndexBuffer = null;
  24526. }
  24527. // Remove from mesh
  24528. var index = this._mesh.subMeshes.indexOf(this);
  24529. this._mesh.subMeshes.splice(index, 1);
  24530. };
  24531. // Statics
  24532. /**
  24533. * Creates a new Submesh from the passed parameters :
  24534. * - materialIndex (integer) : the index of the main mesh material.
  24535. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24536. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24537. * - mesh (Mesh) : the main mesh to create the submesh from.
  24538. * - renderingMesh (optional Mesh) : rendering mesh.
  24539. */
  24540. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24541. var minVertexIndex = Number.MAX_VALUE;
  24542. var maxVertexIndex = -Number.MAX_VALUE;
  24543. renderingMesh = renderingMesh || mesh;
  24544. var indices = renderingMesh.getIndices();
  24545. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24546. var vertexIndex = indices[index];
  24547. if (vertexIndex < minVertexIndex)
  24548. minVertexIndex = vertexIndex;
  24549. if (vertexIndex > maxVertexIndex)
  24550. maxVertexIndex = vertexIndex;
  24551. }
  24552. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24553. };
  24554. return SubMesh;
  24555. }(BaseSubMesh));
  24556. BABYLON.SubMesh = SubMesh;
  24557. })(BABYLON || (BABYLON = {}));
  24558. //# sourceMappingURL=babylon.subMesh.js.map
  24559. var BABYLON;
  24560. (function (BABYLON) {
  24561. var EffectFallbacks = (function () {
  24562. function EffectFallbacks() {
  24563. this._defines = {};
  24564. this._currentRank = 32;
  24565. this._maxRank = -1;
  24566. }
  24567. EffectFallbacks.prototype.unBindMesh = function () {
  24568. this._mesh = null;
  24569. };
  24570. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24571. if (!this._defines[rank]) {
  24572. if (rank < this._currentRank) {
  24573. this._currentRank = rank;
  24574. }
  24575. if (rank > this._maxRank) {
  24576. this._maxRank = rank;
  24577. }
  24578. this._defines[rank] = new Array();
  24579. }
  24580. this._defines[rank].push(define);
  24581. };
  24582. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24583. this._meshRank = rank;
  24584. this._mesh = mesh;
  24585. if (rank < this._currentRank) {
  24586. this._currentRank = rank;
  24587. }
  24588. if (rank > this._maxRank) {
  24589. this._maxRank = rank;
  24590. }
  24591. };
  24592. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24593. get: function () {
  24594. return this._currentRank <= this._maxRank;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24600. // First we try to switch to CPU skinning
  24601. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24602. this._mesh.computeBonesUsingShaders = false;
  24603. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24604. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24605. var scene = this._mesh.getScene();
  24606. for (var index = 0; index < scene.meshes.length; index++) {
  24607. var otherMesh = scene.meshes[index];
  24608. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24609. otherMesh.computeBonesUsingShaders = false;
  24610. }
  24611. }
  24612. }
  24613. else {
  24614. var currentFallbacks = this._defines[this._currentRank];
  24615. if (currentFallbacks) {
  24616. for (var index = 0; index < currentFallbacks.length; index++) {
  24617. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24618. }
  24619. }
  24620. this._currentRank++;
  24621. }
  24622. return currentDefines;
  24623. };
  24624. return EffectFallbacks;
  24625. }());
  24626. BABYLON.EffectFallbacks = EffectFallbacks;
  24627. var EffectCreationOptions = (function () {
  24628. function EffectCreationOptions() {
  24629. }
  24630. return EffectCreationOptions;
  24631. }());
  24632. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24633. var Effect = (function () {
  24634. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24635. var _this = this;
  24636. this.uniqueId = 0;
  24637. this.onCompileObservable = new BABYLON.Observable();
  24638. this.onErrorObservable = new BABYLON.Observable();
  24639. this.onBindObservable = new BABYLON.Observable();
  24640. this._uniformBuffersNames = {};
  24641. this._isReady = false;
  24642. this._compilationError = "";
  24643. this.name = baseName;
  24644. if (attributesNamesOrOptions.attributes) {
  24645. var options = attributesNamesOrOptions;
  24646. this._engine = uniformsNamesOrEngine;
  24647. this._attributesNames = options.attributes;
  24648. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24649. this._samplers = options.samplers;
  24650. this.defines = options.defines;
  24651. this.onError = options.onError;
  24652. this.onCompiled = options.onCompiled;
  24653. this._fallbacks = options.fallbacks;
  24654. this._indexParameters = options.indexParameters;
  24655. if (options.uniformBuffersNames) {
  24656. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24657. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24658. }
  24659. }
  24660. }
  24661. else {
  24662. this._engine = engine;
  24663. this.defines = defines;
  24664. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24665. this._samplers = samplers;
  24666. this._attributesNames = attributesNamesOrOptions;
  24667. this.onError = onError;
  24668. this.onCompiled = onCompiled;
  24669. this._indexParameters = indexParameters;
  24670. this._fallbacks = fallbacks;
  24671. }
  24672. this.uniqueId = Effect._uniqueIdSeed++;
  24673. var vertexSource;
  24674. var fragmentSource;
  24675. if (baseName.vertexElement) {
  24676. vertexSource = document.getElementById(baseName.vertexElement);
  24677. if (!vertexSource) {
  24678. vertexSource = baseName.vertexElement;
  24679. }
  24680. }
  24681. else {
  24682. vertexSource = baseName.vertex || baseName;
  24683. }
  24684. if (baseName.fragmentElement) {
  24685. fragmentSource = document.getElementById(baseName.fragmentElement);
  24686. if (!fragmentSource) {
  24687. fragmentSource = baseName.fragmentElement;
  24688. }
  24689. }
  24690. else {
  24691. fragmentSource = baseName.fragment || baseName;
  24692. }
  24693. this._loadVertexShader(vertexSource, function (vertexCode) {
  24694. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24695. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24696. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24697. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24698. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24699. if (baseName) {
  24700. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  24701. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  24702. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  24703. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  24704. }
  24705. else {
  24706. _this._vertexSourceCode = migratedVertexCode;
  24707. _this._fragmentSourceCode = migratedFragmentCode;
  24708. }
  24709. _this._prepareEffect();
  24710. });
  24711. });
  24712. });
  24713. });
  24714. });
  24715. });
  24716. }
  24717. Object.defineProperty(Effect.prototype, "key", {
  24718. get: function () {
  24719. return this._key;
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. // Properties
  24725. Effect.prototype.isReady = function () {
  24726. return this._isReady;
  24727. };
  24728. Effect.prototype.getEngine = function () {
  24729. return this._engine;
  24730. };
  24731. Effect.prototype.getProgram = function () {
  24732. return this._program;
  24733. };
  24734. Effect.prototype.getAttributesNames = function () {
  24735. return this._attributesNames;
  24736. };
  24737. Effect.prototype.getAttributeLocation = function (index) {
  24738. return this._attributes[index];
  24739. };
  24740. Effect.prototype.getAttributeLocationByName = function (name) {
  24741. var index = this._attributesNames.indexOf(name);
  24742. return this._attributes[index];
  24743. };
  24744. Effect.prototype.getAttributesCount = function () {
  24745. return this._attributes.length;
  24746. };
  24747. Effect.prototype.getUniformIndex = function (uniformName) {
  24748. return this._uniformsNames.indexOf(uniformName);
  24749. };
  24750. Effect.prototype.getUniform = function (uniformName) {
  24751. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24752. };
  24753. Effect.prototype.getSamplers = function () {
  24754. return this._samplers;
  24755. };
  24756. Effect.prototype.getCompilationError = function () {
  24757. return this._compilationError;
  24758. };
  24759. // Methods
  24760. Effect.prototype.executeWhenCompiled = function (func) {
  24761. if (this.isReady()) {
  24762. func(this);
  24763. return;
  24764. }
  24765. this.onCompileObservable.add(function (effect) {
  24766. func(effect);
  24767. });
  24768. };
  24769. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24770. if (BABYLON.Tools.IsWindowObjectExist()) {
  24771. // DOM element ?
  24772. if (vertex instanceof HTMLElement) {
  24773. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24774. callback(vertexCode);
  24775. return;
  24776. }
  24777. }
  24778. // Base64 encoded ?
  24779. if (vertex.substr(0, 7) === "base64:") {
  24780. var vertexBinary = window.atob(vertex.substr(7));
  24781. callback(vertexBinary);
  24782. return;
  24783. }
  24784. // Is in local store ?
  24785. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24786. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24787. return;
  24788. }
  24789. var vertexShaderUrl;
  24790. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24791. vertexShaderUrl = vertex;
  24792. }
  24793. else {
  24794. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24795. }
  24796. // Vertex shader
  24797. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24798. };
  24799. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24800. if (BABYLON.Tools.IsWindowObjectExist()) {
  24801. // DOM element ?
  24802. if (fragment instanceof HTMLElement) {
  24803. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24804. callback(fragmentCode);
  24805. return;
  24806. }
  24807. }
  24808. // Base64 encoded ?
  24809. if (fragment.substr(0, 7) === "base64:") {
  24810. var fragmentBinary = window.atob(fragment.substr(7));
  24811. callback(fragmentBinary);
  24812. return;
  24813. }
  24814. // Is in local store ?
  24815. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24816. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24817. return;
  24818. }
  24819. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24820. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24821. return;
  24822. }
  24823. var fragmentShaderUrl;
  24824. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24825. fragmentShaderUrl = fragment;
  24826. }
  24827. else {
  24828. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24829. }
  24830. // Fragment shader
  24831. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24832. };
  24833. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24834. // Rebuild shaders source code
  24835. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24836. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24837. vertexCode = prefix + vertexCode;
  24838. fragmentCode = prefix + fragmentCode;
  24839. // Number lines of shaders source code
  24840. var i = 2;
  24841. var regex = /\n/gm;
  24842. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24843. i = 2;
  24844. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24845. // Dump shaders name and formatted source code
  24846. if (this.name.vertexElement) {
  24847. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24848. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24849. }
  24850. else if (this.name.vertex) {
  24851. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24852. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24853. }
  24854. else {
  24855. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24856. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24857. }
  24858. };
  24859. ;
  24860. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24861. var preparedSourceCode = this._processPrecision(sourceCode);
  24862. if (this._engine.webGLVersion == 1) {
  24863. callback(preparedSourceCode);
  24864. return;
  24865. }
  24866. // Already converted
  24867. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24868. callback(preparedSourceCode.replace("#version 300 es", ""));
  24869. return;
  24870. }
  24871. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24872. // Remove extensions
  24873. // #extension GL_OES_standard_derivatives : enable
  24874. // #extension GL_EXT_shader_texture_lod : enable
  24875. // #extension GL_EXT_frag_depth : enable
  24876. // #extension GL_EXT_draw_buffers : require
  24877. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24878. var result = preparedSourceCode.replace(regex, "");
  24879. // Migrate to GLSL v300
  24880. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24881. result = result.replace(/attribute[ \t]/g, "in ");
  24882. result = result.replace(/[ \t]attribute/g, " in");
  24883. if (isFragment) {
  24884. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  24885. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  24886. result = result.replace(/texture2D\s*\(/g, "texture(");
  24887. result = result.replace(/textureCube\s*\(/g, "texture(");
  24888. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24889. result = result.replace(/gl_FragColor/g, "glFragColor");
  24890. result = result.replace(/gl_FragData/g, "glFragData");
  24891. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24892. }
  24893. callback(result);
  24894. };
  24895. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24896. var _this = this;
  24897. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24898. var match = regex.exec(sourceCode);
  24899. var returnValue = new String(sourceCode);
  24900. while (match != null) {
  24901. var includeFile = match[1];
  24902. // Uniform declaration
  24903. if (includeFile.indexOf("__decl__") !== -1) {
  24904. includeFile = includeFile.replace(/__decl__/, "");
  24905. if (this._engine.supportsUniformBuffers) {
  24906. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24907. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24908. }
  24909. includeFile = includeFile + "Declaration";
  24910. }
  24911. if (Effect.IncludesShadersStore[includeFile]) {
  24912. // Substitution
  24913. var includeContent = Effect.IncludesShadersStore[includeFile];
  24914. if (match[2]) {
  24915. var splits = match[3].split(",");
  24916. for (var index = 0; index < splits.length; index += 2) {
  24917. var source = new RegExp(splits[index], "g");
  24918. var dest = splits[index + 1];
  24919. includeContent = includeContent.replace(source, dest);
  24920. }
  24921. }
  24922. if (match[4]) {
  24923. var indexString = match[5];
  24924. if (indexString.indexOf("..") !== -1) {
  24925. var indexSplits = indexString.split("..");
  24926. var minIndex = parseInt(indexSplits[0]);
  24927. var maxIndex = parseInt(indexSplits[1]);
  24928. var sourceIncludeContent = includeContent.slice(0);
  24929. includeContent = "";
  24930. if (isNaN(maxIndex)) {
  24931. maxIndex = this._indexParameters[indexSplits[1]];
  24932. }
  24933. for (var i = minIndex; i < maxIndex; i++) {
  24934. if (!this._engine.supportsUniformBuffers) {
  24935. // Ubo replacement
  24936. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24937. return p1 + "{X}";
  24938. });
  24939. }
  24940. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  24941. }
  24942. }
  24943. else {
  24944. if (!this._engine.supportsUniformBuffers) {
  24945. // Ubo replacement
  24946. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24947. return p1 + "{X}";
  24948. });
  24949. }
  24950. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24951. }
  24952. }
  24953. // Replace
  24954. returnValue = returnValue.replace(match[0], includeContent);
  24955. }
  24956. else {
  24957. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24958. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24959. Effect.IncludesShadersStore[includeFile] = fileContent;
  24960. _this._processIncludes(returnValue, callback);
  24961. });
  24962. return;
  24963. }
  24964. match = regex.exec(sourceCode);
  24965. }
  24966. callback(returnValue);
  24967. };
  24968. Effect.prototype._processPrecision = function (source) {
  24969. if (source.indexOf("precision highp float") === -1) {
  24970. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24971. source = "precision mediump float;\n" + source;
  24972. }
  24973. else {
  24974. source = "precision highp float;\n" + source;
  24975. }
  24976. }
  24977. else {
  24978. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24979. source = source.replace("precision highp float", "precision mediump float");
  24980. }
  24981. }
  24982. return source;
  24983. };
  24984. Effect.prototype._prepareEffect = function () {
  24985. var attributesNames = this._attributesNames;
  24986. var defines = this.defines;
  24987. var fallbacks = this._fallbacks;
  24988. this._valueCache = {};
  24989. try {
  24990. var engine = this._engine;
  24991. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24992. if (engine.webGLVersion > 1) {
  24993. for (var name in this._uniformBuffersNames) {
  24994. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24995. }
  24996. }
  24997. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24998. this._attributes = engine.getAttributes(this._program, attributesNames);
  24999. var index;
  25000. for (index = 0; index < this._samplers.length; index++) {
  25001. var sampler = this.getUniform(this._samplers[index]);
  25002. if (sampler == null) {
  25003. this._samplers.splice(index, 1);
  25004. index--;
  25005. }
  25006. }
  25007. engine.bindSamplers(this);
  25008. this._compilationError = "";
  25009. this._isReady = true;
  25010. if (this.onCompiled) {
  25011. this.onCompiled(this);
  25012. }
  25013. this.onCompileObservable.notifyObservers(this);
  25014. this.onCompileObservable.clear();
  25015. // Unbind mesh reference in fallbacks
  25016. if (this._fallbacks) {
  25017. this._fallbacks.unBindMesh();
  25018. }
  25019. }
  25020. catch (e) {
  25021. this._compilationError = e.message;
  25022. // Let's go through fallbacks then
  25023. BABYLON.Tools.Error("Unable to compile effect:");
  25024. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25025. return " " + uniform;
  25026. }));
  25027. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25028. return " " + attribute;
  25029. }));
  25030. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25031. BABYLON.Tools.Error("Error: " + this._compilationError);
  25032. if (fallbacks && fallbacks.isMoreFallbacks) {
  25033. BABYLON.Tools.Error("Trying next fallback.");
  25034. this.defines = fallbacks.reduce(this.defines);
  25035. this._prepareEffect();
  25036. }
  25037. else {
  25038. if (this.onError) {
  25039. this.onError(this, this._compilationError);
  25040. }
  25041. this.onErrorObservable.notifyObservers(this);
  25042. this.onErrorObservable.clear();
  25043. // Unbind mesh reference in fallbacks
  25044. if (this._fallbacks) {
  25045. this._fallbacks.unBindMesh();
  25046. }
  25047. }
  25048. }
  25049. };
  25050. Object.defineProperty(Effect.prototype, "isSupported", {
  25051. get: function () {
  25052. return this._compilationError === "";
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. Effect.prototype._bindTexture = function (channel, texture) {
  25058. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25059. };
  25060. Effect.prototype.setTexture = function (channel, texture) {
  25061. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25062. };
  25063. Effect.prototype.setTextureArray = function (channel, textures) {
  25064. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25065. var initialPos = this._samplers.indexOf(channel);
  25066. for (var index = 1; index < textures.length; index++) {
  25067. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25068. }
  25069. }
  25070. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25071. };
  25072. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25073. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25074. };
  25075. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25076. var cache = this._valueCache[uniformName];
  25077. var flag = matrix.updateFlag;
  25078. if (cache !== undefined && cache === flag) {
  25079. return false;
  25080. }
  25081. this._valueCache[uniformName] = flag;
  25082. return true;
  25083. };
  25084. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25085. var cache = this._valueCache[uniformName];
  25086. if (!cache) {
  25087. cache = [x, y];
  25088. this._valueCache[uniformName] = cache;
  25089. return true;
  25090. }
  25091. var changed = false;
  25092. if (cache[0] !== x) {
  25093. cache[0] = x;
  25094. changed = true;
  25095. }
  25096. if (cache[1] !== y) {
  25097. cache[1] = y;
  25098. changed = true;
  25099. }
  25100. return changed;
  25101. };
  25102. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25103. var cache = this._valueCache[uniformName];
  25104. if (!cache) {
  25105. cache = [x, y, z];
  25106. this._valueCache[uniformName] = cache;
  25107. return true;
  25108. }
  25109. var changed = false;
  25110. if (cache[0] !== x) {
  25111. cache[0] = x;
  25112. changed = true;
  25113. }
  25114. if (cache[1] !== y) {
  25115. cache[1] = y;
  25116. changed = true;
  25117. }
  25118. if (cache[2] !== z) {
  25119. cache[2] = z;
  25120. changed = true;
  25121. }
  25122. return changed;
  25123. };
  25124. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25125. var cache = this._valueCache[uniformName];
  25126. if (!cache) {
  25127. cache = [x, y, z, w];
  25128. this._valueCache[uniformName] = cache;
  25129. return true;
  25130. }
  25131. var changed = false;
  25132. if (cache[0] !== x) {
  25133. cache[0] = x;
  25134. changed = true;
  25135. }
  25136. if (cache[1] !== y) {
  25137. cache[1] = y;
  25138. changed = true;
  25139. }
  25140. if (cache[2] !== z) {
  25141. cache[2] = z;
  25142. changed = true;
  25143. }
  25144. if (cache[3] !== w) {
  25145. cache[3] = w;
  25146. changed = true;
  25147. }
  25148. return changed;
  25149. };
  25150. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25151. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25152. return;
  25153. }
  25154. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25155. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25156. };
  25157. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25158. this._engine.bindUniformBlock(this._program, blockName, index);
  25159. };
  25160. Effect.prototype.setIntArray = function (uniformName, array) {
  25161. this._valueCache[uniformName] = null;
  25162. this._engine.setIntArray(this.getUniform(uniformName), array);
  25163. return this;
  25164. };
  25165. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25166. this._valueCache[uniformName] = null;
  25167. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25168. return this;
  25169. };
  25170. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25171. this._valueCache[uniformName] = null;
  25172. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25173. return this;
  25174. };
  25175. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25176. this._valueCache[uniformName] = null;
  25177. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25178. return this;
  25179. };
  25180. Effect.prototype.setFloatArray = function (uniformName, array) {
  25181. this._valueCache[uniformName] = null;
  25182. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25183. return this;
  25184. };
  25185. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25186. this._valueCache[uniformName] = null;
  25187. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25188. return this;
  25189. };
  25190. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25191. this._valueCache[uniformName] = null;
  25192. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25193. return this;
  25194. };
  25195. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25196. this._valueCache[uniformName] = null;
  25197. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25198. return this;
  25199. };
  25200. Effect.prototype.setArray = function (uniformName, array) {
  25201. this._valueCache[uniformName] = null;
  25202. this._engine.setArray(this.getUniform(uniformName), array);
  25203. return this;
  25204. };
  25205. Effect.prototype.setArray2 = function (uniformName, array) {
  25206. this._valueCache[uniformName] = null;
  25207. this._engine.setArray2(this.getUniform(uniformName), array);
  25208. return this;
  25209. };
  25210. Effect.prototype.setArray3 = function (uniformName, array) {
  25211. this._valueCache[uniformName] = null;
  25212. this._engine.setArray3(this.getUniform(uniformName), array);
  25213. return this;
  25214. };
  25215. Effect.prototype.setArray4 = function (uniformName, array) {
  25216. this._valueCache[uniformName] = null;
  25217. this._engine.setArray4(this.getUniform(uniformName), array);
  25218. return this;
  25219. };
  25220. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25221. if (!matrices) {
  25222. return;
  25223. }
  25224. this._valueCache[uniformName] = null;
  25225. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25226. return this;
  25227. };
  25228. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25229. if (this._cacheMatrix(uniformName, matrix)) {
  25230. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25231. }
  25232. return this;
  25233. };
  25234. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25235. this._valueCache[uniformName] = null;
  25236. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25237. return this;
  25238. };
  25239. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25240. this._valueCache[uniformName] = null;
  25241. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25242. return this;
  25243. };
  25244. Effect.prototype.setFloat = function (uniformName, value) {
  25245. var cache = this._valueCache[uniformName];
  25246. if (cache !== undefined && cache === value)
  25247. return this;
  25248. this._valueCache[uniformName] = value;
  25249. this._engine.setFloat(this.getUniform(uniformName), value);
  25250. return this;
  25251. };
  25252. Effect.prototype.setBool = function (uniformName, bool) {
  25253. var cache = this._valueCache[uniformName];
  25254. if (cache !== undefined && cache === bool)
  25255. return this;
  25256. this._valueCache[uniformName] = bool;
  25257. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25258. return this;
  25259. };
  25260. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25261. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25262. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25263. }
  25264. return this;
  25265. };
  25266. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25267. if (this._cacheFloat2(uniformName, x, y)) {
  25268. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25269. }
  25270. return this;
  25271. };
  25272. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25273. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25274. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25275. }
  25276. return this;
  25277. };
  25278. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25279. if (this._cacheFloat3(uniformName, x, y, z)) {
  25280. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25281. }
  25282. return this;
  25283. };
  25284. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25285. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25286. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25287. }
  25288. return this;
  25289. };
  25290. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25291. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25292. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25293. }
  25294. return this;
  25295. };
  25296. Effect.prototype.setColor3 = function (uniformName, color3) {
  25297. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25298. this._engine.setColor3(this.getUniform(uniformName), color3);
  25299. }
  25300. return this;
  25301. };
  25302. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25303. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25304. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25305. }
  25306. return this;
  25307. };
  25308. Effect.ResetCache = function () {
  25309. Effect._baseCache = {};
  25310. };
  25311. Effect._uniqueIdSeed = 0;
  25312. Effect._baseCache = {};
  25313. // Statics
  25314. Effect.ShadersStore = {};
  25315. Effect.IncludesShadersStore = {};
  25316. return Effect;
  25317. }());
  25318. BABYLON.Effect = Effect;
  25319. })(BABYLON || (BABYLON = {}));
  25320. //# sourceMappingURL=babylon.effect.js.map
  25321. var BABYLON;
  25322. (function (BABYLON) {
  25323. var MaterialHelper = (function () {
  25324. function MaterialHelper() {
  25325. }
  25326. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25327. defines._needUVs = true;
  25328. defines[key] = true;
  25329. if (texture.getTextureMatrix().isIdentity(true)) {
  25330. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25331. if (texture.coordinatesIndex === 0) {
  25332. defines["MAINUV1"] = true;
  25333. }
  25334. else {
  25335. defines["MAINUV2"] = true;
  25336. }
  25337. }
  25338. else {
  25339. defines[key + "DIRECTUV"] = 0;
  25340. }
  25341. };
  25342. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25343. var matrix = texture.getTextureMatrix();
  25344. if (!matrix.isIdentity(true)) {
  25345. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25346. }
  25347. };
  25348. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25349. if (defines._areMiscDirty) {
  25350. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25351. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25352. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25353. }
  25354. };
  25355. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25356. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25357. var changed = false;
  25358. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25359. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25360. changed = true;
  25361. }
  25362. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25363. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25364. changed = true;
  25365. }
  25366. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25367. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25368. changed = true;
  25369. }
  25370. if (defines["INSTANCES"] !== useInstances) {
  25371. defines["INSTANCES"] = useInstances;
  25372. changed = true;
  25373. }
  25374. if (changed) {
  25375. defines.markAsUnprocessed();
  25376. }
  25377. };
  25378. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25379. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25380. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25381. return false;
  25382. }
  25383. defines._normals = defines._needNormals;
  25384. defines._uvs = defines._needUVs;
  25385. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25386. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25387. defines["TANGENT"] = true;
  25388. }
  25389. if (defines._needUVs) {
  25390. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25391. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25392. }
  25393. else {
  25394. defines["UV1"] = false;
  25395. defines["UV2"] = false;
  25396. }
  25397. if (useVertexColor) {
  25398. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25399. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25400. }
  25401. if (useBones) {
  25402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25403. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25404. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25405. }
  25406. else {
  25407. defines["NUM_BONE_INFLUENCERS"] = 0;
  25408. defines["BonesPerMesh"] = 0;
  25409. }
  25410. }
  25411. if (useMorphTargets) {
  25412. if (mesh.morphTargetManager) {
  25413. var manager = mesh.morphTargetManager;
  25414. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25415. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25416. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25417. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25418. }
  25419. else {
  25420. defines["MORPHTARGETS_TANGENT"] = false;
  25421. defines["MORPHTARGETS_NORMAL"] = false;
  25422. defines["MORPHTARGETS"] = false;
  25423. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25424. }
  25425. }
  25426. return true;
  25427. };
  25428. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25429. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25430. if (disableLighting === void 0) { disableLighting = false; }
  25431. if (!defines._areLightsDirty) {
  25432. return defines._needNormals;
  25433. }
  25434. var lightIndex = 0;
  25435. var needNormals = false;
  25436. var needRebuild = false;
  25437. var lightmapMode = false;
  25438. var shadowEnabled = false;
  25439. var specularEnabled = false;
  25440. if (scene.lightsEnabled && !disableLighting) {
  25441. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25442. var light = _a[_i];
  25443. needNormals = true;
  25444. if (defines["LIGHT" + lightIndex] === undefined) {
  25445. needRebuild = true;
  25446. }
  25447. defines["LIGHT" + lightIndex] = true;
  25448. defines["SPOTLIGHT" + lightIndex] = false;
  25449. defines["HEMILIGHT" + lightIndex] = false;
  25450. defines["POINTLIGHT" + lightIndex] = false;
  25451. defines["DIRLIGHT" + lightIndex] = false;
  25452. var type;
  25453. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25454. type = "SPOTLIGHT" + lightIndex;
  25455. }
  25456. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25457. type = "HEMILIGHT" + lightIndex;
  25458. }
  25459. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25460. type = "POINTLIGHT" + lightIndex;
  25461. }
  25462. else {
  25463. type = "DIRLIGHT" + lightIndex;
  25464. }
  25465. defines[type] = true;
  25466. // Specular
  25467. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25468. specularEnabled = true;
  25469. }
  25470. // Shadows
  25471. defines["SHADOW" + lightIndex] = false;
  25472. defines["SHADOWPCF" + lightIndex] = false;
  25473. defines["SHADOWESM" + lightIndex] = false;
  25474. defines["SHADOWCUBE" + lightIndex] = false;
  25475. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25476. var shadowGenerator = light.getShadowGenerator();
  25477. if (shadowGenerator) {
  25478. shadowEnabled = true;
  25479. shadowGenerator.prepareDefines(defines, lightIndex);
  25480. }
  25481. }
  25482. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25483. lightmapMode = true;
  25484. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25485. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25486. }
  25487. else {
  25488. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25489. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25490. }
  25491. lightIndex++;
  25492. if (lightIndex === maxSimultaneousLights)
  25493. break;
  25494. }
  25495. }
  25496. defines["SPECULARTERM"] = specularEnabled;
  25497. defines["SHADOWS"] = shadowEnabled;
  25498. // Resetting all other lights if any
  25499. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25500. if (defines["LIGHT" + index] !== undefined) {
  25501. defines["LIGHT" + index] = false;
  25502. defines["HEMILIGHT" + lightIndex] = false;
  25503. defines["POINTLIGHT" + lightIndex] = false;
  25504. defines["DIRLIGHT" + lightIndex] = false;
  25505. defines["SPOTLIGHT" + lightIndex] = false;
  25506. defines["SHADOW" + lightIndex] = false;
  25507. }
  25508. }
  25509. var caps = scene.getEngine().getCaps();
  25510. if (defines["SHADOWFLOAT"] === undefined) {
  25511. needRebuild = true;
  25512. }
  25513. defines["SHADOWFLOAT"] = shadowEnabled &&
  25514. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25515. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25516. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25517. if (needRebuild) {
  25518. defines.rebuild();
  25519. }
  25520. return needNormals;
  25521. };
  25522. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25523. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25524. var uniformsList, uniformBuffersList, samplersList, defines;
  25525. if (uniformsListOrOptions.uniformsNames) {
  25526. var options = uniformsListOrOptions;
  25527. uniformsList = options.uniformsNames;
  25528. uniformBuffersList = options.uniformBuffersNames;
  25529. samplersList = options.samplers;
  25530. defines = options.defines;
  25531. maxSimultaneousLights = options.maxSimultaneousLights;
  25532. }
  25533. else {
  25534. uniformsList = uniformsListOrOptions;
  25535. }
  25536. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25537. if (!defines["LIGHT" + lightIndex]) {
  25538. break;
  25539. }
  25540. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25541. if (uniformBuffersList) {
  25542. uniformBuffersList.push("Light" + lightIndex);
  25543. }
  25544. samplersList.push("shadowSampler" + lightIndex);
  25545. }
  25546. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25547. uniformsList.push("morphTargetInfluences");
  25548. }
  25549. };
  25550. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25551. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25552. if (!defines["SHADOWS"]) {
  25553. return;
  25554. }
  25555. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25556. if (!defines["LIGHT" + lightIndex]) {
  25557. break;
  25558. }
  25559. if (lightIndex > 0) {
  25560. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25561. }
  25562. if (defines["SHADOW" + lightIndex]) {
  25563. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25564. }
  25565. if (defines["SHADOWPCF" + lightIndex]) {
  25566. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25567. }
  25568. if (defines["SHADOWESM" + lightIndex]) {
  25569. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25570. }
  25571. }
  25572. };
  25573. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25574. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25575. if (influencers > 0) {
  25576. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25577. var manager = mesh.morphTargetManager;
  25578. var normal = manager.supportsNormals && defines["NORMAL"];
  25579. var tangent = manager.supportsTangents && defines["TANGENT"];
  25580. for (var index = 0; index < influencers; index++) {
  25581. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25582. if (normal) {
  25583. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25584. }
  25585. if (tangent) {
  25586. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25587. }
  25588. if (attribs.length > maxAttributesCount) {
  25589. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25590. }
  25591. }
  25592. }
  25593. };
  25594. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25595. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25596. fallbacks.addCPUSkinningFallback(0, mesh);
  25597. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25598. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25599. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25600. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25601. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25602. }
  25603. }
  25604. };
  25605. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25606. if (defines["INSTANCES"]) {
  25607. attribs.push("world0");
  25608. attribs.push("world1");
  25609. attribs.push("world2");
  25610. attribs.push("world3");
  25611. }
  25612. };
  25613. // Bindings
  25614. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25615. if (light.shadowEnabled && mesh.receiveShadows) {
  25616. var shadowGenerator = light.getShadowGenerator();
  25617. if (shadowGenerator) {
  25618. shadowGenerator.bindShadowLight(lightIndex, effect);
  25619. }
  25620. }
  25621. };
  25622. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25623. light.transferToEffect(effect, lightIndex + "");
  25624. };
  25625. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25626. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25627. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25628. var lightIndex = 0;
  25629. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25630. var light = _a[_i];
  25631. var scaledIntensity = light.getScaledIntensity();
  25632. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25633. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25634. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25635. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25636. if (defines["SPECULARTERM"]) {
  25637. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25638. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25639. }
  25640. // Shadows
  25641. if (scene.shadowsEnabled) {
  25642. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25643. }
  25644. light._uniformBuffer.update();
  25645. lightIndex++;
  25646. if (lightIndex === maxSimultaneousLights)
  25647. break;
  25648. }
  25649. };
  25650. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25651. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25652. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25653. effect.setColor3("vFogColor", scene.fogColor);
  25654. }
  25655. };
  25656. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25657. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25658. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25659. if (matrices) {
  25660. effect.setMatrices("mBones", matrices);
  25661. }
  25662. }
  25663. };
  25664. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25665. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25666. return;
  25667. }
  25668. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25669. };
  25670. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25671. if (defines["LOGARITHMICDEPTH"]) {
  25672. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25673. }
  25674. };
  25675. MaterialHelper.BindClipPlane = function (effect, scene) {
  25676. if (scene.clipPlane) {
  25677. var clipPlane = scene.clipPlane;
  25678. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25679. }
  25680. };
  25681. return MaterialHelper;
  25682. }());
  25683. BABYLON.MaterialHelper = MaterialHelper;
  25684. })(BABYLON || (BABYLON = {}));
  25685. //# sourceMappingURL=babylon.materialHelper.js.map
  25686. var BABYLON;
  25687. (function (BABYLON) {
  25688. var MaterialDefines = (function () {
  25689. function MaterialDefines() {
  25690. this._isDirty = true;
  25691. this._areLightsDirty = true;
  25692. this._areAttributesDirty = true;
  25693. this._areTexturesDirty = true;
  25694. this._areFresnelDirty = true;
  25695. this._areMiscDirty = true;
  25696. this._areImageProcessingDirty = true;
  25697. this._normals = false;
  25698. this._uvs = false;
  25699. this._needNormals = false;
  25700. this._needUVs = false;
  25701. }
  25702. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25703. get: function () {
  25704. return this._isDirty;
  25705. },
  25706. enumerable: true,
  25707. configurable: true
  25708. });
  25709. MaterialDefines.prototype.markAsProcessed = function () {
  25710. this._isDirty = false;
  25711. this._areAttributesDirty = false;
  25712. this._areTexturesDirty = false;
  25713. this._areFresnelDirty = false;
  25714. this._areLightsDirty = false;
  25715. this._areMiscDirty = false;
  25716. this._areImageProcessingDirty = false;
  25717. };
  25718. MaterialDefines.prototype.markAsUnprocessed = function () {
  25719. this._isDirty = true;
  25720. };
  25721. MaterialDefines.prototype.markAllAsDirty = function () {
  25722. this._areTexturesDirty = true;
  25723. this._areAttributesDirty = true;
  25724. this._areLightsDirty = true;
  25725. this._areFresnelDirty = true;
  25726. this._areMiscDirty = true;
  25727. this._areImageProcessingDirty = true;
  25728. this._isDirty = true;
  25729. };
  25730. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25731. this._areImageProcessingDirty = true;
  25732. this._isDirty = true;
  25733. };
  25734. MaterialDefines.prototype.markAsLightDirty = function () {
  25735. this._areLightsDirty = true;
  25736. this._isDirty = true;
  25737. };
  25738. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25739. this._areAttributesDirty = true;
  25740. this._isDirty = true;
  25741. };
  25742. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25743. this._areTexturesDirty = true;
  25744. this._isDirty = true;
  25745. };
  25746. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25747. this._areFresnelDirty = true;
  25748. this._isDirty = true;
  25749. };
  25750. MaterialDefines.prototype.markAsMiscDirty = function () {
  25751. this._areMiscDirty = true;
  25752. this._isDirty = true;
  25753. };
  25754. MaterialDefines.prototype.rebuild = function () {
  25755. if (this._keys) {
  25756. delete this._keys;
  25757. }
  25758. this._keys = [];
  25759. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25760. var key = _a[_i];
  25761. if (key[0] === "_") {
  25762. continue;
  25763. }
  25764. this._keys.push(key);
  25765. }
  25766. };
  25767. MaterialDefines.prototype.isEqual = function (other) {
  25768. if (this._keys.length !== other._keys.length) {
  25769. return false;
  25770. }
  25771. for (var index = 0; index < this._keys.length; index++) {
  25772. var prop = this._keys[index];
  25773. if (this[prop] !== other[prop]) {
  25774. return false;
  25775. }
  25776. }
  25777. return true;
  25778. };
  25779. MaterialDefines.prototype.cloneTo = function (other) {
  25780. if (this._keys.length !== other._keys.length) {
  25781. other._keys = this._keys.slice(0);
  25782. }
  25783. for (var index = 0; index < this._keys.length; index++) {
  25784. var prop = this._keys[index];
  25785. other[prop] = this[prop];
  25786. }
  25787. };
  25788. MaterialDefines.prototype.reset = function () {
  25789. for (var index = 0; index < this._keys.length; index++) {
  25790. var prop = this._keys[index];
  25791. if (typeof (this[prop]) === "number") {
  25792. this[prop] = 0;
  25793. }
  25794. else {
  25795. this[prop] = false;
  25796. }
  25797. }
  25798. };
  25799. MaterialDefines.prototype.toString = function () {
  25800. var result = "";
  25801. for (var index = 0; index < this._keys.length; index++) {
  25802. var prop = this._keys[index];
  25803. var value = this[prop];
  25804. if (typeof (value) === "number") {
  25805. result += "#define " + prop + " " + this[prop] + "\n";
  25806. }
  25807. else if (value) {
  25808. result += "#define " + prop + "\n";
  25809. }
  25810. }
  25811. return result;
  25812. };
  25813. return MaterialDefines;
  25814. }());
  25815. BABYLON.MaterialDefines = MaterialDefines;
  25816. var Material = (function () {
  25817. function Material(name, scene, doNotAdd) {
  25818. this.checkReadyOnEveryCall = false;
  25819. this.checkReadyOnlyOnce = false;
  25820. this.state = "";
  25821. this.alpha = 1.0;
  25822. this._backFaceCulling = true;
  25823. this.doNotSerialize = false;
  25824. this.storeEffectOnSubMeshes = false;
  25825. /**
  25826. * An event triggered when the material is disposed.
  25827. * @type {BABYLON.Observable}
  25828. */
  25829. this.onDisposeObservable = new BABYLON.Observable();
  25830. /**
  25831. * An event triggered when the material is bound.
  25832. * @type {BABYLON.Observable}
  25833. */
  25834. this.onBindObservable = new BABYLON.Observable();
  25835. /**
  25836. * An event triggered when the material is unbound.
  25837. * @type {BABYLON.Observable}
  25838. */
  25839. this.onUnBindObservable = new BABYLON.Observable();
  25840. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25841. this._needDepthPrePass = false;
  25842. this.disableDepthWrite = false;
  25843. this.forceDepthWrite = false;
  25844. this.separateCullingPass = false;
  25845. this._fogEnabled = true;
  25846. this.pointSize = 1.0;
  25847. this.zOffset = 0;
  25848. this._wasPreviouslyReady = false;
  25849. this._fillMode = Material.TriangleFillMode;
  25850. this.name = name;
  25851. this.id = name || BABYLON.Tools.RandomId();
  25852. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25853. if (this._scene.useRightHandedSystem) {
  25854. this.sideOrientation = Material.ClockWiseSideOrientation;
  25855. }
  25856. else {
  25857. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25858. }
  25859. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25860. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25861. if (!doNotAdd) {
  25862. this._scene.materials.push(this);
  25863. }
  25864. }
  25865. Object.defineProperty(Material, "TriangleFillMode", {
  25866. get: function () {
  25867. return Material._TriangleFillMode;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. Object.defineProperty(Material, "WireFrameFillMode", {
  25873. get: function () {
  25874. return Material._WireFrameFillMode;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(Material, "PointFillMode", {
  25880. get: function () {
  25881. return Material._PointFillMode;
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25887. get: function () {
  25888. return Material._ClockWiseSideOrientation;
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25894. get: function () {
  25895. return Material._CounterClockWiseSideOrientation;
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. Object.defineProperty(Material, "TextureDirtyFlag", {
  25901. get: function () {
  25902. return Material._TextureDirtyFlag;
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. Object.defineProperty(Material, "LightDirtyFlag", {
  25908. get: function () {
  25909. return Material._LightDirtyFlag;
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25915. get: function () {
  25916. return Material._FresnelDirtyFlag;
  25917. },
  25918. enumerable: true,
  25919. configurable: true
  25920. });
  25921. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25922. get: function () {
  25923. return Material._AttributesDirtyFlag;
  25924. },
  25925. enumerable: true,
  25926. configurable: true
  25927. });
  25928. Object.defineProperty(Material, "MiscDirtyFlag", {
  25929. get: function () {
  25930. return Material._MiscDirtyFlag;
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25936. get: function () {
  25937. return this._backFaceCulling;
  25938. },
  25939. set: function (value) {
  25940. if (this._backFaceCulling === value) {
  25941. return;
  25942. }
  25943. this._backFaceCulling = value;
  25944. this.markAsDirty(Material.TextureDirtyFlag);
  25945. },
  25946. enumerable: true,
  25947. configurable: true
  25948. });
  25949. Object.defineProperty(Material.prototype, "onDispose", {
  25950. set: function (callback) {
  25951. if (this._onDisposeObserver) {
  25952. this.onDisposeObservable.remove(this._onDisposeObserver);
  25953. }
  25954. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25955. },
  25956. enumerable: true,
  25957. configurable: true
  25958. });
  25959. Object.defineProperty(Material.prototype, "onBind", {
  25960. set: function (callback) {
  25961. if (this._onBindObserver) {
  25962. this.onBindObservable.remove(this._onBindObserver);
  25963. }
  25964. this._onBindObserver = this.onBindObservable.add(callback);
  25965. },
  25966. enumerable: true,
  25967. configurable: true
  25968. });
  25969. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  25970. get: function () {
  25971. return this._needDepthPrePass;
  25972. },
  25973. set: function (value) {
  25974. if (this._needDepthPrePass === value) {
  25975. return;
  25976. }
  25977. this._needDepthPrePass = value;
  25978. if (this._needDepthPrePass) {
  25979. this.checkReadyOnEveryCall = true;
  25980. }
  25981. },
  25982. enumerable: true,
  25983. configurable: true
  25984. });
  25985. Object.defineProperty(Material.prototype, "fogEnabled", {
  25986. get: function () {
  25987. return this._fogEnabled;
  25988. },
  25989. set: function (value) {
  25990. if (this._fogEnabled === value) {
  25991. return;
  25992. }
  25993. this._fogEnabled = value;
  25994. this.markAsDirty(Material.MiscDirtyFlag);
  25995. },
  25996. enumerable: true,
  25997. configurable: true
  25998. });
  25999. Object.defineProperty(Material.prototype, "wireframe", {
  26000. get: function () {
  26001. return this._fillMode === Material.WireFrameFillMode;
  26002. },
  26003. set: function (value) {
  26004. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. Object.defineProperty(Material.prototype, "pointsCloud", {
  26010. get: function () {
  26011. return this._fillMode === Material.PointFillMode;
  26012. },
  26013. set: function (value) {
  26014. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26015. },
  26016. enumerable: true,
  26017. configurable: true
  26018. });
  26019. Object.defineProperty(Material.prototype, "fillMode", {
  26020. get: function () {
  26021. return this._fillMode;
  26022. },
  26023. set: function (value) {
  26024. if (this._fillMode === value) {
  26025. return;
  26026. }
  26027. this._fillMode = value;
  26028. this.markAsDirty(Material.MiscDirtyFlag);
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. /**
  26034. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26035. * subclasses should override adding information pertainent to themselves
  26036. */
  26037. Material.prototype.toString = function (fullDetails) {
  26038. var ret = "Name: " + this.name;
  26039. if (fullDetails) {
  26040. }
  26041. return ret;
  26042. };
  26043. /**
  26044. * Child classes can use it to update shaders
  26045. */
  26046. Material.prototype.getClassName = function () {
  26047. return "Material";
  26048. };
  26049. Object.defineProperty(Material.prototype, "isFrozen", {
  26050. get: function () {
  26051. return this.checkReadyOnlyOnce;
  26052. },
  26053. enumerable: true,
  26054. configurable: true
  26055. });
  26056. Material.prototype.freeze = function () {
  26057. this.checkReadyOnlyOnce = true;
  26058. };
  26059. Material.prototype.unfreeze = function () {
  26060. this.checkReadyOnlyOnce = false;
  26061. };
  26062. Material.prototype.isReady = function (mesh, useInstances) {
  26063. return true;
  26064. };
  26065. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26066. return false;
  26067. };
  26068. Material.prototype.getEffect = function () {
  26069. return this._effect;
  26070. };
  26071. Material.prototype.getScene = function () {
  26072. return this._scene;
  26073. };
  26074. Material.prototype.needAlphaBlending = function () {
  26075. return (this.alpha < 1.0);
  26076. };
  26077. Material.prototype.needAlphaTesting = function () {
  26078. return false;
  26079. };
  26080. Material.prototype.getAlphaTestTexture = function () {
  26081. return null;
  26082. };
  26083. Material.prototype.markDirty = function () {
  26084. this._wasPreviouslyReady = false;
  26085. };
  26086. Material.prototype._preBind = function (effect, overrideOrientation) {
  26087. var engine = this._scene.getEngine();
  26088. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  26089. var reverse = orientation === Material.ClockWiseSideOrientation;
  26090. engine.enableEffect(effect ? effect : this._effect);
  26091. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26092. return reverse;
  26093. };
  26094. Material.prototype.bind = function (world, mesh) {
  26095. };
  26096. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26097. };
  26098. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26099. };
  26100. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  26101. sceneUbo.bindToEffect(effect, "Scene");
  26102. };
  26103. Material.prototype.bindView = function (effect) {
  26104. if (!this._useUBO) {
  26105. effect.setMatrix("view", this.getScene().getViewMatrix());
  26106. }
  26107. else {
  26108. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26109. }
  26110. };
  26111. Material.prototype.bindViewProjection = function (effect) {
  26112. if (!this._useUBO) {
  26113. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26114. }
  26115. else {
  26116. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26117. }
  26118. };
  26119. Material.prototype._afterBind = function (mesh) {
  26120. this._scene._cachedMaterial = this;
  26121. if (mesh) {
  26122. this._scene._cachedVisibility = mesh.visibility;
  26123. }
  26124. else {
  26125. this._scene._cachedVisibility = 1;
  26126. }
  26127. this.onBindObservable.notifyObservers(mesh);
  26128. if (this.disableDepthWrite) {
  26129. var engine = this._scene.getEngine();
  26130. this._cachedDepthWriteState = engine.getDepthWrite();
  26131. engine.setDepthWrite(false);
  26132. }
  26133. };
  26134. Material.prototype.unbind = function () {
  26135. this.onUnBindObservable.notifyObservers(this);
  26136. if (this.disableDepthWrite) {
  26137. var engine = this._scene.getEngine();
  26138. engine.setDepthWrite(this._cachedDepthWriteState);
  26139. }
  26140. };
  26141. Material.prototype.getActiveTextures = function () {
  26142. return [];
  26143. };
  26144. Material.prototype.hasTexture = function (texture) {
  26145. return false;
  26146. };
  26147. Material.prototype.clone = function (name) {
  26148. return null;
  26149. };
  26150. Material.prototype.getBindedMeshes = function () {
  26151. var result = new Array();
  26152. for (var index = 0; index < this._scene.meshes.length; index++) {
  26153. var mesh = this._scene.meshes[index];
  26154. if (mesh.material === this) {
  26155. result.push(mesh);
  26156. }
  26157. }
  26158. return result;
  26159. };
  26160. /**
  26161. * Force shader compilation including textures ready check
  26162. */
  26163. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26164. var _this = this;
  26165. var subMesh = new BABYLON.BaseSubMesh();
  26166. var scene = this.getScene();
  26167. var engine = scene.getEngine();
  26168. var checkReady = function () {
  26169. if (!_this._scene || !_this._scene.getEngine()) {
  26170. return;
  26171. }
  26172. if (subMesh._materialDefines) {
  26173. subMesh._materialDefines._renderId = -1;
  26174. }
  26175. var alphaTestState = engine.getAlphaTesting();
  26176. var clipPlaneState = scene.clipPlane;
  26177. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26178. if (options && options.clipPlane) {
  26179. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26180. }
  26181. if (_this.storeEffectOnSubMeshes) {
  26182. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26183. if (onCompiled) {
  26184. onCompiled(_this);
  26185. }
  26186. }
  26187. else {
  26188. setTimeout(checkReady, 16);
  26189. }
  26190. }
  26191. else {
  26192. if (_this.isReady(mesh)) {
  26193. if (onCompiled) {
  26194. onCompiled(_this);
  26195. }
  26196. }
  26197. else {
  26198. setTimeout(checkReady, 16);
  26199. }
  26200. }
  26201. engine.setAlphaTesting(alphaTestState);
  26202. if (options && options.clipPlane) {
  26203. scene.clipPlane = clipPlaneState;
  26204. }
  26205. };
  26206. checkReady();
  26207. };
  26208. Material.prototype.markAsDirty = function (flag) {
  26209. if (flag & Material.TextureDirtyFlag) {
  26210. this._markAllSubMeshesAsTexturesDirty();
  26211. }
  26212. if (flag & Material.LightDirtyFlag) {
  26213. this._markAllSubMeshesAsLightsDirty();
  26214. }
  26215. if (flag & Material.FresnelDirtyFlag) {
  26216. this._markAllSubMeshesAsFresnelDirty();
  26217. }
  26218. if (flag & Material.AttributesDirtyFlag) {
  26219. this._markAllSubMeshesAsAttributesDirty();
  26220. }
  26221. if (flag & Material.MiscDirtyFlag) {
  26222. this._markAllSubMeshesAsMiscDirty();
  26223. }
  26224. this.getScene().resetCachedMaterial();
  26225. };
  26226. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26227. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26228. var mesh = _a[_i];
  26229. if (!mesh.subMeshes) {
  26230. continue;
  26231. }
  26232. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26233. var subMesh = _c[_b];
  26234. if (subMesh.getMaterial() !== this) {
  26235. continue;
  26236. }
  26237. if (!subMesh._materialDefines) {
  26238. continue;
  26239. }
  26240. func(subMesh._materialDefines);
  26241. }
  26242. }
  26243. };
  26244. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26245. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26246. };
  26247. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26248. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26249. };
  26250. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26251. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26252. };
  26253. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26254. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26255. };
  26256. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26257. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26258. };
  26259. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26260. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26261. };
  26262. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26263. // Animations
  26264. this.getScene().stopAnimation(this);
  26265. // Remove from scene
  26266. var index = this._scene.materials.indexOf(this);
  26267. if (index >= 0) {
  26268. this._scene.materials.splice(index, 1);
  26269. }
  26270. // Remove from meshes
  26271. for (index = 0; index < this._scene.meshes.length; index++) {
  26272. var mesh = this._scene.meshes[index];
  26273. if (mesh.material === this) {
  26274. mesh.material = null;
  26275. if (mesh.geometry) {
  26276. var geometry = mesh.geometry;
  26277. if (this.storeEffectOnSubMeshes) {
  26278. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26279. var subMesh = _a[_i];
  26280. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26281. }
  26282. }
  26283. else {
  26284. geometry._releaseVertexArrayObject(this._effect);
  26285. }
  26286. }
  26287. }
  26288. }
  26289. this._uniformBuffer.dispose();
  26290. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26291. if (forceDisposeEffect && this._effect) {
  26292. if (this.storeEffectOnSubMeshes) {
  26293. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26294. var subMesh = _c[_b];
  26295. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26296. }
  26297. }
  26298. else {
  26299. this._scene.getEngine()._releaseEffect(this._effect);
  26300. }
  26301. this._effect = null;
  26302. }
  26303. // Callback
  26304. this.onDisposeObservable.notifyObservers(this);
  26305. this.onDisposeObservable.clear();
  26306. this.onBindObservable.clear();
  26307. this.onUnBindObservable.clear();
  26308. };
  26309. Material.prototype.serialize = function () {
  26310. return BABYLON.SerializationHelper.Serialize(this);
  26311. };
  26312. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26313. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26314. multiMaterial.id = parsedMultiMaterial.id;
  26315. if (BABYLON.Tags) {
  26316. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26317. }
  26318. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26319. var subMatId = parsedMultiMaterial.materials[matIndex];
  26320. if (subMatId) {
  26321. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26322. }
  26323. else {
  26324. multiMaterial.subMaterials.push(null);
  26325. }
  26326. }
  26327. return multiMaterial;
  26328. };
  26329. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26330. if (!parsedMaterial.customType) {
  26331. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26332. }
  26333. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26334. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26335. if (!BABYLON.LegacyPBRMaterial) {
  26336. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26337. return;
  26338. }
  26339. }
  26340. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26341. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26342. ;
  26343. };
  26344. Material._TriangleFillMode = 0;
  26345. Material._WireFrameFillMode = 1;
  26346. Material._PointFillMode = 2;
  26347. Material._ClockWiseSideOrientation = 0;
  26348. Material._CounterClockWiseSideOrientation = 1;
  26349. Material._TextureDirtyFlag = 1;
  26350. Material._LightDirtyFlag = 2;
  26351. Material._FresnelDirtyFlag = 4;
  26352. Material._AttributesDirtyFlag = 8;
  26353. Material._MiscDirtyFlag = 16;
  26354. __decorate([
  26355. BABYLON.serialize()
  26356. ], Material.prototype, "id", void 0);
  26357. __decorate([
  26358. BABYLON.serialize()
  26359. ], Material.prototype, "name", void 0);
  26360. __decorate([
  26361. BABYLON.serialize()
  26362. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26363. __decorate([
  26364. BABYLON.serialize()
  26365. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26366. __decorate([
  26367. BABYLON.serialize()
  26368. ], Material.prototype, "state", void 0);
  26369. __decorate([
  26370. BABYLON.serialize()
  26371. ], Material.prototype, "alpha", void 0);
  26372. __decorate([
  26373. BABYLON.serialize("backFaceCulling")
  26374. ], Material.prototype, "_backFaceCulling", void 0);
  26375. __decorate([
  26376. BABYLON.serialize()
  26377. ], Material.prototype, "sideOrientation", void 0);
  26378. __decorate([
  26379. BABYLON.serialize()
  26380. ], Material.prototype, "alphaMode", void 0);
  26381. __decorate([
  26382. BABYLON.serialize()
  26383. ], Material.prototype, "_needDepthPrePass", void 0);
  26384. __decorate([
  26385. BABYLON.serialize()
  26386. ], Material.prototype, "disableDepthWrite", void 0);
  26387. __decorate([
  26388. BABYLON.serialize()
  26389. ], Material.prototype, "forceDepthWrite", void 0);
  26390. __decorate([
  26391. BABYLON.serialize()
  26392. ], Material.prototype, "separateCullingPass", void 0);
  26393. __decorate([
  26394. BABYLON.serialize("fogEnabled")
  26395. ], Material.prototype, "_fogEnabled", void 0);
  26396. __decorate([
  26397. BABYLON.serialize()
  26398. ], Material.prototype, "pointSize", void 0);
  26399. __decorate([
  26400. BABYLON.serialize()
  26401. ], Material.prototype, "zOffset", void 0);
  26402. __decorate([
  26403. BABYLON.serialize()
  26404. ], Material.prototype, "wireframe", null);
  26405. __decorate([
  26406. BABYLON.serialize()
  26407. ], Material.prototype, "pointsCloud", null);
  26408. __decorate([
  26409. BABYLON.serialize()
  26410. ], Material.prototype, "fillMode", null);
  26411. return Material;
  26412. }());
  26413. BABYLON.Material = Material;
  26414. })(BABYLON || (BABYLON = {}));
  26415. //# sourceMappingURL=babylon.material.js.map
  26416. var BABYLON;
  26417. (function (BABYLON) {
  26418. var UniformBuffer = (function () {
  26419. /**
  26420. * Uniform buffer objects.
  26421. *
  26422. * Handles blocks of uniform on the GPU.
  26423. *
  26424. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26425. *
  26426. * For more information, please refer to :
  26427. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26428. */
  26429. function UniformBuffer(engine, data, dynamic) {
  26430. this._engine = engine;
  26431. this._noUBO = !engine.supportsUniformBuffers;
  26432. this._dynamic = dynamic;
  26433. this._data = data || [];
  26434. this._uniformLocations = {};
  26435. this._uniformSizes = {};
  26436. this._uniformLocationPointer = 0;
  26437. this._needSync = false;
  26438. if (this._noUBO) {
  26439. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26440. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26441. this.updateFloat = this._updateFloatForEffect;
  26442. this.updateFloat2 = this._updateFloat2ForEffect;
  26443. this.updateFloat3 = this._updateFloat3ForEffect;
  26444. this.updateFloat4 = this._updateFloat4ForEffect;
  26445. this.updateMatrix = this._updateMatrixForEffect;
  26446. this.updateVector3 = this._updateVector3ForEffect;
  26447. this.updateVector4 = this._updateVector4ForEffect;
  26448. this.updateColor3 = this._updateColor3ForEffect;
  26449. this.updateColor4 = this._updateColor4ForEffect;
  26450. }
  26451. else {
  26452. this._engine._uniformBuffers.push(this);
  26453. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26454. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26455. this.updateFloat = this._updateFloatForUniform;
  26456. this.updateFloat2 = this._updateFloat2ForUniform;
  26457. this.updateFloat3 = this._updateFloat3ForUniform;
  26458. this.updateFloat4 = this._updateFloat4ForUniform;
  26459. this.updateMatrix = this._updateMatrixForUniform;
  26460. this.updateVector3 = this._updateVector3ForUniform;
  26461. this.updateVector4 = this._updateVector4ForUniform;
  26462. this.updateColor3 = this._updateColor3ForUniform;
  26463. this.updateColor4 = this._updateColor4ForUniform;
  26464. }
  26465. }
  26466. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26467. // Properties
  26468. /**
  26469. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26470. * or just falling back on setUniformXXX calls.
  26471. */
  26472. get: function () {
  26473. return !this._noUBO;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26479. /**
  26480. * Indicates if the WebGL underlying uniform buffer is in sync
  26481. * with the javascript cache data.
  26482. */
  26483. get: function () {
  26484. return !this._needSync;
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. /**
  26490. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26491. * Also, a dynamic UniformBuffer will disable cache verification and always
  26492. * update the underlying WebGL uniform buffer to the GPU.
  26493. */
  26494. UniformBuffer.prototype.isDynamic = function () {
  26495. return this._dynamic;
  26496. };
  26497. /**
  26498. * The data cache on JS side.
  26499. */
  26500. UniformBuffer.prototype.getData = function () {
  26501. return this._bufferData;
  26502. };
  26503. /**
  26504. * The underlying WebGL Uniform buffer.
  26505. */
  26506. UniformBuffer.prototype.getBuffer = function () {
  26507. return this._buffer;
  26508. };
  26509. /**
  26510. * std140 layout specifies how to align data within an UBO structure.
  26511. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26512. * for specs.
  26513. */
  26514. UniformBuffer.prototype._fillAlignment = function (size) {
  26515. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26516. // and 4x4 matrices
  26517. // TODO : change if other types are used
  26518. var alignment;
  26519. if (size <= 2) {
  26520. alignment = size;
  26521. }
  26522. else {
  26523. alignment = 4;
  26524. }
  26525. if ((this._uniformLocationPointer % alignment) !== 0) {
  26526. var oldPointer = this._uniformLocationPointer;
  26527. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26528. var diff = this._uniformLocationPointer - oldPointer;
  26529. for (var i = 0; i < diff; i++) {
  26530. this._data.push(0);
  26531. }
  26532. }
  26533. };
  26534. /**
  26535. * Adds an uniform in the buffer.
  26536. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26537. * for the layout to be correct !
  26538. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26539. * @param {number|number[]} size Data size, or data directly.
  26540. */
  26541. UniformBuffer.prototype.addUniform = function (name, size) {
  26542. if (this._noUBO) {
  26543. return;
  26544. }
  26545. if (this._uniformLocations[name] !== undefined) {
  26546. // Already existing uniform
  26547. return;
  26548. }
  26549. // This function must be called in the order of the shader layout !
  26550. // size can be the size of the uniform, or data directly
  26551. var data;
  26552. if (size instanceof Array) {
  26553. data = size;
  26554. size = data.length;
  26555. }
  26556. else {
  26557. size = size;
  26558. data = [];
  26559. // Fill with zeros
  26560. for (var i = 0; i < size; i++) {
  26561. data.push(0);
  26562. }
  26563. }
  26564. this._fillAlignment(size);
  26565. this._uniformSizes[name] = size;
  26566. this._uniformLocations[name] = this._uniformLocationPointer;
  26567. this._uniformLocationPointer += size;
  26568. for (var i = 0; i < size; i++) {
  26569. this._data.push(data[i]);
  26570. }
  26571. this._needSync = true;
  26572. };
  26573. /**
  26574. * Wrapper for addUniform.
  26575. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26576. * @param {Matrix} mat A 4x4 matrix.
  26577. */
  26578. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26579. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26580. };
  26581. /**
  26582. * Wrapper for addUniform.
  26583. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26584. * @param {number} x
  26585. * @param {number} y
  26586. */
  26587. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26588. var temp = [x, y];
  26589. this.addUniform(name, temp);
  26590. };
  26591. /**
  26592. * Wrapper for addUniform.
  26593. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26594. * @param {number} x
  26595. * @param {number} y
  26596. * @param {number} z
  26597. */
  26598. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26599. var temp = [x, y, z];
  26600. this.addUniform(name, temp);
  26601. };
  26602. /**
  26603. * Wrapper for addUniform.
  26604. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26605. * @param {Color3} color
  26606. */
  26607. UniformBuffer.prototype.addColor3 = function (name, color) {
  26608. var temp = new Array();
  26609. color.toArray(temp);
  26610. this.addUniform(name, temp);
  26611. };
  26612. /**
  26613. * Wrapper for addUniform.
  26614. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26615. * @param {Color3} color
  26616. * @param {number} alpha
  26617. */
  26618. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26619. var temp = new Array();
  26620. color.toArray(temp);
  26621. temp.push(alpha);
  26622. this.addUniform(name, temp);
  26623. };
  26624. /**
  26625. * Wrapper for addUniform.
  26626. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26627. * @param {Vector3} vector
  26628. */
  26629. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26630. var temp = new Array();
  26631. vector.toArray(temp);
  26632. this.addUniform(name, temp);
  26633. };
  26634. /**
  26635. * Wrapper for addUniform.
  26636. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26637. */
  26638. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26639. this.addUniform(name, 12);
  26640. };
  26641. /**
  26642. * Wrapper for addUniform.
  26643. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26644. */
  26645. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26646. this.addUniform(name, 8);
  26647. };
  26648. /**
  26649. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26650. */
  26651. UniformBuffer.prototype.create = function () {
  26652. if (this._noUBO) {
  26653. return;
  26654. }
  26655. if (this._buffer) {
  26656. return; // nothing to do
  26657. }
  26658. // See spec, alignment must be filled as a vec4
  26659. this._fillAlignment(4);
  26660. this._bufferData = new Float32Array(this._data);
  26661. this._rebuild();
  26662. this._needSync = true;
  26663. };
  26664. UniformBuffer.prototype._rebuild = function () {
  26665. if (this._noUBO) {
  26666. return;
  26667. }
  26668. if (this._dynamic) {
  26669. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26670. }
  26671. else {
  26672. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26673. }
  26674. };
  26675. /**
  26676. * Updates the WebGL Uniform Buffer on the GPU.
  26677. * If the `dynamic` flag is set to true, no cache comparison is done.
  26678. * Otherwise, the buffer will be updated only if the cache differs.
  26679. */
  26680. UniformBuffer.prototype.update = function () {
  26681. if (!this._buffer) {
  26682. this.create();
  26683. return;
  26684. }
  26685. if (!this._dynamic && !this._needSync) {
  26686. return;
  26687. }
  26688. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26689. this._needSync = false;
  26690. };
  26691. /**
  26692. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26693. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26694. * @param {number[]|Float32Array} data Flattened data
  26695. * @param {number} size Size of the data.
  26696. */
  26697. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26698. var location = this._uniformLocations[uniformName];
  26699. if (location === undefined) {
  26700. if (this._buffer) {
  26701. // Cannot add an uniform if the buffer is already created
  26702. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26703. return;
  26704. }
  26705. this.addUniform(uniformName, size);
  26706. location = this._uniformLocations[uniformName];
  26707. }
  26708. if (!this._buffer) {
  26709. this.create();
  26710. }
  26711. if (!this._dynamic) {
  26712. // Cache for static uniform buffers
  26713. var changed = false;
  26714. for (var i = 0; i < size; i++) {
  26715. if (this._bufferData[location + i] !== data[i]) {
  26716. changed = true;
  26717. this._bufferData[location + i] = data[i];
  26718. }
  26719. }
  26720. this._needSync = this._needSync || changed;
  26721. }
  26722. else {
  26723. // No cache for dynamic
  26724. for (var i = 0; i < size; i++) {
  26725. this._bufferData[location + i] = data[i];
  26726. }
  26727. }
  26728. };
  26729. // Update methods
  26730. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26731. // To match std140, matrix must be realigned
  26732. for (var i = 0; i < 3; i++) {
  26733. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26734. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26735. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26736. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26737. }
  26738. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26739. };
  26740. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26741. this._currentEffect.setMatrix3x3(name, matrix);
  26742. };
  26743. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26744. this._currentEffect.setMatrix2x2(name, matrix);
  26745. };
  26746. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26747. // To match std140, matrix must be realigned
  26748. for (var i = 0; i < 2; i++) {
  26749. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26750. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26751. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26752. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26753. }
  26754. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26755. };
  26756. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26757. this._currentEffect.setFloat(name, x);
  26758. };
  26759. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26760. UniformBuffer._tempBuffer[0] = x;
  26761. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26762. };
  26763. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26764. if (suffix === void 0) { suffix = ""; }
  26765. this._currentEffect.setFloat2(name + suffix, x, y);
  26766. };
  26767. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26768. if (suffix === void 0) { suffix = ""; }
  26769. UniformBuffer._tempBuffer[0] = x;
  26770. UniformBuffer._tempBuffer[1] = y;
  26771. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26772. };
  26773. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26774. if (suffix === void 0) { suffix = ""; }
  26775. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26776. };
  26777. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26778. if (suffix === void 0) { suffix = ""; }
  26779. UniformBuffer._tempBuffer[0] = x;
  26780. UniformBuffer._tempBuffer[1] = y;
  26781. UniformBuffer._tempBuffer[2] = z;
  26782. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26783. };
  26784. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26785. if (suffix === void 0) { suffix = ""; }
  26786. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26787. };
  26788. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26789. if (suffix === void 0) { suffix = ""; }
  26790. UniformBuffer._tempBuffer[0] = x;
  26791. UniformBuffer._tempBuffer[1] = y;
  26792. UniformBuffer._tempBuffer[2] = z;
  26793. UniformBuffer._tempBuffer[3] = w;
  26794. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26795. };
  26796. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26797. this._currentEffect.setMatrix(name, mat);
  26798. };
  26799. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26800. this.updateUniform(name, mat.toArray(), 16);
  26801. };
  26802. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26803. this._currentEffect.setVector3(name, vector);
  26804. };
  26805. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26806. vector.toArray(UniformBuffer._tempBuffer);
  26807. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26808. };
  26809. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26810. this._currentEffect.setVector4(name, vector);
  26811. };
  26812. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26813. vector.toArray(UniformBuffer._tempBuffer);
  26814. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26815. };
  26816. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26817. if (suffix === void 0) { suffix = ""; }
  26818. this._currentEffect.setColor3(name + suffix, color);
  26819. };
  26820. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26821. if (suffix === void 0) { suffix = ""; }
  26822. color.toArray(UniformBuffer._tempBuffer);
  26823. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26824. };
  26825. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26826. if (suffix === void 0) { suffix = ""; }
  26827. this._currentEffect.setColor4(name + suffix, color, alpha);
  26828. };
  26829. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26830. if (suffix === void 0) { suffix = ""; }
  26831. color.toArray(UniformBuffer._tempBuffer);
  26832. UniformBuffer._tempBuffer[3] = alpha;
  26833. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26834. };
  26835. /**
  26836. * Sets a sampler uniform on the effect.
  26837. * @param {string} name Name of the sampler.
  26838. * @param {Texture} texture
  26839. */
  26840. UniformBuffer.prototype.setTexture = function (name, texture) {
  26841. this._currentEffect.setTexture(name, texture);
  26842. };
  26843. /**
  26844. * Directly updates the value of the uniform in the cache AND on the GPU.
  26845. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26846. * @param {number[]|Float32Array} data Flattened data
  26847. */
  26848. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26849. this.updateUniform(uniformName, data, data.length);
  26850. this.update();
  26851. };
  26852. /**
  26853. * Binds this uniform buffer to an effect.
  26854. * @param {Effect} effect
  26855. * @param {string} name Name of the uniform block in the shader.
  26856. */
  26857. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26858. this._currentEffect = effect;
  26859. if (this._noUBO) {
  26860. return;
  26861. }
  26862. effect.bindUniformBuffer(this._buffer, name);
  26863. };
  26864. /**
  26865. * Disposes the uniform buffer.
  26866. */
  26867. UniformBuffer.prototype.dispose = function () {
  26868. if (this._noUBO) {
  26869. return;
  26870. }
  26871. var index = this._engine._uniformBuffers.indexOf(this);
  26872. if (index !== -1) {
  26873. this._engine._uniformBuffers.splice(index, 1);
  26874. }
  26875. if (!this._buffer) {
  26876. return;
  26877. }
  26878. if (this._engine._releaseBuffer(this._buffer)) {
  26879. this._buffer = null;
  26880. }
  26881. };
  26882. // Pool for avoiding memory leaks
  26883. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26884. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26885. return UniformBuffer;
  26886. }());
  26887. BABYLON.UniformBuffer = UniformBuffer;
  26888. })(BABYLON || (BABYLON = {}));
  26889. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26890. var BABYLON;
  26891. (function (BABYLON) {
  26892. var PushMaterial = (function (_super) {
  26893. __extends(PushMaterial, _super);
  26894. function PushMaterial(name, scene) {
  26895. var _this = _super.call(this, name, scene) || this;
  26896. _this.storeEffectOnSubMeshes = true;
  26897. return _this;
  26898. }
  26899. PushMaterial.prototype.getEffect = function () {
  26900. return this._activeEffect;
  26901. };
  26902. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26903. if (!mesh) {
  26904. return false;
  26905. }
  26906. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26907. return true;
  26908. }
  26909. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26910. };
  26911. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26912. this._activeEffect.setMatrix("world", world);
  26913. };
  26914. PushMaterial.prototype.bind = function (world, mesh) {
  26915. if (!mesh) {
  26916. return;
  26917. }
  26918. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26919. };
  26920. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26921. _super.prototype._afterBind.call(this, mesh);
  26922. this.getScene()._cachedEffect = effect;
  26923. };
  26924. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26925. if (visibility === void 0) { visibility = 1; }
  26926. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26927. };
  26928. return PushMaterial;
  26929. }(BABYLON.Material));
  26930. BABYLON.PushMaterial = PushMaterial;
  26931. })(BABYLON || (BABYLON = {}));
  26932. //# sourceMappingURL=babylon.pushMaterial.js.map
  26933. var BABYLON;
  26934. (function (BABYLON) {
  26935. var VertexData = (function () {
  26936. function VertexData() {
  26937. }
  26938. VertexData.prototype.set = function (data, kind) {
  26939. switch (kind) {
  26940. case BABYLON.VertexBuffer.PositionKind:
  26941. this.positions = data;
  26942. break;
  26943. case BABYLON.VertexBuffer.NormalKind:
  26944. this.normals = data;
  26945. break;
  26946. case BABYLON.VertexBuffer.TangentKind:
  26947. this.tangents = data;
  26948. break;
  26949. case BABYLON.VertexBuffer.UVKind:
  26950. this.uvs = data;
  26951. break;
  26952. case BABYLON.VertexBuffer.UV2Kind:
  26953. this.uvs2 = data;
  26954. break;
  26955. case BABYLON.VertexBuffer.UV3Kind:
  26956. this.uvs3 = data;
  26957. break;
  26958. case BABYLON.VertexBuffer.UV4Kind:
  26959. this.uvs4 = data;
  26960. break;
  26961. case BABYLON.VertexBuffer.UV5Kind:
  26962. this.uvs5 = data;
  26963. break;
  26964. case BABYLON.VertexBuffer.UV6Kind:
  26965. this.uvs6 = data;
  26966. break;
  26967. case BABYLON.VertexBuffer.ColorKind:
  26968. this.colors = data;
  26969. break;
  26970. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26971. this.matricesIndices = data;
  26972. break;
  26973. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26974. this.matricesWeights = data;
  26975. break;
  26976. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26977. this.matricesIndicesExtra = data;
  26978. break;
  26979. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26980. this.matricesWeightsExtra = data;
  26981. break;
  26982. }
  26983. };
  26984. /**
  26985. * Associates the vertexData to the passed Mesh.
  26986. * Sets it as updatable or not (default `false`).
  26987. * Returns the VertexData.
  26988. */
  26989. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26990. this._applyTo(mesh, updatable);
  26991. return this;
  26992. };
  26993. /**
  26994. * Associates the vertexData to the passed Geometry.
  26995. * Sets it as updatable or not (default `false`).
  26996. * Returns the VertexData.
  26997. */
  26998. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26999. this._applyTo(geometry, updatable);
  27000. return this;
  27001. };
  27002. /**
  27003. * Updates the associated mesh.
  27004. * Returns the VertexData.
  27005. */
  27006. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27007. this._update(mesh);
  27008. return this;
  27009. };
  27010. /**
  27011. * Updates the associated geometry.
  27012. * Returns the VertexData.
  27013. */
  27014. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27015. this._update(geometry);
  27016. return this;
  27017. };
  27018. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27019. if (this.positions) {
  27020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27021. }
  27022. if (this.normals) {
  27023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27024. }
  27025. if (this.tangents) {
  27026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  27027. }
  27028. if (this.uvs) {
  27029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27030. }
  27031. if (this.uvs2) {
  27032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27033. }
  27034. if (this.uvs3) {
  27035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27036. }
  27037. if (this.uvs4) {
  27038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27039. }
  27040. if (this.uvs5) {
  27041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27042. }
  27043. if (this.uvs6) {
  27044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27045. }
  27046. if (this.colors) {
  27047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27048. }
  27049. if (this.matricesIndices) {
  27050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27051. }
  27052. if (this.matricesWeights) {
  27053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27054. }
  27055. if (this.matricesIndicesExtra) {
  27056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27057. }
  27058. if (this.matricesWeightsExtra) {
  27059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27060. }
  27061. if (this.indices) {
  27062. meshOrGeometry.setIndices(this.indices, null, updatable);
  27063. }
  27064. return this;
  27065. };
  27066. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27067. if (this.positions) {
  27068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27069. }
  27070. if (this.normals) {
  27071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27072. }
  27073. if (this.tangents) {
  27074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  27075. }
  27076. if (this.uvs) {
  27077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27078. }
  27079. if (this.uvs2) {
  27080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27081. }
  27082. if (this.uvs3) {
  27083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27084. }
  27085. if (this.uvs4) {
  27086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27087. }
  27088. if (this.uvs5) {
  27089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27090. }
  27091. if (this.uvs6) {
  27092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27093. }
  27094. if (this.colors) {
  27095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27096. }
  27097. if (this.matricesIndices) {
  27098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27099. }
  27100. if (this.matricesWeights) {
  27101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27102. }
  27103. if (this.matricesIndicesExtra) {
  27104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27105. }
  27106. if (this.matricesWeightsExtra) {
  27107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27108. }
  27109. if (this.indices) {
  27110. meshOrGeometry.setIndices(this.indices);
  27111. }
  27112. return this;
  27113. };
  27114. /**
  27115. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27116. * Returns the VertexData.
  27117. */
  27118. VertexData.prototype.transform = function (matrix) {
  27119. var transformed = BABYLON.Vector3.Zero();
  27120. var index;
  27121. if (this.positions) {
  27122. var position = BABYLON.Vector3.Zero();
  27123. for (index = 0; index < this.positions.length; index += 3) {
  27124. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27125. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27126. this.positions[index] = transformed.x;
  27127. this.positions[index + 1] = transformed.y;
  27128. this.positions[index + 2] = transformed.z;
  27129. }
  27130. }
  27131. if (this.normals) {
  27132. var normal = BABYLON.Vector3.Zero();
  27133. for (index = 0; index < this.normals.length; index += 3) {
  27134. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27135. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27136. this.normals[index] = transformed.x;
  27137. this.normals[index + 1] = transformed.y;
  27138. this.normals[index + 2] = transformed.z;
  27139. }
  27140. }
  27141. if (this.tangents) {
  27142. var tangent = BABYLON.Vector4.Zero();
  27143. var tangentTransformed = BABYLON.Vector4.Zero();
  27144. for (index = 0; index < this.tangents.length; index += 4) {
  27145. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27146. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27147. this.tangents[index] = tangentTransformed.x;
  27148. this.tangents[index + 1] = tangentTransformed.y;
  27149. this.tangents[index + 2] = tangentTransformed.z;
  27150. this.tangents[index + 3] = tangentTransformed.w;
  27151. }
  27152. }
  27153. return this;
  27154. };
  27155. /**
  27156. * Merges the passed VertexData into the current one.
  27157. * Returns the modified VertexData.
  27158. */
  27159. VertexData.prototype.merge = function (other) {
  27160. if (other.indices) {
  27161. if (!this.indices) {
  27162. this.indices = [];
  27163. }
  27164. var offset = this.positions ? this.positions.length / 3 : 0;
  27165. for (var index = 0; index < other.indices.length; index++) {
  27166. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27167. this.indices.push(other.indices[index] + offset);
  27168. }
  27169. }
  27170. this.positions = this._mergeElement(this.positions, other.positions);
  27171. var count = this.positions.length / 3;
  27172. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27173. this.tangents = this._mergeElement(this.tangents, other.tangents, count * 4);
  27174. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27175. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27176. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27177. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27178. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27179. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27180. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27181. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27182. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27183. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27184. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27185. return this;
  27186. };
  27187. VertexData.prototype._mergeElement = function (source, other, length) {
  27188. if (length === void 0) { length = 0; }
  27189. if (!other && !source) {
  27190. return null;
  27191. }
  27192. if (!other) {
  27193. return this._mergeElement(source, new Float32Array(source.length), length);
  27194. }
  27195. if (!source) {
  27196. if (length === other.length) {
  27197. return other;
  27198. }
  27199. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27200. }
  27201. var len = other.length + source.length;
  27202. var isSrcTypedArray = source instanceof Float32Array;
  27203. var isOthTypedArray = other instanceof Float32Array;
  27204. // use non-loop method when the source is Float32Array
  27205. if (isSrcTypedArray) {
  27206. var ret32 = new Float32Array(len);
  27207. ret32.set(source);
  27208. ret32.set(other, source.length);
  27209. return ret32;
  27210. // source is number[], when other is also use concat
  27211. }
  27212. else if (!isOthTypedArray) {
  27213. return source.concat(other);
  27214. // source is a number[], but other is a Float32Array, loop required
  27215. }
  27216. else {
  27217. var ret = source.slice(0); // copy source to a separate array
  27218. for (var i = 0, len = other.length; i < len; i++) {
  27219. ret.push(other[i]);
  27220. }
  27221. return ret;
  27222. }
  27223. };
  27224. /**
  27225. * Serializes the VertexData.
  27226. * Returns a serialized object.
  27227. */
  27228. VertexData.prototype.serialize = function () {
  27229. var serializationObject = this.serialize();
  27230. if (this.positions) {
  27231. serializationObject.positions = this.positions;
  27232. }
  27233. if (this.normals) {
  27234. serializationObject.normals = this.normals;
  27235. }
  27236. if (this.tangents) {
  27237. serializationObject.tangents = this.tangents;
  27238. }
  27239. if (this.uvs) {
  27240. serializationObject.uvs = this.uvs;
  27241. }
  27242. if (this.uvs2) {
  27243. serializationObject.uvs2 = this.uvs2;
  27244. }
  27245. if (this.uvs3) {
  27246. serializationObject.uvs3 = this.uvs3;
  27247. }
  27248. if (this.uvs4) {
  27249. serializationObject.uvs4 = this.uvs4;
  27250. }
  27251. if (this.uvs5) {
  27252. serializationObject.uvs5 = this.uvs5;
  27253. }
  27254. if (this.uvs6) {
  27255. serializationObject.uvs6 = this.uvs6;
  27256. }
  27257. if (this.colors) {
  27258. serializationObject.colors = this.colors;
  27259. }
  27260. if (this.matricesIndices) {
  27261. serializationObject.matricesIndices = this.matricesIndices;
  27262. serializationObject.matricesIndices._isExpanded = true;
  27263. }
  27264. if (this.matricesWeights) {
  27265. serializationObject.matricesWeights = this.matricesWeights;
  27266. }
  27267. if (this.matricesIndicesExtra) {
  27268. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27269. serializationObject.matricesIndicesExtra._isExpanded = true;
  27270. }
  27271. if (this.matricesWeightsExtra) {
  27272. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27273. }
  27274. serializationObject.indices = this.indices;
  27275. return serializationObject;
  27276. };
  27277. // Statics
  27278. /**
  27279. * Returns the object VertexData associated to the passed mesh.
  27280. */
  27281. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27282. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27283. };
  27284. /**
  27285. * Returns the object VertexData associated to the passed geometry.
  27286. */
  27287. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27288. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27289. };
  27290. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27291. var result = new VertexData();
  27292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27293. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27294. }
  27295. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27296. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27297. }
  27298. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27299. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27300. }
  27301. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27302. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27303. }
  27304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27305. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27306. }
  27307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27308. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27309. }
  27310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27311. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27312. }
  27313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27314. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27315. }
  27316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27317. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27318. }
  27319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27320. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27321. }
  27322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27323. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27324. }
  27325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27326. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27327. }
  27328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27329. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27330. }
  27331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27332. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27333. }
  27334. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27335. return result;
  27336. };
  27337. /**
  27338. * Creates the vertexData of the Ribbon.
  27339. */
  27340. VertexData.CreateRibbon = function (options) {
  27341. var pathArray = options.pathArray;
  27342. var closeArray = options.closeArray || false;
  27343. var closePath = options.closePath || false;
  27344. var invertUV = options.invertUV || false;
  27345. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27346. var offset = options.offset || defaultOffset;
  27347. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27348. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27349. var customUV = options.uvs;
  27350. var customColors = options.colors;
  27351. var positions = [];
  27352. var indices = [];
  27353. var normals = [];
  27354. var uvs = [];
  27355. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27356. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27357. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27358. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27359. var minlg; // minimal length among all paths from pathArray
  27360. var lg = []; // array of path lengths : nb of vertex per path
  27361. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27362. var p; // path iterator
  27363. var i; // point iterator
  27364. var j; // point iterator
  27365. // if single path in pathArray
  27366. if (pathArray.length < 2) {
  27367. var ar1 = [];
  27368. var ar2 = [];
  27369. for (i = 0; i < pathArray[0].length - offset; i++) {
  27370. ar1.push(pathArray[0][i]);
  27371. ar2.push(pathArray[0][i + offset]);
  27372. }
  27373. pathArray = [ar1, ar2];
  27374. }
  27375. // positions and horizontal distances (u)
  27376. var idc = 0;
  27377. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27378. var path;
  27379. var l;
  27380. minlg = pathArray[0].length;
  27381. var vectlg;
  27382. var dist;
  27383. for (p = 0; p < pathArray.length; p++) {
  27384. uTotalDistance[p] = 0;
  27385. us[p] = [0];
  27386. path = pathArray[p];
  27387. l = path.length;
  27388. minlg = (minlg < l) ? minlg : l;
  27389. j = 0;
  27390. while (j < l) {
  27391. positions.push(path[j].x, path[j].y, path[j].z);
  27392. if (j > 0) {
  27393. vectlg = path[j].subtract(path[j - 1]).length();
  27394. dist = vectlg + uTotalDistance[p];
  27395. us[p].push(dist);
  27396. uTotalDistance[p] = dist;
  27397. }
  27398. j++;
  27399. }
  27400. if (closePath) {
  27401. j--;
  27402. positions.push(path[0].x, path[0].y, path[0].z);
  27403. vectlg = path[j].subtract(path[0]).length();
  27404. dist = vectlg + uTotalDistance[p];
  27405. us[p].push(dist);
  27406. uTotalDistance[p] = dist;
  27407. }
  27408. lg[p] = l + closePathCorr;
  27409. idx[p] = idc;
  27410. idc += (l + closePathCorr);
  27411. }
  27412. // vertical distances (v)
  27413. var path1;
  27414. var path2;
  27415. var vertex1;
  27416. var vertex2;
  27417. for (i = 0; i < minlg + closePathCorr; i++) {
  27418. vTotalDistance[i] = 0;
  27419. vs[i] = [0];
  27420. for (p = 0; p < pathArray.length - 1; p++) {
  27421. path1 = pathArray[p];
  27422. path2 = pathArray[p + 1];
  27423. if (i === minlg) {
  27424. vertex1 = path1[0];
  27425. vertex2 = path2[0];
  27426. }
  27427. else {
  27428. vertex1 = path1[i];
  27429. vertex2 = path2[i];
  27430. }
  27431. vectlg = vertex2.subtract(vertex1).length();
  27432. dist = vectlg + vTotalDistance[i];
  27433. vs[i].push(dist);
  27434. vTotalDistance[i] = dist;
  27435. }
  27436. if (closeArray) {
  27437. path1 = pathArray[p];
  27438. path2 = pathArray[0];
  27439. if (i === minlg) {
  27440. vertex2 = path2[0];
  27441. }
  27442. vectlg = vertex2.subtract(vertex1).length();
  27443. dist = vectlg + vTotalDistance[i];
  27444. vTotalDistance[i] = dist;
  27445. }
  27446. }
  27447. // uvs
  27448. var u;
  27449. var v;
  27450. if (customUV) {
  27451. for (p = 0; p < customUV.length; p++) {
  27452. uvs.push(customUV[p].x, customUV[p].y);
  27453. }
  27454. }
  27455. else {
  27456. for (p = 0; p < pathArray.length; p++) {
  27457. for (i = 0; i < minlg + closePathCorr; i++) {
  27458. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27459. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27460. if (invertUV) {
  27461. uvs.push(v, u);
  27462. }
  27463. else {
  27464. uvs.push(u, v);
  27465. }
  27466. }
  27467. }
  27468. }
  27469. // indices
  27470. p = 0; // path index
  27471. var pi = 0; // positions array index
  27472. var l1 = lg[p] - 1; // path1 length
  27473. var l2 = lg[p + 1] - 1; // path2 length
  27474. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27475. var shft = idx[1] - idx[0]; // shift
  27476. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27477. while (pi <= min && p < path1nb) {
  27478. // 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
  27479. indices.push(pi, pi + shft, pi + 1);
  27480. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27481. pi += 1;
  27482. if (pi === min) {
  27483. p++;
  27484. if (p === lg.length - 1) {
  27485. shft = idx[0] - idx[p];
  27486. l1 = lg[p] - 1;
  27487. l2 = lg[0] - 1;
  27488. }
  27489. else {
  27490. shft = idx[p + 1] - idx[p];
  27491. l1 = lg[p] - 1;
  27492. l2 = lg[p + 1] - 1;
  27493. }
  27494. pi = idx[p];
  27495. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27496. }
  27497. }
  27498. // normals
  27499. VertexData.ComputeNormals(positions, indices, normals);
  27500. if (closePath) {
  27501. var indexFirst = 0;
  27502. var indexLast = 0;
  27503. for (p = 0; p < pathArray.length; p++) {
  27504. indexFirst = idx[p] * 3;
  27505. if (p + 1 < pathArray.length) {
  27506. indexLast = (idx[p + 1] - 1) * 3;
  27507. }
  27508. else {
  27509. indexLast = normals.length - 3;
  27510. }
  27511. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27512. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27513. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27514. normals[indexLast] = normals[indexFirst];
  27515. normals[indexLast + 1] = normals[indexFirst + 1];
  27516. normals[indexLast + 2] = normals[indexFirst + 2];
  27517. }
  27518. }
  27519. // sides
  27520. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27521. // Colors
  27522. if (customColors) {
  27523. var colors = new Float32Array(customColors.length * 4);
  27524. for (var c = 0; c < customColors.length; c++) {
  27525. colors[c * 4] = customColors[c].r;
  27526. colors[c * 4 + 1] = customColors[c].g;
  27527. colors[c * 4 + 2] = customColors[c].b;
  27528. colors[c * 4 + 3] = customColors[c].a;
  27529. }
  27530. }
  27531. // Result
  27532. var vertexData = new VertexData();
  27533. var positions32 = new Float32Array(positions);
  27534. var normals32 = new Float32Array(normals);
  27535. var uvs32 = new Float32Array(uvs);
  27536. vertexData.indices = indices;
  27537. vertexData.positions = positions32;
  27538. vertexData.normals = normals32;
  27539. vertexData.uvs = uvs32;
  27540. if (customColors) {
  27541. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27542. }
  27543. if (closePath) {
  27544. vertexData._idx = idx;
  27545. }
  27546. return vertexData;
  27547. };
  27548. /**
  27549. * Creates the VertexData of the Box.
  27550. */
  27551. VertexData.CreateBox = function (options) {
  27552. var normalsSource = [
  27553. new BABYLON.Vector3(0, 0, 1),
  27554. new BABYLON.Vector3(0, 0, -1),
  27555. new BABYLON.Vector3(1, 0, 0),
  27556. new BABYLON.Vector3(-1, 0, 0),
  27557. new BABYLON.Vector3(0, 1, 0),
  27558. new BABYLON.Vector3(0, -1, 0)
  27559. ];
  27560. var indices = [];
  27561. var positions = [];
  27562. var normals = [];
  27563. var uvs = [];
  27564. var width = options.width || options.size || 1;
  27565. var height = options.height || options.size || 1;
  27566. var depth = options.depth || options.size || 1;
  27567. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27568. var faceUV = options.faceUV || new Array(6);
  27569. var faceColors = options.faceColors;
  27570. var colors = [];
  27571. // default face colors and UV if undefined
  27572. for (var f = 0; f < 6; f++) {
  27573. if (faceUV[f] === undefined) {
  27574. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27575. }
  27576. if (faceColors && faceColors[f] === undefined) {
  27577. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27578. }
  27579. }
  27580. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27581. // Create each face in turn.
  27582. for (var index = 0; index < normalsSource.length; index++) {
  27583. var normal = normalsSource[index];
  27584. // Get two vectors perpendicular to the face normal and to each other.
  27585. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27586. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27587. // Six indices (two triangles) per face.
  27588. var verticesLength = positions.length / 3;
  27589. indices.push(verticesLength);
  27590. indices.push(verticesLength + 1);
  27591. indices.push(verticesLength + 2);
  27592. indices.push(verticesLength);
  27593. indices.push(verticesLength + 2);
  27594. indices.push(verticesLength + 3);
  27595. // Four vertices per face.
  27596. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27597. positions.push(vertex.x, vertex.y, vertex.z);
  27598. normals.push(normal.x, normal.y, normal.z);
  27599. uvs.push(faceUV[index].z, faceUV[index].w);
  27600. if (faceColors) {
  27601. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27602. }
  27603. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27604. positions.push(vertex.x, vertex.y, vertex.z);
  27605. normals.push(normal.x, normal.y, normal.z);
  27606. uvs.push(faceUV[index].x, faceUV[index].w);
  27607. if (faceColors) {
  27608. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27609. }
  27610. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27611. positions.push(vertex.x, vertex.y, vertex.z);
  27612. normals.push(normal.x, normal.y, normal.z);
  27613. uvs.push(faceUV[index].x, faceUV[index].y);
  27614. if (faceColors) {
  27615. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27616. }
  27617. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27618. positions.push(vertex.x, vertex.y, vertex.z);
  27619. normals.push(normal.x, normal.y, normal.z);
  27620. uvs.push(faceUV[index].z, faceUV[index].y);
  27621. if (faceColors) {
  27622. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27623. }
  27624. }
  27625. // sides
  27626. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27627. // Result
  27628. var vertexData = new VertexData();
  27629. vertexData.indices = indices;
  27630. vertexData.positions = positions;
  27631. vertexData.normals = normals;
  27632. vertexData.uvs = uvs;
  27633. if (faceColors) {
  27634. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27635. vertexData.colors = totalColors;
  27636. }
  27637. return vertexData;
  27638. };
  27639. /**
  27640. * Creates the VertexData of the Sphere.
  27641. */
  27642. VertexData.CreateSphere = function (options) {
  27643. var segments = options.segments || 32;
  27644. var diameterX = options.diameterX || options.diameter || 1;
  27645. var diameterY = options.diameterY || options.diameter || 1;
  27646. var diameterZ = options.diameterZ || options.diameter || 1;
  27647. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27648. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27650. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27651. var totalZRotationSteps = 2 + segments;
  27652. var totalYRotationSteps = 2 * totalZRotationSteps;
  27653. var indices = [];
  27654. var positions = [];
  27655. var normals = [];
  27656. var uvs = [];
  27657. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27658. var normalizedZ = zRotationStep / totalZRotationSteps;
  27659. var angleZ = normalizedZ * Math.PI * slice;
  27660. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27661. var normalizedY = yRotationStep / totalYRotationSteps;
  27662. var angleY = normalizedY * Math.PI * 2 * arc;
  27663. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27664. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27665. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27666. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27667. var vertex = complete.multiply(radius);
  27668. var normal = complete.divide(radius).normalize();
  27669. positions.push(vertex.x, vertex.y, vertex.z);
  27670. normals.push(normal.x, normal.y, normal.z);
  27671. uvs.push(normalizedY, normalizedZ);
  27672. }
  27673. if (zRotationStep > 0) {
  27674. var verticesCount = positions.length / 3;
  27675. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27676. indices.push((firstIndex));
  27677. indices.push((firstIndex + 1));
  27678. indices.push(firstIndex + totalYRotationSteps + 1);
  27679. indices.push((firstIndex + totalYRotationSteps + 1));
  27680. indices.push((firstIndex + 1));
  27681. indices.push((firstIndex + totalYRotationSteps + 2));
  27682. }
  27683. }
  27684. }
  27685. // Sides
  27686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27687. // Result
  27688. var vertexData = new VertexData();
  27689. vertexData.indices = indices;
  27690. vertexData.positions = positions;
  27691. vertexData.normals = normals;
  27692. vertexData.uvs = uvs;
  27693. return vertexData;
  27694. };
  27695. /**
  27696. * Creates the VertexData of the Cylinder or Cone.
  27697. */
  27698. VertexData.CreateCylinder = function (options) {
  27699. var height = options.height || 2;
  27700. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27701. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27702. var tessellation = options.tessellation || 24;
  27703. var subdivisions = options.subdivisions || 1;
  27704. var hasRings = options.hasRings;
  27705. var enclose = options.enclose;
  27706. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27707. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27708. var faceUV = options.faceUV || new Array(3);
  27709. var faceColors = options.faceColors;
  27710. // default face colors and UV if undefined
  27711. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27712. var ringNb = (hasRings) ? subdivisions : 1;
  27713. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27714. var f;
  27715. for (f = 0; f < surfaceNb; f++) {
  27716. if (faceColors && faceColors[f] === undefined) {
  27717. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27718. }
  27719. }
  27720. for (f = 0; f < surfaceNb; f++) {
  27721. if (faceUV && faceUV[f] === undefined) {
  27722. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27723. }
  27724. }
  27725. var indices = new Array();
  27726. var positions = new Array();
  27727. var normals = new Array();
  27728. var uvs = new Array();
  27729. var colors = new Array();
  27730. var angle_step = Math.PI * 2 * arc / tessellation;
  27731. var angle;
  27732. var h;
  27733. var radius;
  27734. var tan = (diameterBottom - diameterTop) / 2 / height;
  27735. var ringVertex = BABYLON.Vector3.Zero();
  27736. var ringNormal = BABYLON.Vector3.Zero();
  27737. var ringFirstVertex = BABYLON.Vector3.Zero();
  27738. var ringFirstNormal = BABYLON.Vector3.Zero();
  27739. var quadNormal = BABYLON.Vector3.Zero();
  27740. var Y = BABYLON.Axis.Y;
  27741. // positions, normals, uvs
  27742. var i;
  27743. var j;
  27744. var r;
  27745. var ringIdx = 1;
  27746. var s = 1; // surface index
  27747. var cs = 0;
  27748. var v = 0;
  27749. for (i = 0; i <= subdivisions; i++) {
  27750. h = i / subdivisions;
  27751. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27752. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27753. for (r = 0; r < ringIdx; r++) {
  27754. if (hasRings) {
  27755. s += r;
  27756. }
  27757. if (enclose) {
  27758. s += 2 * r;
  27759. }
  27760. for (j = 0; j <= tessellation; j++) {
  27761. angle = j * angle_step;
  27762. // position
  27763. ringVertex.x = Math.cos(-angle) * radius;
  27764. ringVertex.y = -height / 2 + h * height;
  27765. ringVertex.z = Math.sin(-angle) * radius;
  27766. // normal
  27767. if (diameterTop === 0 && i === subdivisions) {
  27768. // if no top cap, reuse former normals
  27769. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27770. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27771. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27772. }
  27773. else {
  27774. ringNormal.x = ringVertex.x;
  27775. ringNormal.z = ringVertex.z;
  27776. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27777. ringNormal.normalize();
  27778. }
  27779. // keep first ring vertex values for enclose
  27780. if (j === 0) {
  27781. ringFirstVertex.copyFrom(ringVertex);
  27782. ringFirstNormal.copyFrom(ringNormal);
  27783. }
  27784. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27785. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27786. if (hasRings) {
  27787. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27788. }
  27789. else {
  27790. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27791. }
  27792. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27793. if (faceColors) {
  27794. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27795. }
  27796. }
  27797. // if enclose, add four vertices and their dedicated normals
  27798. if (arc !== 1 && enclose) {
  27799. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27800. positions.push(0, ringVertex.y, 0);
  27801. positions.push(0, ringVertex.y, 0);
  27802. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27803. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27804. quadNormal.normalize();
  27805. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27806. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27807. quadNormal.normalize();
  27808. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27809. if (hasRings) {
  27810. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27811. }
  27812. else {
  27813. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27814. }
  27815. uvs.push(faceUV[s + 1].x, v);
  27816. uvs.push(faceUV[s + 1].z, v);
  27817. if (hasRings) {
  27818. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27819. }
  27820. else {
  27821. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27822. }
  27823. uvs.push(faceUV[s + 2].x, v);
  27824. uvs.push(faceUV[s + 2].z, v);
  27825. if (faceColors) {
  27826. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27827. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27828. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27829. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27830. }
  27831. }
  27832. if (cs !== s) {
  27833. cs = s;
  27834. }
  27835. }
  27836. }
  27837. // indices
  27838. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27839. var s;
  27840. i = 0;
  27841. for (s = 0; s < subdivisions; s++) {
  27842. for (j = 0; j < tessellation; j++) {
  27843. var i0 = i * (e + 1) + j;
  27844. var i1 = (i + 1) * (e + 1) + j;
  27845. var i2 = i * (e + 1) + (j + 1);
  27846. var i3 = (i + 1) * (e + 1) + (j + 1);
  27847. indices.push(i0, i1, i2);
  27848. indices.push(i3, i2, i1);
  27849. }
  27850. if (arc !== 1 && enclose) {
  27851. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27852. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27853. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27854. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27855. }
  27856. i = (hasRings) ? (i + 2) : (i + 1);
  27857. }
  27858. // Caps
  27859. var createCylinderCap = function (isTop) {
  27860. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27861. if (radius === 0) {
  27862. return;
  27863. }
  27864. // Cap positions, normals & uvs
  27865. var angle;
  27866. var circleVector;
  27867. var i;
  27868. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27869. var c;
  27870. if (faceColors) {
  27871. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27872. }
  27873. // cap center
  27874. var vbase = positions.length / 3;
  27875. var offset = isTop ? height / 2 : -height / 2;
  27876. var center = new BABYLON.Vector3(0, offset, 0);
  27877. positions.push(center.x, center.y, center.z);
  27878. normals.push(0, isTop ? 1 : -1, 0);
  27879. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27880. if (faceColors) {
  27881. colors.push(c.r, c.g, c.b, c.a);
  27882. }
  27883. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27884. for (i = 0; i <= tessellation; i++) {
  27885. angle = Math.PI * 2 * i * arc / tessellation;
  27886. var cos = Math.cos(-angle);
  27887. var sin = Math.sin(-angle);
  27888. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27889. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27890. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27891. normals.push(0, isTop ? 1 : -1, 0);
  27892. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27893. if (faceColors) {
  27894. colors.push(c.r, c.g, c.b, c.a);
  27895. }
  27896. }
  27897. // Cap indices
  27898. for (i = 0; i < tessellation; i++) {
  27899. if (!isTop) {
  27900. indices.push(vbase);
  27901. indices.push(vbase + (i + 1));
  27902. indices.push(vbase + (i + 2));
  27903. }
  27904. else {
  27905. indices.push(vbase);
  27906. indices.push(vbase + (i + 2));
  27907. indices.push(vbase + (i + 1));
  27908. }
  27909. }
  27910. };
  27911. // add caps to geometry
  27912. createCylinderCap(false);
  27913. createCylinderCap(true);
  27914. // Sides
  27915. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27916. var vertexData = new VertexData();
  27917. vertexData.indices = indices;
  27918. vertexData.positions = positions;
  27919. vertexData.normals = normals;
  27920. vertexData.uvs = uvs;
  27921. if (faceColors) {
  27922. vertexData.colors = colors;
  27923. }
  27924. return vertexData;
  27925. };
  27926. /**
  27927. * Creates the VertexData of the Torus.
  27928. */
  27929. VertexData.CreateTorus = function (options) {
  27930. var indices = [];
  27931. var positions = [];
  27932. var normals = [];
  27933. var uvs = [];
  27934. var diameter = options.diameter || 1;
  27935. var thickness = options.thickness || 0.5;
  27936. var tessellation = options.tessellation || 16;
  27937. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27938. var stride = tessellation + 1;
  27939. for (var i = 0; i <= tessellation; i++) {
  27940. var u = i / tessellation;
  27941. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27942. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27943. for (var j = 0; j <= tessellation; j++) {
  27944. var v = 1 - j / tessellation;
  27945. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27946. var dx = Math.cos(innerAngle);
  27947. var dy = Math.sin(innerAngle);
  27948. // Create a vertex.
  27949. var normal = new BABYLON.Vector3(dx, dy, 0);
  27950. var position = normal.scale(thickness / 2);
  27951. var textureCoordinate = new BABYLON.Vector2(u, v);
  27952. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27953. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27954. positions.push(position.x, position.y, position.z);
  27955. normals.push(normal.x, normal.y, normal.z);
  27956. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27957. // And create indices for two triangles.
  27958. var nextI = (i + 1) % stride;
  27959. var nextJ = (j + 1) % stride;
  27960. indices.push(i * stride + j);
  27961. indices.push(i * stride + nextJ);
  27962. indices.push(nextI * stride + j);
  27963. indices.push(i * stride + nextJ);
  27964. indices.push(nextI * stride + nextJ);
  27965. indices.push(nextI * stride + j);
  27966. }
  27967. }
  27968. // Sides
  27969. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27970. // Result
  27971. var vertexData = new VertexData();
  27972. vertexData.indices = indices;
  27973. vertexData.positions = positions;
  27974. vertexData.normals = normals;
  27975. vertexData.uvs = uvs;
  27976. return vertexData;
  27977. };
  27978. /**
  27979. * Creates the VertexData of the LineSystem.
  27980. */
  27981. VertexData.CreateLineSystem = function (options) {
  27982. var indices = [];
  27983. var positions = [];
  27984. var lines = options.lines;
  27985. var idx = 0;
  27986. for (var l = 0; l < lines.length; l++) {
  27987. var points = lines[l];
  27988. for (var index = 0; index < points.length; index++) {
  27989. positions.push(points[index].x, points[index].y, points[index].z);
  27990. if (index > 0) {
  27991. indices.push(idx - 1);
  27992. indices.push(idx);
  27993. }
  27994. idx++;
  27995. }
  27996. }
  27997. var vertexData = new VertexData();
  27998. vertexData.indices = indices;
  27999. vertexData.positions = positions;
  28000. return vertexData;
  28001. };
  28002. /**
  28003. * Create the VertexData of the DashedLines.
  28004. */
  28005. VertexData.CreateDashedLines = function (options) {
  28006. var dashSize = options.dashSize || 3;
  28007. var gapSize = options.gapSize || 1;
  28008. var dashNb = options.dashNb || 200;
  28009. var points = options.points;
  28010. var positions = new Array();
  28011. var indices = new Array();
  28012. var curvect = BABYLON.Vector3.Zero();
  28013. var lg = 0;
  28014. var nb = 0;
  28015. var shft = 0;
  28016. var dashshft = 0;
  28017. var curshft = 0;
  28018. var idx = 0;
  28019. var i = 0;
  28020. for (i = 0; i < points.length - 1; i++) {
  28021. points[i + 1].subtractToRef(points[i], curvect);
  28022. lg += curvect.length();
  28023. }
  28024. shft = lg / dashNb;
  28025. dashshft = dashSize * shft / (dashSize + gapSize);
  28026. for (i = 0; i < points.length - 1; i++) {
  28027. points[i + 1].subtractToRef(points[i], curvect);
  28028. nb = Math.floor(curvect.length() / shft);
  28029. curvect.normalize();
  28030. for (var j = 0; j < nb; j++) {
  28031. curshft = shft * j;
  28032. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28033. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28034. indices.push(idx, idx + 1);
  28035. idx += 2;
  28036. }
  28037. }
  28038. // Result
  28039. var vertexData = new VertexData();
  28040. vertexData.positions = positions;
  28041. vertexData.indices = indices;
  28042. return vertexData;
  28043. };
  28044. /**
  28045. * Creates the VertexData of the Ground.
  28046. */
  28047. VertexData.CreateGround = function (options) {
  28048. var indices = [];
  28049. var positions = [];
  28050. var normals = [];
  28051. var uvs = [];
  28052. var row, col;
  28053. var width = options.width || 1;
  28054. var height = options.height || 1;
  28055. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  28056. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  28057. for (row = 0; row <= subdivisionsY; row++) {
  28058. for (col = 0; col <= subdivisionsX; col++) {
  28059. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  28060. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28061. positions.push(position.x, position.y, position.z);
  28062. normals.push(normal.x, normal.y, normal.z);
  28063. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  28064. }
  28065. }
  28066. for (row = 0; row < subdivisionsY; row++) {
  28067. for (col = 0; col < subdivisionsX; col++) {
  28068. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28069. indices.push(col + 1 + row * (subdivisionsX + 1));
  28070. indices.push(col + row * (subdivisionsX + 1));
  28071. indices.push(col + (row + 1) * (subdivisionsX + 1));
  28072. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28073. indices.push(col + row * (subdivisionsX + 1));
  28074. }
  28075. }
  28076. // Result
  28077. var vertexData = new VertexData();
  28078. vertexData.indices = indices;
  28079. vertexData.positions = positions;
  28080. vertexData.normals = normals;
  28081. vertexData.uvs = uvs;
  28082. return vertexData;
  28083. };
  28084. /**
  28085. * Creates the VertexData of the TiledGround.
  28086. */
  28087. VertexData.CreateTiledGround = function (options) {
  28088. var xmin = options.xmin || -1.0;
  28089. var zmin = options.zmin || -1.0;
  28090. var xmax = options.xmax || 1.0;
  28091. var zmax = options.zmax || 1.0;
  28092. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28093. var precision = options.precision || { w: 1, h: 1 };
  28094. var indices = new Array();
  28095. var positions = new Array();
  28096. var normals = new Array();
  28097. var uvs = new Array();
  28098. var row, col, tileRow, tileCol;
  28099. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  28100. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28101. precision.w = (precision.w < 1) ? 1 : precision.w;
  28102. precision.h = (precision.h < 1) ? 1 : precision.h;
  28103. var tileSize = {
  28104. 'w': (xmax - xmin) / subdivisions.w,
  28105. 'h': (zmax - zmin) / subdivisions.h
  28106. };
  28107. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28108. // Indices
  28109. var base = positions.length / 3;
  28110. var rowLength = precision.w + 1;
  28111. for (row = 0; row < precision.h; row++) {
  28112. for (col = 0; col < precision.w; col++) {
  28113. var square = [
  28114. base + col + row * rowLength,
  28115. base + (col + 1) + row * rowLength,
  28116. base + (col + 1) + (row + 1) * rowLength,
  28117. base + col + (row + 1) * rowLength
  28118. ];
  28119. indices.push(square[1]);
  28120. indices.push(square[2]);
  28121. indices.push(square[3]);
  28122. indices.push(square[0]);
  28123. indices.push(square[1]);
  28124. indices.push(square[3]);
  28125. }
  28126. }
  28127. // Position, normals and uvs
  28128. var position = BABYLON.Vector3.Zero();
  28129. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28130. for (row = 0; row <= precision.h; row++) {
  28131. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28132. for (col = 0; col <= precision.w; col++) {
  28133. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28134. position.y = 0;
  28135. positions.push(position.x, position.y, position.z);
  28136. normals.push(normal.x, normal.y, normal.z);
  28137. uvs.push(col / precision.w, row / precision.h);
  28138. }
  28139. }
  28140. }
  28141. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28142. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28143. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28144. }
  28145. }
  28146. // Result
  28147. var vertexData = new VertexData();
  28148. vertexData.indices = indices;
  28149. vertexData.positions = positions;
  28150. vertexData.normals = normals;
  28151. vertexData.uvs = uvs;
  28152. return vertexData;
  28153. };
  28154. /**
  28155. * Creates the VertexData of the Ground designed from a heightmap.
  28156. */
  28157. VertexData.CreateGroundFromHeightMap = function (options) {
  28158. var indices = [];
  28159. var positions = [];
  28160. var normals = [];
  28161. var uvs = [];
  28162. var row, col;
  28163. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28164. // Vertices
  28165. for (row = 0; row <= options.subdivisions; row++) {
  28166. for (col = 0; col <= options.subdivisions; col++) {
  28167. 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));
  28168. // Compute height
  28169. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28170. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28171. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28172. var r = options.buffer[pos] / 255.0;
  28173. var g = options.buffer[pos + 1] / 255.0;
  28174. var b = options.buffer[pos + 2] / 255.0;
  28175. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28176. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28177. // Add vertex
  28178. positions.push(position.x, position.y, position.z);
  28179. normals.push(0, 0, 0);
  28180. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28181. }
  28182. }
  28183. // Indices
  28184. for (row = 0; row < options.subdivisions; row++) {
  28185. for (col = 0; col < options.subdivisions; col++) {
  28186. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28187. indices.push(col + 1 + row * (options.subdivisions + 1));
  28188. indices.push(col + row * (options.subdivisions + 1));
  28189. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28190. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28191. indices.push(col + row * (options.subdivisions + 1));
  28192. }
  28193. }
  28194. // Normals
  28195. VertexData.ComputeNormals(positions, indices, normals);
  28196. // Result
  28197. var vertexData = new VertexData();
  28198. vertexData.indices = indices;
  28199. vertexData.positions = positions;
  28200. vertexData.normals = normals;
  28201. vertexData.uvs = uvs;
  28202. return vertexData;
  28203. };
  28204. /**
  28205. * Creates the VertexData of the Plane.
  28206. */
  28207. VertexData.CreatePlane = function (options) {
  28208. var indices = [];
  28209. var positions = [];
  28210. var normals = [];
  28211. var uvs = [];
  28212. var width = options.width || options.size || 1;
  28213. var height = options.height || options.size || 1;
  28214. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28215. // Vertices
  28216. var halfWidth = width / 2.0;
  28217. var halfHeight = height / 2.0;
  28218. positions.push(-halfWidth, -halfHeight, 0);
  28219. normals.push(0, 0, -1.0);
  28220. uvs.push(0.0, 0.0);
  28221. positions.push(halfWidth, -halfHeight, 0);
  28222. normals.push(0, 0, -1.0);
  28223. uvs.push(1.0, 0.0);
  28224. positions.push(halfWidth, halfHeight, 0);
  28225. normals.push(0, 0, -1.0);
  28226. uvs.push(1.0, 1.0);
  28227. positions.push(-halfWidth, halfHeight, 0);
  28228. normals.push(0, 0, -1.0);
  28229. uvs.push(0.0, 1.0);
  28230. // Indices
  28231. indices.push(0);
  28232. indices.push(1);
  28233. indices.push(2);
  28234. indices.push(0);
  28235. indices.push(2);
  28236. indices.push(3);
  28237. // Sides
  28238. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28239. // Result
  28240. var vertexData = new VertexData();
  28241. vertexData.indices = indices;
  28242. vertexData.positions = positions;
  28243. vertexData.normals = normals;
  28244. vertexData.uvs = uvs;
  28245. return vertexData;
  28246. };
  28247. /**
  28248. * Creates the VertexData of the Disc or regular Polygon.
  28249. */
  28250. VertexData.CreateDisc = function (options) {
  28251. var positions = new Array();
  28252. var indices = new Array();
  28253. var normals = new Array();
  28254. var uvs = new Array();
  28255. var radius = options.radius || 0.5;
  28256. var tessellation = options.tessellation || 64;
  28257. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28258. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28259. // positions and uvs
  28260. positions.push(0, 0, 0); // disc center first
  28261. uvs.push(0.5, 0.5);
  28262. var theta = Math.PI * 2 * arc;
  28263. var step = theta / tessellation;
  28264. for (var a = 0; a < theta; a += step) {
  28265. var x = Math.cos(a);
  28266. var y = Math.sin(a);
  28267. var u = (x + 1) / 2;
  28268. var v = (1 - y) / 2;
  28269. positions.push(radius * x, radius * y, 0);
  28270. uvs.push(u, v);
  28271. }
  28272. if (arc === 1) {
  28273. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28274. uvs.push(uvs[2], uvs[3]);
  28275. }
  28276. //indices
  28277. var vertexNb = positions.length / 3;
  28278. for (var i = 1; i < vertexNb - 1; i++) {
  28279. indices.push(i + 1, 0, i);
  28280. }
  28281. // result
  28282. VertexData.ComputeNormals(positions, indices, normals);
  28283. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28284. var vertexData = new VertexData();
  28285. vertexData.indices = indices;
  28286. vertexData.positions = positions;
  28287. vertexData.normals = normals;
  28288. vertexData.uvs = uvs;
  28289. return vertexData;
  28290. };
  28291. /**
  28292. * Re-creates the VertexData of the Polygon for sideOrientation.
  28293. */
  28294. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28295. var faceUV = fUV || new Array(3);
  28296. var faceColors = fColors;
  28297. var colors = [];
  28298. // default face colors and UV if undefined
  28299. for (var f = 0; f < 3; f++) {
  28300. if (faceUV[f] === undefined) {
  28301. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28302. }
  28303. if (faceColors && faceColors[f] === undefined) {
  28304. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28305. }
  28306. }
  28307. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28308. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28309. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28310. var indices = polygon.getIndices();
  28311. // set face colours and textures
  28312. var idx = 0;
  28313. var face = 0;
  28314. for (var index = 0; index < normals.length; index += 3) {
  28315. //Edge Face no. 1
  28316. if (Math.abs(normals[index + 1]) < 0.001) {
  28317. face = 1;
  28318. }
  28319. //Top Face no. 0
  28320. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28321. face = 0;
  28322. }
  28323. //Bottom Face no. 2
  28324. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28325. face = 2;
  28326. }
  28327. idx = index / 3;
  28328. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28329. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28330. if (faceColors) {
  28331. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28332. }
  28333. }
  28334. // sides
  28335. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28336. // Result
  28337. var vertexData = new VertexData();
  28338. vertexData.indices = indices;
  28339. vertexData.positions = positions;
  28340. vertexData.normals = normals;
  28341. vertexData.uvs = uvs;
  28342. if (faceColors) {
  28343. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28344. vertexData.colors = totalColors;
  28345. }
  28346. return vertexData;
  28347. };
  28348. /**
  28349. * Creates the VertexData of the IcoSphere.
  28350. */
  28351. VertexData.CreateIcoSphere = function (options) {
  28352. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28353. var radius = options.radius || 1;
  28354. var flat = (options.flat === undefined) ? true : options.flat;
  28355. var subdivisions = options.subdivisions || 4;
  28356. var radiusX = options.radiusX || radius;
  28357. var radiusY = options.radiusY || radius;
  28358. var radiusZ = options.radiusZ || radius;
  28359. var t = (1 + Math.sqrt(5)) / 2;
  28360. // 12 vertex x,y,z
  28361. var ico_vertices = [
  28362. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28363. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28364. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28365. ];
  28366. // index of 3 vertex makes a face of icopshere
  28367. var ico_indices = [
  28368. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28369. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28370. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28371. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28372. ];
  28373. // vertex for uv have aliased position, not for UV
  28374. var vertices_unalias_id = [
  28375. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28376. // vertex alias
  28377. 0,
  28378. 2,
  28379. 3,
  28380. 3,
  28381. 3,
  28382. 4,
  28383. 7,
  28384. 8,
  28385. 9,
  28386. 9,
  28387. 10,
  28388. 11 // 23: B + 12
  28389. ];
  28390. // uv as integer step (not pixels !)
  28391. var ico_vertexuv = [
  28392. 5, 1, 3, 1, 6, 4, 0, 0,
  28393. 5, 3, 4, 2, 2, 2, 4, 0,
  28394. 2, 0, 1, 1, 6, 0, 6, 2,
  28395. // vertex alias (for same vertex on different faces)
  28396. 0, 4,
  28397. 3, 3,
  28398. 4, 4,
  28399. 3, 1,
  28400. 4, 2,
  28401. 4, 4,
  28402. 0, 2,
  28403. 1, 1,
  28404. 2, 2,
  28405. 3, 3,
  28406. 1, 3,
  28407. 2, 4 // 23: B + 12
  28408. ];
  28409. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28410. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28411. // First island of uv mapping
  28412. // v = 4h 3+ 2
  28413. // v = 3h 9+ 4
  28414. // v = 2h 9+ 5 B
  28415. // v = 1h 9 1 0
  28416. // v = 0h 3 8 7 A
  28417. // u = 0 1 2 3 4 5 6 *a
  28418. // Second island of uv mapping
  28419. // v = 4h 0+ B+ 4+
  28420. // v = 3h A+ 2+
  28421. // v = 2h 7+ 6 3+
  28422. // v = 1h 8+ 3+
  28423. // v = 0h
  28424. // u = 0 1 2 3 4 5 6 *a
  28425. // Face layout on texture UV mapping
  28426. // ============
  28427. // \ 4 /\ 16 / ======
  28428. // \ / \ / /\ 11 /
  28429. // \/ 7 \/ / \ /
  28430. // ======= / 10 \/
  28431. // /\ 17 /\ =======
  28432. // / \ / \ \ 15 /\
  28433. // / 8 \/ 12 \ \ / \
  28434. // ============ \/ 6 \
  28435. // \ 18 /\ ============
  28436. // \ / \ \ 5 /\ 0 /
  28437. // \/ 13 \ \ / \ /
  28438. // ======= \/ 1 \/
  28439. // =============
  28440. // /\ 19 /\ 2 /\
  28441. // / \ / \ / \
  28442. // / 14 \/ 9 \/ 3 \
  28443. // ===================
  28444. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28445. var ustep = 138 / 1024;
  28446. var vstep = 239 / 1024;
  28447. var uoffset = 60 / 1024;
  28448. var voffset = 26 / 1024;
  28449. // Second island should have margin, not to touch the first island
  28450. // avoid any borderline artefact in pixel rounding
  28451. var island_u_offset = -40 / 1024;
  28452. var island_v_offset = +20 / 1024;
  28453. // face is either island 0 or 1 :
  28454. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28455. var island = [
  28456. 0, 0, 0, 0, 1,
  28457. 0, 0, 1, 1, 0,
  28458. 0, 0, 1, 1, 0,
  28459. 0, 1, 1, 1, 0 // 15 - 19
  28460. ];
  28461. var indices = new Array();
  28462. var positions = new Array();
  28463. var normals = new Array();
  28464. var uvs = new Array();
  28465. var current_indice = 0;
  28466. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28467. var face_vertex_pos = new Array(3);
  28468. var face_vertex_uv = new Array(3);
  28469. var v012;
  28470. for (v012 = 0; v012 < 3; v012++) {
  28471. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28472. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28473. }
  28474. // create all with normals
  28475. for (var face = 0; face < 20; face++) {
  28476. // 3 vertex per face
  28477. for (v012 = 0; v012 < 3; v012++) {
  28478. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28479. var v_id = ico_indices[3 * face + v012];
  28480. // vertex have 3D position (x,y,z)
  28481. 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]);
  28482. // Normalize to get normal, then scale to radius
  28483. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28484. // uv Coordinates from vertex ID
  28485. 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);
  28486. }
  28487. // Subdivide the face (interpolate pos, norm, uv)
  28488. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28489. // - norm is linear interpolation of vertex corner normal
  28490. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28491. // - uv is linear interpolation
  28492. //
  28493. // Topology is as below for sub-divide by 2
  28494. // vertex shown as v0,v1,v2
  28495. // interp index is i1 to progress in range [v0,v1[
  28496. // interp index is i2 to progress in range [v0,v2[
  28497. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28498. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28499. //
  28500. //
  28501. // i2 v2
  28502. // ^ ^
  28503. // / / \
  28504. // / / \
  28505. // / / \
  28506. // / / (0,1) \
  28507. // / #---------\
  28508. // / / \ (0,0)'/ \
  28509. // / / \ / \
  28510. // / / \ / \
  28511. // / / (0,0) \ / (1,0) \
  28512. // / #---------#---------\
  28513. // v0 v1
  28514. //
  28515. // --------------------> i1
  28516. //
  28517. // interp of (i1,i2):
  28518. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28519. // along i1 : lerp(x0,x1, i1/(S-i2))
  28520. //
  28521. // centroid of triangle is needed to get help normal computation
  28522. // (c1,c2) are used for centroid location
  28523. var interp_vertex = function (i1, i2, c1, c2) {
  28524. // vertex is interpolated from
  28525. // - face_vertex_pos[0..2]
  28526. // - face_vertex_uv[0..2]
  28527. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28528. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28529. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28530. pos_interp.normalize();
  28531. var vertex_normal;
  28532. if (flat) {
  28533. // in flat mode, recalculate normal as face centroid normal
  28534. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28535. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28536. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28537. }
  28538. else {
  28539. // in smooth mode, recalculate normal from each single vertex position
  28540. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28541. }
  28542. // Vertex normal need correction due to X,Y,Z radius scaling
  28543. vertex_normal.x /= radiusX;
  28544. vertex_normal.y /= radiusY;
  28545. vertex_normal.z /= radiusZ;
  28546. vertex_normal.normalize();
  28547. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28548. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28549. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28550. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28551. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28552. uvs.push(uv_interp.x, uv_interp.y);
  28553. // push each vertex has member of a face
  28554. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28555. indices.push(current_indice);
  28556. current_indice++;
  28557. };
  28558. for (var i2 = 0; i2 < subdivisions; i2++) {
  28559. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28560. // face : (i1,i2) for /\ :
  28561. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28562. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28563. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28564. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28565. if (i1 + i2 + 1 < subdivisions) {
  28566. // face : (i1,i2)' for \/ :
  28567. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28568. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28569. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28570. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28571. }
  28572. }
  28573. }
  28574. }
  28575. // Sides
  28576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28577. // Result
  28578. var vertexData = new VertexData();
  28579. vertexData.indices = indices;
  28580. vertexData.positions = positions;
  28581. vertexData.normals = normals;
  28582. vertexData.uvs = uvs;
  28583. return vertexData;
  28584. };
  28585. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28586. /**
  28587. * Creates the VertexData of the Polyhedron.
  28588. */
  28589. VertexData.CreatePolyhedron = function (options) {
  28590. // provided polyhedron types :
  28591. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28592. // 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)
  28593. var polyhedra = [];
  28594. 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]] };
  28595. 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]] };
  28596. polyhedra[2] = {
  28597. 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]],
  28598. 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]]
  28599. };
  28600. polyhedra[3] = {
  28601. 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]],
  28602. 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]]
  28603. };
  28604. polyhedra[4] = {
  28605. 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]],
  28606. 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]]
  28607. };
  28608. 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]] };
  28609. 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]] };
  28610. 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]] };
  28611. 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]] };
  28612. 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]] };
  28613. 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]] };
  28614. 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]] };
  28615. 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]] };
  28616. 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]] };
  28617. polyhedra[14] = {
  28618. 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]],
  28619. 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]]
  28620. };
  28621. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28622. var size = options.size;
  28623. var sizeX = options.sizeX || size || 1;
  28624. var sizeY = options.sizeY || size || 1;
  28625. var sizeZ = options.sizeZ || size || 1;
  28626. var data = options.custom || polyhedra[type];
  28627. var nbfaces = data.face.length;
  28628. var faceUV = options.faceUV || new Array(nbfaces);
  28629. var faceColors = options.faceColors;
  28630. var flat = (options.flat === undefined) ? true : options.flat;
  28631. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28632. var positions = new Array();
  28633. var indices = new Array();
  28634. var normals = new Array();
  28635. var uvs = new Array();
  28636. var colors = new Array();
  28637. var index = 0;
  28638. var faceIdx = 0; // face cursor in the array "indexes"
  28639. var indexes = new Array();
  28640. var i = 0;
  28641. var f = 0;
  28642. var u, v, ang, x, y, tmp;
  28643. // default face colors and UV if undefined
  28644. if (flat) {
  28645. for (f = 0; f < nbfaces; f++) {
  28646. if (faceColors && faceColors[f] === undefined) {
  28647. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28648. }
  28649. if (faceUV && faceUV[f] === undefined) {
  28650. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28651. }
  28652. }
  28653. }
  28654. if (!flat) {
  28655. for (i = 0; i < data.vertex.length; i++) {
  28656. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28657. uvs.push(0, 0);
  28658. }
  28659. for (f = 0; f < nbfaces; f++) {
  28660. for (i = 0; i < data.face[f].length - 2; i++) {
  28661. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28662. }
  28663. }
  28664. }
  28665. else {
  28666. for (f = 0; f < nbfaces; f++) {
  28667. var fl = data.face[f].length; // number of vertices of the current face
  28668. ang = 2 * Math.PI / fl;
  28669. x = 0.5 * Math.tan(ang / 2);
  28670. y = 0.5;
  28671. // positions, uvs, colors
  28672. for (i = 0; i < fl; i++) {
  28673. // positions
  28674. 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);
  28675. indexes.push(index);
  28676. index++;
  28677. // uvs
  28678. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28679. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28680. uvs.push(u, v);
  28681. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28682. y = x * Math.sin(ang) + y * Math.cos(ang);
  28683. x = tmp;
  28684. // colors
  28685. if (faceColors) {
  28686. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28687. }
  28688. }
  28689. // indices from indexes
  28690. for (i = 0; i < fl - 2; i++) {
  28691. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28692. }
  28693. faceIdx += fl;
  28694. }
  28695. }
  28696. VertexData.ComputeNormals(positions, indices, normals);
  28697. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28698. var vertexData = new VertexData();
  28699. vertexData.positions = positions;
  28700. vertexData.indices = indices;
  28701. vertexData.normals = normals;
  28702. vertexData.uvs = uvs;
  28703. if (faceColors && flat) {
  28704. vertexData.colors = colors;
  28705. }
  28706. return vertexData;
  28707. };
  28708. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28709. /**
  28710. * Creates the VertexData of the Torus Knot.
  28711. */
  28712. VertexData.CreateTorusKnot = function (options) {
  28713. var indices = new Array();
  28714. var positions = new Array();
  28715. var normals = new Array();
  28716. var uvs = new Array();
  28717. var radius = options.radius || 2;
  28718. var tube = options.tube || 0.5;
  28719. var radialSegments = options.radialSegments || 32;
  28720. var tubularSegments = options.tubularSegments || 32;
  28721. var p = options.p || 2;
  28722. var q = options.q || 3;
  28723. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28724. // Helper
  28725. var getPos = function (angle) {
  28726. var cu = Math.cos(angle);
  28727. var su = Math.sin(angle);
  28728. var quOverP = q / p * angle;
  28729. var cs = Math.cos(quOverP);
  28730. var tx = radius * (2 + cs) * 0.5 * cu;
  28731. var ty = radius * (2 + cs) * su * 0.5;
  28732. var tz = radius * Math.sin(quOverP) * 0.5;
  28733. return new BABYLON.Vector3(tx, ty, tz);
  28734. };
  28735. // Vertices
  28736. var i;
  28737. var j;
  28738. for (i = 0; i <= radialSegments; i++) {
  28739. var modI = i % radialSegments;
  28740. var u = modI / radialSegments * 2 * p * Math.PI;
  28741. var p1 = getPos(u);
  28742. var p2 = getPos(u + 0.01);
  28743. var tang = p2.subtract(p1);
  28744. var n = p2.add(p1);
  28745. var bitan = BABYLON.Vector3.Cross(tang, n);
  28746. n = BABYLON.Vector3.Cross(bitan, tang);
  28747. bitan.normalize();
  28748. n.normalize();
  28749. for (j = 0; j < tubularSegments; j++) {
  28750. var modJ = j % tubularSegments;
  28751. var v = modJ / tubularSegments * 2 * Math.PI;
  28752. var cx = -tube * Math.cos(v);
  28753. var cy = tube * Math.sin(v);
  28754. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28755. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28756. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28757. uvs.push(i / radialSegments);
  28758. uvs.push(j / tubularSegments);
  28759. }
  28760. }
  28761. for (i = 0; i < radialSegments; i++) {
  28762. for (j = 0; j < tubularSegments; j++) {
  28763. var jNext = (j + 1) % tubularSegments;
  28764. var a = i * tubularSegments + j;
  28765. var b = (i + 1) * tubularSegments + j;
  28766. var c = (i + 1) * tubularSegments + jNext;
  28767. var d = i * tubularSegments + jNext;
  28768. indices.push(d);
  28769. indices.push(b);
  28770. indices.push(a);
  28771. indices.push(d);
  28772. indices.push(c);
  28773. indices.push(b);
  28774. }
  28775. }
  28776. // Normals
  28777. VertexData.ComputeNormals(positions, indices, normals);
  28778. // Sides
  28779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28780. // Result
  28781. var vertexData = new VertexData();
  28782. vertexData.indices = indices;
  28783. vertexData.positions = positions;
  28784. vertexData.normals = normals;
  28785. vertexData.uvs = uvs;
  28786. return vertexData;
  28787. };
  28788. // Tools
  28789. /**
  28790. * @param {any} - positions (number[] or Float32Array)
  28791. * @param {any} - indices (number[] or Uint16Array)
  28792. * @param {any} - normals (number[] or Float32Array)
  28793. * options (optional) :
  28794. * facetPositions : optional array of facet positions (vector3)
  28795. * facetNormals : optional array of facet normals (vector3)
  28796. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28797. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28798. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28799. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28800. * bInfo : optional bounding info, required for facetPartitioning computation
  28801. */
  28802. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28803. // temporary scalar variables
  28804. var index = 0; // facet index
  28805. var p1p2x = 0.0; // p1p2 vector x coordinate
  28806. var p1p2y = 0.0; // p1p2 vector y coordinate
  28807. var p1p2z = 0.0; // p1p2 vector z coordinate
  28808. var p3p2x = 0.0; // p3p2 vector x coordinate
  28809. var p3p2y = 0.0; // p3p2 vector y coordinate
  28810. var p3p2z = 0.0; // p3p2 vector z coordinate
  28811. var faceNormalx = 0.0; // facet normal x coordinate
  28812. var faceNormaly = 0.0; // facet normal y coordinate
  28813. var faceNormalz = 0.0; // facet normal z coordinate
  28814. var length = 0.0; // facet normal length before normalization
  28815. var v1x = 0; // vector1 x index in the positions array
  28816. var v1y = 0; // vector1 y index in the positions array
  28817. var v1z = 0; // vector1 z index in the positions array
  28818. var v2x = 0; // vector2 x index in the positions array
  28819. var v2y = 0; // vector2 y index in the positions array
  28820. var v2z = 0; // vector2 z index in the positions array
  28821. var v3x = 0; // vector3 x index in the positions array
  28822. var v3y = 0; // vector3 y index in the positions array
  28823. var v3z = 0; // vector3 z index in the positions array
  28824. var computeFacetNormals = false;
  28825. var computeFacetPositions = false;
  28826. var computeFacetPartitioning = false;
  28827. var faceNormalSign = 1;
  28828. if (options) {
  28829. computeFacetNormals = (options.facetNormals) ? true : false;
  28830. computeFacetPositions = (options.facetPositions) ? true : false;
  28831. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28832. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28833. }
  28834. // facetPartitioning reinit if needed
  28835. if (computeFacetPartitioning) {
  28836. var ox = 0; // X partitioning index for facet position
  28837. var oy = 0; // Y partinioning index for facet position
  28838. var oz = 0; // Z partinioning index for facet position
  28839. var b1x = 0; // X partitioning index for facet v1 vertex
  28840. var b1y = 0; // Y partitioning index for facet v1 vertex
  28841. var b1z = 0; // z partitioning index for facet v1 vertex
  28842. var b2x = 0; // X partitioning index for facet v2 vertex
  28843. var b2y = 0; // Y partitioning index for facet v2 vertex
  28844. var b2z = 0; // Z partitioning index for facet v2 vertex
  28845. var b3x = 0; // X partitioning index for facet v3 vertex
  28846. var b3y = 0; // Y partitioning index for facet v3 vertex
  28847. var b3z = 0; // Z partitioning index for facet v3 vertex
  28848. var block_idx_o = 0; // facet barycenter block index
  28849. var block_idx_v1 = 0; // v1 vertex block index
  28850. var block_idx_v2 = 0; // v2 vertex block index
  28851. var block_idx_v3 = 0; // v3 vertex block index
  28852. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28853. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28854. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28855. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28856. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28857. var subSq = options.subDiv.max * options.subDiv.max;
  28858. options.facetPartitioning.length = 0;
  28859. }
  28860. // reset the normals
  28861. for (index = 0; index < positions.length; index++) {
  28862. normals[index] = 0.0;
  28863. }
  28864. // Loop : 1 indice triplet = 1 facet
  28865. var nbFaces = indices.length / 3;
  28866. for (index = 0; index < nbFaces; index++) {
  28867. // get the indexes of the coordinates of each vertex of the facet
  28868. v1x = indices[index * 3] * 3;
  28869. v1y = v1x + 1;
  28870. v1z = v1x + 2;
  28871. v2x = indices[index * 3 + 1] * 3;
  28872. v2y = v2x + 1;
  28873. v2z = v2x + 2;
  28874. v3x = indices[index * 3 + 2] * 3;
  28875. v3y = v3x + 1;
  28876. v3z = v3x + 2;
  28877. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28878. p1p2y = positions[v1y] - positions[v2y];
  28879. p1p2z = positions[v1z] - positions[v2z];
  28880. p3p2x = positions[v3x] - positions[v2x];
  28881. p3p2y = positions[v3y] - positions[v2y];
  28882. p3p2z = positions[v3z] - positions[v2z];
  28883. // compute the face normal with the cross product
  28884. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28885. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28886. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28887. // normalize this normal and store it in the array facetData
  28888. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28889. length = (length === 0) ? 1.0 : length;
  28890. faceNormalx /= length;
  28891. faceNormaly /= length;
  28892. faceNormalz /= length;
  28893. if (computeFacetNormals) {
  28894. options.facetNormals[index].x = faceNormalx;
  28895. options.facetNormals[index].y = faceNormaly;
  28896. options.facetNormals[index].z = faceNormalz;
  28897. }
  28898. if (computeFacetPositions) {
  28899. // compute and the facet barycenter coordinates in the array facetPositions
  28900. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28901. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28902. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28903. }
  28904. if (computeFacetPartitioning) {
  28905. // store the facet indexes in arrays in the main facetPartitioning array :
  28906. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28907. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28908. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28909. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28910. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28911. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28912. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28913. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28914. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28915. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28916. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28917. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28918. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28919. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28920. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28921. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28922. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28923. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28924. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28925. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28926. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28927. // push each facet index in each block containing the vertex
  28928. options.facetPartitioning[block_idx_v1].push(index);
  28929. if (block_idx_v2 != block_idx_v1) {
  28930. options.facetPartitioning[block_idx_v2].push(index);
  28931. }
  28932. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28933. options.facetPartitioning[block_idx_v3].push(index);
  28934. }
  28935. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28936. options.facetPartitioning[block_idx_o].push(index);
  28937. }
  28938. }
  28939. // compute the normals anyway
  28940. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28941. normals[v1y] += faceNormaly;
  28942. normals[v1z] += faceNormalz;
  28943. normals[v2x] += faceNormalx;
  28944. normals[v2y] += faceNormaly;
  28945. normals[v2z] += faceNormalz;
  28946. normals[v3x] += faceNormalx;
  28947. normals[v3y] += faceNormaly;
  28948. normals[v3z] += faceNormalz;
  28949. }
  28950. // last normalization of each normal
  28951. for (index = 0; index < normals.length / 3; index++) {
  28952. faceNormalx = normals[index * 3];
  28953. faceNormaly = normals[index * 3 + 1];
  28954. faceNormalz = normals[index * 3 + 2];
  28955. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28956. length = (length === 0) ? 1.0 : length;
  28957. faceNormalx /= length;
  28958. faceNormaly /= length;
  28959. faceNormalz /= length;
  28960. normals[index * 3] = faceNormalx;
  28961. normals[index * 3 + 1] = faceNormaly;
  28962. normals[index * 3 + 2] = faceNormalz;
  28963. }
  28964. };
  28965. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28966. var li = indices.length;
  28967. var ln = normals.length;
  28968. var i;
  28969. var n;
  28970. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28971. switch (sideOrientation) {
  28972. case BABYLON.Mesh.FRONTSIDE:
  28973. // nothing changed
  28974. break;
  28975. case BABYLON.Mesh.BACKSIDE:
  28976. var tmp;
  28977. // indices
  28978. for (i = 0; i < li; i += 3) {
  28979. tmp = indices[i];
  28980. indices[i] = indices[i + 2];
  28981. indices[i + 2] = tmp;
  28982. }
  28983. // normals
  28984. for (n = 0; n < ln; n++) {
  28985. normals[n] = -normals[n];
  28986. }
  28987. break;
  28988. case BABYLON.Mesh.DOUBLESIDE:
  28989. // positions
  28990. var lp = positions.length;
  28991. var l = lp / 3;
  28992. for (var p = 0; p < lp; p++) {
  28993. positions[lp + p] = positions[p];
  28994. }
  28995. // indices
  28996. for (i = 0; i < li; i += 3) {
  28997. indices[i + li] = indices[i + 2] + l;
  28998. indices[i + 1 + li] = indices[i + 1] + l;
  28999. indices[i + 2 + li] = indices[i] + l;
  29000. }
  29001. // normals
  29002. for (n = 0; n < ln; n++) {
  29003. normals[ln + n] = -normals[n];
  29004. }
  29005. // uvs
  29006. var lu = uvs.length;
  29007. var u = 0;
  29008. for (u = 0; u < lu; u++) {
  29009. uvs[u + lu] = uvs[u];
  29010. }
  29011. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29012. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  29013. u = 0;
  29014. for (i = 0; i < lu / 2; i++) {
  29015. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  29016. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  29017. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  29018. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  29019. u += 2;
  29020. }
  29021. break;
  29022. }
  29023. };
  29024. /**
  29025. * Creates a new VertexData from the imported parameters.
  29026. */
  29027. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29028. var vertexData = new VertexData();
  29029. // positions
  29030. var positions = parsedVertexData.positions;
  29031. if (positions) {
  29032. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29033. }
  29034. // normals
  29035. var normals = parsedVertexData.normals;
  29036. if (normals) {
  29037. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29038. }
  29039. // tangents
  29040. var tangents = parsedVertexData.tangents;
  29041. if (tangents) {
  29042. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  29043. }
  29044. // uvs
  29045. var uvs = parsedVertexData.uvs;
  29046. if (uvs) {
  29047. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29048. }
  29049. // uv2s
  29050. var uv2s = parsedVertexData.uv2s;
  29051. if (uv2s) {
  29052. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29053. }
  29054. // uv3s
  29055. var uv3s = parsedVertexData.uv3s;
  29056. if (uv3s) {
  29057. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29058. }
  29059. // uv4s
  29060. var uv4s = parsedVertexData.uv4s;
  29061. if (uv4s) {
  29062. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29063. }
  29064. // uv5s
  29065. var uv5s = parsedVertexData.uv5s;
  29066. if (uv5s) {
  29067. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29068. }
  29069. // uv6s
  29070. var uv6s = parsedVertexData.uv6s;
  29071. if (uv6s) {
  29072. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29073. }
  29074. // colors
  29075. var colors = parsedVertexData.colors;
  29076. if (colors) {
  29077. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29078. }
  29079. // matricesIndices
  29080. var matricesIndices = parsedVertexData.matricesIndices;
  29081. if (matricesIndices) {
  29082. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29083. }
  29084. // matricesWeights
  29085. var matricesWeights = parsedVertexData.matricesWeights;
  29086. if (matricesWeights) {
  29087. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29088. }
  29089. // indices
  29090. var indices = parsedVertexData.indices;
  29091. if (indices) {
  29092. vertexData.indices = indices;
  29093. }
  29094. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29095. };
  29096. return VertexData;
  29097. }());
  29098. BABYLON.VertexData = VertexData;
  29099. })(BABYLON || (BABYLON = {}));
  29100. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  29101. var BABYLON;
  29102. (function (BABYLON) {
  29103. var Geometry = (function () {
  29104. function Geometry(id, scene, vertexData, updatable, mesh) {
  29105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29106. this._totalVertices = 0;
  29107. this._isDisposed = false;
  29108. this._indexBufferIsUpdatable = false;
  29109. this.id = id;
  29110. this._engine = scene.getEngine();
  29111. this._meshes = [];
  29112. this._scene = scene;
  29113. //Init vertex buffer cache
  29114. this._vertexBuffers = {};
  29115. this._indices = [];
  29116. this._updatable = updatable;
  29117. // vertexData
  29118. if (vertexData) {
  29119. this.setAllVerticesData(vertexData, updatable);
  29120. }
  29121. else {
  29122. this._totalVertices = 0;
  29123. this._indices = [];
  29124. }
  29125. if (this._engine.getCaps().vertexArrayObject) {
  29126. this._vertexArrayObjects = {};
  29127. }
  29128. // applyToMesh
  29129. if (mesh) {
  29130. if (mesh.getClassName() === "LinesMesh") {
  29131. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29132. this.updateExtend();
  29133. }
  29134. this.applyToMesh(mesh);
  29135. mesh.computeWorldMatrix(true);
  29136. }
  29137. }
  29138. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29139. /**
  29140. * 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
  29141. * @returns The Bias Vector
  29142. */
  29143. get: function () {
  29144. return this._boundingBias;
  29145. },
  29146. set: function (value) {
  29147. if (this._boundingBias && this._boundingBias.equals(value)) {
  29148. return;
  29149. }
  29150. this._boundingBias = value.clone();
  29151. this.updateBoundingInfo(true, null);
  29152. },
  29153. enumerable: true,
  29154. configurable: true
  29155. });
  29156. Object.defineProperty(Geometry.prototype, "extend", {
  29157. get: function () {
  29158. return this._extend;
  29159. },
  29160. enumerable: true,
  29161. configurable: true
  29162. });
  29163. Geometry.prototype.getScene = function () {
  29164. return this._scene;
  29165. };
  29166. Geometry.prototype.getEngine = function () {
  29167. return this._engine;
  29168. };
  29169. Geometry.prototype.isReady = function () {
  29170. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29171. };
  29172. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29173. get: function () {
  29174. for (var index = 0; index < this._meshes.length; index++) {
  29175. if (!this._meshes[index].doNotSerialize) {
  29176. return false;
  29177. }
  29178. }
  29179. return true;
  29180. },
  29181. enumerable: true,
  29182. configurable: true
  29183. });
  29184. Geometry.prototype._rebuild = function () {
  29185. if (this._vertexArrayObjects) {
  29186. this._vertexArrayObjects = {};
  29187. }
  29188. // Index buffer
  29189. if (this._meshes.length !== 0 && this._indices) {
  29190. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29191. }
  29192. // Vertex buffers
  29193. for (var key in this._vertexBuffers) {
  29194. var vertexBuffer = this._vertexBuffers[key];
  29195. vertexBuffer._rebuild();
  29196. }
  29197. };
  29198. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29199. vertexData.applyToGeometry(this, updatable);
  29200. this.notifyUpdate();
  29201. };
  29202. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29203. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29204. this.setVerticesBuffer(buffer);
  29205. };
  29206. Geometry.prototype.removeVerticesData = function (kind) {
  29207. if (this._vertexBuffers[kind]) {
  29208. this._vertexBuffers[kind].dispose();
  29209. delete this._vertexBuffers[kind];
  29210. }
  29211. };
  29212. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29213. var kind = buffer.getKind();
  29214. if (this._vertexBuffers[kind]) {
  29215. this._vertexBuffers[kind].dispose();
  29216. }
  29217. this._vertexBuffers[kind] = buffer;
  29218. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29219. var data = buffer.getData();
  29220. var stride = buffer.getStrideSize();
  29221. this._totalVertices = data.length / stride;
  29222. this.updateExtend(data, stride);
  29223. this._resetPointsArrayCache();
  29224. var meshes = this._meshes;
  29225. var numOfMeshes = meshes.length;
  29226. for (var index = 0; index < numOfMeshes; index++) {
  29227. var mesh = meshes[index];
  29228. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29229. mesh._createGlobalSubMesh(false);
  29230. mesh.computeWorldMatrix(true);
  29231. }
  29232. }
  29233. this.notifyUpdate(kind);
  29234. if (this._vertexArrayObjects) {
  29235. this._disposeVertexArrayObjects();
  29236. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29237. }
  29238. };
  29239. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29240. var vertexBuffer = this.getVertexBuffer(kind);
  29241. if (!vertexBuffer) {
  29242. return;
  29243. }
  29244. vertexBuffer.updateDirectly(data, offset);
  29245. this.notifyUpdate(kind);
  29246. };
  29247. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29248. var vertexBuffer = this.getVertexBuffer(kind);
  29249. if (!vertexBuffer) {
  29250. return;
  29251. }
  29252. vertexBuffer.update(data);
  29253. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29254. var stride = vertexBuffer.getStrideSize();
  29255. this._totalVertices = data.length / stride;
  29256. this.updateBoundingInfo(updateExtends, data);
  29257. }
  29258. this.notifyUpdate(kind);
  29259. };
  29260. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29261. if (updateExtends) {
  29262. this.updateExtend(data);
  29263. }
  29264. var meshes = this._meshes;
  29265. var numOfMeshes = meshes.length;
  29266. this._resetPointsArrayCache();
  29267. for (var index = 0; index < numOfMeshes; index++) {
  29268. var mesh = meshes[index];
  29269. if (updateExtends) {
  29270. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29271. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29272. var subMesh = mesh.subMeshes[subIndex];
  29273. subMesh.refreshBoundingInfo();
  29274. }
  29275. }
  29276. }
  29277. };
  29278. Geometry.prototype._bind = function (effect, indexToBind) {
  29279. if (indexToBind === void 0) { indexToBind = undefined; }
  29280. if (indexToBind === undefined) {
  29281. indexToBind = this._indexBuffer;
  29282. }
  29283. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29284. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29285. return;
  29286. }
  29287. // Using VAO
  29288. if (!this._vertexArrayObjects[effect.key]) {
  29289. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29290. }
  29291. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29292. };
  29293. Geometry.prototype.getTotalVertices = function () {
  29294. if (!this.isReady()) {
  29295. return 0;
  29296. }
  29297. return this._totalVertices;
  29298. };
  29299. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29300. var vertexBuffer = this.getVertexBuffer(kind);
  29301. if (!vertexBuffer) {
  29302. return null;
  29303. }
  29304. var orig = vertexBuffer.getData();
  29305. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29306. return orig;
  29307. }
  29308. else {
  29309. var len = orig.length;
  29310. var copy = [];
  29311. for (var i = 0; i < len; i++) {
  29312. copy.push(orig[i]);
  29313. }
  29314. return copy;
  29315. }
  29316. };
  29317. Geometry.prototype.getVertexBuffer = function (kind) {
  29318. if (!this.isReady()) {
  29319. return null;
  29320. }
  29321. return this._vertexBuffers[kind];
  29322. };
  29323. Geometry.prototype.getVertexBuffers = function () {
  29324. if (!this.isReady()) {
  29325. return null;
  29326. }
  29327. return this._vertexBuffers;
  29328. };
  29329. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29330. if (!this._vertexBuffers) {
  29331. if (this._delayInfo) {
  29332. return this._delayInfo.indexOf(kind) !== -1;
  29333. }
  29334. return false;
  29335. }
  29336. return this._vertexBuffers[kind] !== undefined;
  29337. };
  29338. Geometry.prototype.getVerticesDataKinds = function () {
  29339. var result = [];
  29340. var kind;
  29341. if (!this._vertexBuffers && this._delayInfo) {
  29342. for (kind in this._delayInfo) {
  29343. result.push(kind);
  29344. }
  29345. }
  29346. else {
  29347. for (kind in this._vertexBuffers) {
  29348. result.push(kind);
  29349. }
  29350. }
  29351. return result;
  29352. };
  29353. Geometry.prototype.updateIndices = function (indices, offset) {
  29354. if (!this._indexBuffer) {
  29355. return;
  29356. }
  29357. if (!this._indexBufferIsUpdatable) {
  29358. this.setIndices(indices, null, true);
  29359. }
  29360. else {
  29361. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  29362. }
  29363. };
  29364. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  29365. if (this._indexBuffer) {
  29366. this._engine._releaseBuffer(this._indexBuffer);
  29367. }
  29368. this._disposeVertexArrayObjects();
  29369. this._indices = indices;
  29370. this._indexBufferIsUpdatable = updatable;
  29371. if (this._meshes.length !== 0 && this._indices) {
  29372. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  29373. }
  29374. if (totalVertices != undefined) {
  29375. this._totalVertices = totalVertices;
  29376. }
  29377. var meshes = this._meshes;
  29378. var numOfMeshes = meshes.length;
  29379. for (var index = 0; index < numOfMeshes; index++) {
  29380. meshes[index]._createGlobalSubMesh(true);
  29381. }
  29382. this.notifyUpdate();
  29383. };
  29384. Geometry.prototype.getTotalIndices = function () {
  29385. if (!this.isReady()) {
  29386. return 0;
  29387. }
  29388. return this._indices.length;
  29389. };
  29390. Geometry.prototype.getIndices = function (copyWhenShared) {
  29391. if (!this.isReady()) {
  29392. return null;
  29393. }
  29394. var orig = this._indices;
  29395. if (!copyWhenShared || this._meshes.length === 1) {
  29396. return orig;
  29397. }
  29398. else {
  29399. var len = orig.length;
  29400. var copy = [];
  29401. for (var i = 0; i < len; i++) {
  29402. copy.push(orig[i]);
  29403. }
  29404. return copy;
  29405. }
  29406. };
  29407. Geometry.prototype.getIndexBuffer = function () {
  29408. if (!this.isReady()) {
  29409. return null;
  29410. }
  29411. return this._indexBuffer;
  29412. };
  29413. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29414. if (!effect || !this._vertexArrayObjects) {
  29415. return;
  29416. }
  29417. if (this._vertexArrayObjects[effect.key]) {
  29418. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29419. delete this._vertexArrayObjects[effect.key];
  29420. }
  29421. };
  29422. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29423. var meshes = this._meshes;
  29424. var index = meshes.indexOf(mesh);
  29425. if (index === -1) {
  29426. return;
  29427. }
  29428. meshes.splice(index, 1);
  29429. mesh._geometry = null;
  29430. if (meshes.length === 0 && shouldDispose) {
  29431. this.dispose();
  29432. }
  29433. };
  29434. Geometry.prototype.applyToMesh = function (mesh) {
  29435. if (mesh._geometry === this) {
  29436. return;
  29437. }
  29438. var previousGeometry = mesh._geometry;
  29439. if (previousGeometry) {
  29440. previousGeometry.releaseForMesh(mesh);
  29441. }
  29442. var meshes = this._meshes;
  29443. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29444. mesh._geometry = this;
  29445. this._scene.pushGeometry(this);
  29446. meshes.push(mesh);
  29447. if (this.isReady()) {
  29448. this._applyToMesh(mesh);
  29449. }
  29450. else {
  29451. mesh._boundingInfo = this._boundingInfo;
  29452. }
  29453. };
  29454. Geometry.prototype.updateExtend = function (data, stride) {
  29455. if (data === void 0) { data = null; }
  29456. if (!data) {
  29457. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29458. }
  29459. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29460. };
  29461. Geometry.prototype._applyToMesh = function (mesh) {
  29462. var numOfMeshes = this._meshes.length;
  29463. // vertexBuffers
  29464. for (var kind in this._vertexBuffers) {
  29465. if (numOfMeshes === 1) {
  29466. this._vertexBuffers[kind].create();
  29467. }
  29468. var buffer = this._vertexBuffers[kind].getBuffer();
  29469. if (buffer)
  29470. buffer.references = numOfMeshes;
  29471. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29472. if (!this._extend) {
  29473. this.updateExtend(this._vertexBuffers[kind].getData());
  29474. }
  29475. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29476. mesh._createGlobalSubMesh(false);
  29477. //bounding info was just created again, world matrix should be applied again.
  29478. mesh._updateBoundingInfo();
  29479. }
  29480. }
  29481. // indexBuffer
  29482. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29483. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29484. }
  29485. if (this._indexBuffer) {
  29486. this._indexBuffer.references = numOfMeshes;
  29487. }
  29488. };
  29489. Geometry.prototype.notifyUpdate = function (kind) {
  29490. if (this.onGeometryUpdated) {
  29491. this.onGeometryUpdated(this, kind);
  29492. }
  29493. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29494. var mesh = _a[_i];
  29495. mesh._markSubMeshesAsAttributesDirty();
  29496. }
  29497. };
  29498. Geometry.prototype.load = function (scene, onLoaded) {
  29499. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29500. return;
  29501. }
  29502. if (this.isReady()) {
  29503. if (onLoaded) {
  29504. onLoaded();
  29505. }
  29506. return;
  29507. }
  29508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29509. this._queueLoad(scene, onLoaded);
  29510. };
  29511. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29512. var _this = this;
  29513. scene._addPendingData(this);
  29514. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29515. _this._delayLoadingFunction(JSON.parse(data), _this);
  29516. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29517. _this._delayInfo = [];
  29518. scene._removePendingData(_this);
  29519. var meshes = _this._meshes;
  29520. var numOfMeshes = meshes.length;
  29521. for (var index = 0; index < numOfMeshes; index++) {
  29522. _this._applyToMesh(meshes[index]);
  29523. }
  29524. if (onLoaded) {
  29525. onLoaded();
  29526. }
  29527. }, function () { }, scene.database);
  29528. };
  29529. /**
  29530. * Invert the geometry to move from a right handed system to a left handed one.
  29531. */
  29532. Geometry.prototype.toLeftHanded = function () {
  29533. // Flip faces
  29534. var tIndices = this.getIndices(false);
  29535. if (tIndices != null && tIndices.length > 0) {
  29536. for (var i = 0; i < tIndices.length; i += 3) {
  29537. var tTemp = tIndices[i + 0];
  29538. tIndices[i + 0] = tIndices[i + 2];
  29539. tIndices[i + 2] = tTemp;
  29540. }
  29541. this.setIndices(tIndices);
  29542. }
  29543. // Negate position.z
  29544. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29545. if (tPositions != null && tPositions.length > 0) {
  29546. for (var i = 0; i < tPositions.length; i += 3) {
  29547. tPositions[i + 2] = -tPositions[i + 2];
  29548. }
  29549. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29550. }
  29551. // Negate normal.z
  29552. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29553. if (tNormals != null && tNormals.length > 0) {
  29554. for (var i = 0; i < tNormals.length; i += 3) {
  29555. tNormals[i + 2] = -tNormals[i + 2];
  29556. }
  29557. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29558. }
  29559. };
  29560. // Cache
  29561. Geometry.prototype._resetPointsArrayCache = function () {
  29562. this._positions = null;
  29563. };
  29564. Geometry.prototype._generatePointsArray = function () {
  29565. if (this._positions)
  29566. return true;
  29567. this._positions = [];
  29568. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29569. if (!data) {
  29570. return false;
  29571. }
  29572. for (var index = 0; index < data.length; index += 3) {
  29573. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29574. }
  29575. return true;
  29576. };
  29577. Geometry.prototype.isDisposed = function () {
  29578. return this._isDisposed;
  29579. };
  29580. Geometry.prototype._disposeVertexArrayObjects = function () {
  29581. if (this._vertexArrayObjects) {
  29582. for (var kind in this._vertexArrayObjects) {
  29583. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29584. }
  29585. this._vertexArrayObjects = {};
  29586. }
  29587. };
  29588. Geometry.prototype.dispose = function () {
  29589. var meshes = this._meshes;
  29590. var numOfMeshes = meshes.length;
  29591. var index;
  29592. for (index = 0; index < numOfMeshes; index++) {
  29593. this.releaseForMesh(meshes[index]);
  29594. }
  29595. this._meshes = [];
  29596. this._disposeVertexArrayObjects();
  29597. for (var kind in this._vertexBuffers) {
  29598. this._vertexBuffers[kind].dispose();
  29599. }
  29600. this._vertexBuffers = {};
  29601. this._totalVertices = 0;
  29602. if (this._indexBuffer) {
  29603. this._engine._releaseBuffer(this._indexBuffer);
  29604. }
  29605. this._indexBuffer = null;
  29606. this._indices = [];
  29607. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29608. this.delayLoadingFile = null;
  29609. this._delayLoadingFunction = null;
  29610. this._delayInfo = [];
  29611. this._boundingInfo = null;
  29612. this._scene.removeGeometry(this);
  29613. this._isDisposed = true;
  29614. };
  29615. Geometry.prototype.copy = function (id) {
  29616. var vertexData = new BABYLON.VertexData();
  29617. vertexData.indices = [];
  29618. var indices = this.getIndices();
  29619. for (var index = 0; index < indices.length; index++) {
  29620. vertexData.indices.push(indices[index]);
  29621. }
  29622. var updatable = false;
  29623. var stopChecking = false;
  29624. var kind;
  29625. for (kind in this._vertexBuffers) {
  29626. // using slice() to make a copy of the array and not just reference it
  29627. var data = this.getVerticesData(kind);
  29628. if (data instanceof Float32Array) {
  29629. vertexData.set(new Float32Array(data), kind);
  29630. }
  29631. else {
  29632. vertexData.set(data.slice(0), kind);
  29633. }
  29634. if (!stopChecking) {
  29635. updatable = this.getVertexBuffer(kind).isUpdatable();
  29636. stopChecking = !updatable;
  29637. }
  29638. }
  29639. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29640. geometry.delayLoadState = this.delayLoadState;
  29641. geometry.delayLoadingFile = this.delayLoadingFile;
  29642. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29643. for (kind in this._delayInfo) {
  29644. geometry._delayInfo = geometry._delayInfo || [];
  29645. geometry._delayInfo.push(kind);
  29646. }
  29647. // Bounding info
  29648. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29649. return geometry;
  29650. };
  29651. Geometry.prototype.serialize = function () {
  29652. var serializationObject = {};
  29653. serializationObject.id = this.id;
  29654. serializationObject.updatable = this._updatable;
  29655. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29656. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29657. }
  29658. return serializationObject;
  29659. };
  29660. Geometry.prototype.toNumberArray = function (origin) {
  29661. if (Array.isArray(origin)) {
  29662. return origin;
  29663. }
  29664. else {
  29665. return Array.prototype.slice.call(origin);
  29666. }
  29667. };
  29668. Geometry.prototype.serializeVerticeData = function () {
  29669. var serializationObject = this.serialize();
  29670. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29671. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29672. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29673. serializationObject.positions._updatable = true;
  29674. }
  29675. }
  29676. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29677. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29678. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29679. serializationObject.normals._updatable = true;
  29680. }
  29681. }
  29682. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29683. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29684. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29685. serializationObject.uvs._updatable = true;
  29686. }
  29687. }
  29688. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29689. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29690. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29691. serializationObject.uv2s._updatable = true;
  29692. }
  29693. }
  29694. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29695. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29696. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29697. serializationObject.uv3s._updatable = true;
  29698. }
  29699. }
  29700. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29701. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29702. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29703. serializationObject.uv4s._updatable = true;
  29704. }
  29705. }
  29706. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29707. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29708. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29709. serializationObject.uv5s._updatable = true;
  29710. }
  29711. }
  29712. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29713. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29714. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29715. serializationObject.uv6s._updatable = true;
  29716. }
  29717. }
  29718. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29719. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29720. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29721. serializationObject.colors._updatable = true;
  29722. }
  29723. }
  29724. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29725. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29726. serializationObject.matricesIndices._isExpanded = true;
  29727. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29728. serializationObject.matricesIndices._updatable = true;
  29729. }
  29730. }
  29731. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29732. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29733. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29734. serializationObject.matricesWeights._updatable = true;
  29735. }
  29736. }
  29737. serializationObject.indices = this.toNumberArray(this.getIndices());
  29738. return serializationObject;
  29739. };
  29740. // Statics
  29741. Geometry.ExtractFromMesh = function (mesh, id) {
  29742. var geometry = mesh._geometry;
  29743. if (!geometry) {
  29744. return null;
  29745. }
  29746. return geometry.copy(id);
  29747. };
  29748. /**
  29749. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29750. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29751. * Be aware Math.random() could cause collisions, but:
  29752. * "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"
  29753. */
  29754. Geometry.RandomId = function () {
  29755. return BABYLON.Tools.RandomId();
  29756. };
  29757. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29758. var scene = mesh.getScene();
  29759. // Geometry
  29760. var geometryId = parsedGeometry.geometryId;
  29761. if (geometryId) {
  29762. var geometry = scene.getGeometryByID(geometryId);
  29763. if (geometry) {
  29764. geometry.applyToMesh(mesh);
  29765. }
  29766. }
  29767. else if (parsedGeometry instanceof ArrayBuffer) {
  29768. var binaryInfo = mesh._binaryInfo;
  29769. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29770. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29771. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29772. }
  29773. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29774. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29775. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29776. }
  29777. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29778. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29779. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29780. }
  29781. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29782. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29783. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29784. }
  29785. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29786. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29787. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29788. }
  29789. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29790. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29791. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29792. }
  29793. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29794. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29795. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29796. }
  29797. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29798. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29799. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29800. }
  29801. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29802. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29803. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29804. }
  29805. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29806. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29807. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29808. }
  29809. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29810. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29812. }
  29813. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29814. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29815. mesh.setIndices(indicesData);
  29816. }
  29817. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29818. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29819. mesh.subMeshes = [];
  29820. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29821. var materialIndex = subMeshesData[(i * 5) + 0];
  29822. var verticesStart = subMeshesData[(i * 5) + 1];
  29823. var verticesCount = subMeshesData[(i * 5) + 2];
  29824. var indexStart = subMeshesData[(i * 5) + 3];
  29825. var indexCount = subMeshesData[(i * 5) + 4];
  29826. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29827. }
  29828. }
  29829. }
  29830. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29831. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29832. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29833. if (parsedGeometry.uvs) {
  29834. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29835. }
  29836. if (parsedGeometry.uvs2) {
  29837. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29838. }
  29839. if (parsedGeometry.uvs3) {
  29840. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29841. }
  29842. if (parsedGeometry.uvs4) {
  29843. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29844. }
  29845. if (parsedGeometry.uvs5) {
  29846. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29847. }
  29848. if (parsedGeometry.uvs6) {
  29849. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29850. }
  29851. if (parsedGeometry.colors) {
  29852. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29853. }
  29854. if (parsedGeometry.matricesIndices) {
  29855. if (!parsedGeometry.matricesIndices._isExpanded) {
  29856. var floatIndices = [];
  29857. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29858. var matricesIndex = parsedGeometry.matricesIndices[i];
  29859. floatIndices.push(matricesIndex & 0x000000FF);
  29860. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29861. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29862. floatIndices.push(matricesIndex >> 24);
  29863. }
  29864. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29865. }
  29866. else {
  29867. delete parsedGeometry.matricesIndices._isExpanded;
  29868. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29869. }
  29870. }
  29871. if (parsedGeometry.matricesIndicesExtra) {
  29872. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29873. var floatIndices = [];
  29874. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29875. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29876. floatIndices.push(matricesIndex & 0x000000FF);
  29877. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29878. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29879. floatIndices.push(matricesIndex >> 24);
  29880. }
  29881. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29882. }
  29883. else {
  29884. delete parsedGeometry.matricesIndices._isExpanded;
  29885. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29886. }
  29887. }
  29888. if (parsedGeometry.matricesWeights) {
  29889. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  29890. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29891. }
  29892. if (parsedGeometry.matricesWeightsExtra) {
  29893. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29894. }
  29895. mesh.setIndices(parsedGeometry.indices);
  29896. }
  29897. // SubMeshes
  29898. if (parsedGeometry.subMeshes) {
  29899. mesh.subMeshes = [];
  29900. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29901. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29902. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29903. }
  29904. }
  29905. // Flat shading
  29906. if (mesh._shouldGenerateFlatShading) {
  29907. mesh.convertToFlatShadedMesh();
  29908. delete mesh._shouldGenerateFlatShading;
  29909. }
  29910. // Update
  29911. mesh.computeWorldMatrix(true);
  29912. // Octree
  29913. if (scene['_selectionOctree']) {
  29914. scene['_selectionOctree'].addMesh(mesh);
  29915. }
  29916. };
  29917. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  29918. var epsilon = 1e-3;
  29919. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29920. return;
  29921. }
  29922. var noInfluenceBoneIndex = 0.0;
  29923. if (parsedGeometry.skeletonId > -1) {
  29924. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  29925. noInfluenceBoneIndex = skeleton.bones.length;
  29926. }
  29927. else {
  29928. return;
  29929. }
  29930. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29931. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29932. var matricesWeights = parsedGeometry.matricesWeights;
  29933. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  29934. var influencers = parsedGeometry.numBoneInfluencer;
  29935. var size = matricesWeights.length;
  29936. for (var i = 0; i < size; i += 4) {
  29937. var weight = 0.0;
  29938. var firstZeroWeight = -1;
  29939. for (var j = 0; j < 4; j++) {
  29940. var w = matricesWeights[i + j];
  29941. weight += w;
  29942. if (w < epsilon && firstZeroWeight < 0) {
  29943. firstZeroWeight = j;
  29944. }
  29945. }
  29946. if (matricesWeightsExtra) {
  29947. for (var j = 0; j < 4; j++) {
  29948. var w = matricesWeightsExtra[i + j];
  29949. weight += w;
  29950. if (w < epsilon && firstZeroWeight < 0) {
  29951. firstZeroWeight = j + 4;
  29952. }
  29953. }
  29954. }
  29955. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  29956. firstZeroWeight = influencers - 1;
  29957. }
  29958. if (weight > epsilon) {
  29959. var mweight = 1.0 / weight;
  29960. for (var j = 0; j < 4; j++) {
  29961. matricesWeights[i + j] *= mweight;
  29962. }
  29963. if (matricesWeightsExtra) {
  29964. for (var j = 0; j < 4; j++) {
  29965. matricesWeightsExtra[i + j] *= mweight;
  29966. }
  29967. }
  29968. }
  29969. else {
  29970. if (firstZeroWeight >= 4) {
  29971. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  29972. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  29973. }
  29974. else {
  29975. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  29976. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  29977. }
  29978. }
  29979. }
  29980. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  29981. if (parsedGeometry.matricesWeightsExtra) {
  29982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  29983. }
  29984. };
  29985. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29986. if (scene.getGeometryByID(parsedVertexData.id)) {
  29987. return null; // null since geometry could be something else than a box...
  29988. }
  29989. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29990. if (BABYLON.Tags) {
  29991. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29992. }
  29993. if (parsedVertexData.delayLoadingFile) {
  29994. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29995. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29996. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29997. geometry._delayInfo = [];
  29998. if (parsedVertexData.hasUVs) {
  29999. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30000. }
  30001. if (parsedVertexData.hasUVs2) {
  30002. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30003. }
  30004. if (parsedVertexData.hasUVs3) {
  30005. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30006. }
  30007. if (parsedVertexData.hasUVs4) {
  30008. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30009. }
  30010. if (parsedVertexData.hasUVs5) {
  30011. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30012. }
  30013. if (parsedVertexData.hasUVs6) {
  30014. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30015. }
  30016. if (parsedVertexData.hasColors) {
  30017. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30018. }
  30019. if (parsedVertexData.hasMatricesIndices) {
  30020. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30021. }
  30022. if (parsedVertexData.hasMatricesWeights) {
  30023. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30024. }
  30025. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  30026. }
  30027. else {
  30028. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  30029. }
  30030. scene.pushGeometry(geometry, true);
  30031. return geometry;
  30032. };
  30033. return Geometry;
  30034. }());
  30035. BABYLON.Geometry = Geometry;
  30036. /////// Primitives //////////////////////////////////////////////
  30037. (function (Geometry) {
  30038. var Primitives;
  30039. (function (Primitives) {
  30040. /// Abstract class
  30041. var _Primitive = (function (_super) {
  30042. __extends(_Primitive, _super);
  30043. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30044. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  30045. _this._canBeRegenerated = _canBeRegenerated;
  30046. _this._beingRegenerated = true;
  30047. _this.regenerate();
  30048. _this._beingRegenerated = false;
  30049. return _this;
  30050. }
  30051. _Primitive.prototype.canBeRegenerated = function () {
  30052. return this._canBeRegenerated;
  30053. };
  30054. _Primitive.prototype.regenerate = function () {
  30055. if (!this._canBeRegenerated) {
  30056. return;
  30057. }
  30058. this._beingRegenerated = true;
  30059. this.setAllVerticesData(this._regenerateVertexData(), false);
  30060. this._beingRegenerated = false;
  30061. };
  30062. _Primitive.prototype.asNewGeometry = function (id) {
  30063. return _super.prototype.copy.call(this, id);
  30064. };
  30065. // overrides
  30066. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30067. if (!this._beingRegenerated) {
  30068. return;
  30069. }
  30070. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30071. };
  30072. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30073. if (!this._beingRegenerated) {
  30074. return;
  30075. }
  30076. _super.prototype.setVerticesData.call(this, kind, data, false);
  30077. };
  30078. // to override
  30079. // protected
  30080. _Primitive.prototype._regenerateVertexData = function () {
  30081. throw new Error("Abstract method");
  30082. };
  30083. _Primitive.prototype.copy = function (id) {
  30084. throw new Error("Must be overriden in sub-classes.");
  30085. };
  30086. _Primitive.prototype.serialize = function () {
  30087. var serializationObject = _super.prototype.serialize.call(this);
  30088. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30089. return serializationObject;
  30090. };
  30091. return _Primitive;
  30092. }(Geometry));
  30093. Primitives._Primitive = _Primitive;
  30094. var Ribbon = (function (_super) {
  30095. __extends(Ribbon, _super);
  30096. // Members
  30097. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30100. _this.pathArray = pathArray;
  30101. _this.closeArray = closeArray;
  30102. _this.closePath = closePath;
  30103. _this.offset = offset;
  30104. _this.side = side;
  30105. return _this;
  30106. }
  30107. Ribbon.prototype._regenerateVertexData = function () {
  30108. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30109. };
  30110. Ribbon.prototype.copy = function (id) {
  30111. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30112. };
  30113. return Ribbon;
  30114. }(_Primitive));
  30115. Primitives.Ribbon = Ribbon;
  30116. var Box = (function (_super) {
  30117. __extends(Box, _super);
  30118. // Members
  30119. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30120. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30121. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30122. _this.size = size;
  30123. _this.side = side;
  30124. return _this;
  30125. }
  30126. Box.prototype._regenerateVertexData = function () {
  30127. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30128. };
  30129. Box.prototype.copy = function (id) {
  30130. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30131. };
  30132. Box.prototype.serialize = function () {
  30133. var serializationObject = _super.prototype.serialize.call(this);
  30134. serializationObject.size = this.size;
  30135. return serializationObject;
  30136. };
  30137. Box.Parse = function (parsedBox, scene) {
  30138. if (scene.getGeometryByID(parsedBox.id)) {
  30139. return null; // null since geometry could be something else than a box...
  30140. }
  30141. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30142. if (BABYLON.Tags) {
  30143. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30144. }
  30145. scene.pushGeometry(box, true);
  30146. return box;
  30147. };
  30148. return Box;
  30149. }(_Primitive));
  30150. Primitives.Box = Box;
  30151. var Sphere = (function (_super) {
  30152. __extends(Sphere, _super);
  30153. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30154. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30155. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30156. _this.segments = segments;
  30157. _this.diameter = diameter;
  30158. _this.side = side;
  30159. return _this;
  30160. }
  30161. Sphere.prototype._regenerateVertexData = function () {
  30162. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30163. };
  30164. Sphere.prototype.copy = function (id) {
  30165. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30166. };
  30167. Sphere.prototype.serialize = function () {
  30168. var serializationObject = _super.prototype.serialize.call(this);
  30169. serializationObject.segments = this.segments;
  30170. serializationObject.diameter = this.diameter;
  30171. return serializationObject;
  30172. };
  30173. Sphere.Parse = function (parsedSphere, scene) {
  30174. if (scene.getGeometryByID(parsedSphere.id)) {
  30175. return null; // null since geometry could be something else than a sphere...
  30176. }
  30177. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30178. if (BABYLON.Tags) {
  30179. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30180. }
  30181. scene.pushGeometry(sphere, true);
  30182. return sphere;
  30183. };
  30184. return Sphere;
  30185. }(_Primitive));
  30186. Primitives.Sphere = Sphere;
  30187. var Disc = (function (_super) {
  30188. __extends(Disc, _super);
  30189. // Members
  30190. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30193. _this.radius = radius;
  30194. _this.tessellation = tessellation;
  30195. _this.side = side;
  30196. return _this;
  30197. }
  30198. Disc.prototype._regenerateVertexData = function () {
  30199. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30200. };
  30201. Disc.prototype.copy = function (id) {
  30202. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30203. };
  30204. return Disc;
  30205. }(_Primitive));
  30206. Primitives.Disc = Disc;
  30207. var Cylinder = (function (_super) {
  30208. __extends(Cylinder, _super);
  30209. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30210. if (subdivisions === void 0) { subdivisions = 1; }
  30211. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30213. _this.height = height;
  30214. _this.diameterTop = diameterTop;
  30215. _this.diameterBottom = diameterBottom;
  30216. _this.tessellation = tessellation;
  30217. _this.subdivisions = subdivisions;
  30218. _this.side = side;
  30219. return _this;
  30220. }
  30221. Cylinder.prototype._regenerateVertexData = function () {
  30222. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30223. };
  30224. Cylinder.prototype.copy = function (id) {
  30225. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30226. };
  30227. Cylinder.prototype.serialize = function () {
  30228. var serializationObject = _super.prototype.serialize.call(this);
  30229. serializationObject.height = this.height;
  30230. serializationObject.diameterTop = this.diameterTop;
  30231. serializationObject.diameterBottom = this.diameterBottom;
  30232. serializationObject.tessellation = this.tessellation;
  30233. return serializationObject;
  30234. };
  30235. Cylinder.Parse = function (parsedCylinder, scene) {
  30236. if (scene.getGeometryByID(parsedCylinder.id)) {
  30237. return null; // null since geometry could be something else than a cylinder...
  30238. }
  30239. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30240. if (BABYLON.Tags) {
  30241. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30242. }
  30243. scene.pushGeometry(cylinder, true);
  30244. return cylinder;
  30245. };
  30246. return Cylinder;
  30247. }(_Primitive));
  30248. Primitives.Cylinder = Cylinder;
  30249. var Torus = (function (_super) {
  30250. __extends(Torus, _super);
  30251. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30252. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30253. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30254. _this.diameter = diameter;
  30255. _this.thickness = thickness;
  30256. _this.tessellation = tessellation;
  30257. _this.side = side;
  30258. return _this;
  30259. }
  30260. Torus.prototype._regenerateVertexData = function () {
  30261. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30262. };
  30263. Torus.prototype.copy = function (id) {
  30264. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30265. };
  30266. Torus.prototype.serialize = function () {
  30267. var serializationObject = _super.prototype.serialize.call(this);
  30268. serializationObject.diameter = this.diameter;
  30269. serializationObject.thickness = this.thickness;
  30270. serializationObject.tessellation = this.tessellation;
  30271. return serializationObject;
  30272. };
  30273. Torus.Parse = function (parsedTorus, scene) {
  30274. if (scene.getGeometryByID(parsedTorus.id)) {
  30275. return null; // null since geometry could be something else than a torus...
  30276. }
  30277. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30278. if (BABYLON.Tags) {
  30279. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30280. }
  30281. scene.pushGeometry(torus, true);
  30282. return torus;
  30283. };
  30284. return Torus;
  30285. }(_Primitive));
  30286. Primitives.Torus = Torus;
  30287. var Ground = (function (_super) {
  30288. __extends(Ground, _super);
  30289. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30290. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30291. _this.width = width;
  30292. _this.height = height;
  30293. _this.subdivisions = subdivisions;
  30294. return _this;
  30295. }
  30296. Ground.prototype._regenerateVertexData = function () {
  30297. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30298. };
  30299. Ground.prototype.copy = function (id) {
  30300. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30301. };
  30302. Ground.prototype.serialize = function () {
  30303. var serializationObject = _super.prototype.serialize.call(this);
  30304. serializationObject.width = this.width;
  30305. serializationObject.height = this.height;
  30306. serializationObject.subdivisions = this.subdivisions;
  30307. return serializationObject;
  30308. };
  30309. Ground.Parse = function (parsedGround, scene) {
  30310. if (scene.getGeometryByID(parsedGround.id)) {
  30311. return null; // null since geometry could be something else than a ground...
  30312. }
  30313. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30314. if (BABYLON.Tags) {
  30315. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30316. }
  30317. scene.pushGeometry(ground, true);
  30318. return ground;
  30319. };
  30320. return Ground;
  30321. }(_Primitive));
  30322. Primitives.Ground = Ground;
  30323. var TiledGround = (function (_super) {
  30324. __extends(TiledGround, _super);
  30325. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30326. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30327. _this.xmin = xmin;
  30328. _this.zmin = zmin;
  30329. _this.xmax = xmax;
  30330. _this.zmax = zmax;
  30331. _this.subdivisions = subdivisions;
  30332. _this.precision = precision;
  30333. return _this;
  30334. }
  30335. TiledGround.prototype._regenerateVertexData = function () {
  30336. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30337. };
  30338. TiledGround.prototype.copy = function (id) {
  30339. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30340. };
  30341. return TiledGround;
  30342. }(_Primitive));
  30343. Primitives.TiledGround = TiledGround;
  30344. var Plane = (function (_super) {
  30345. __extends(Plane, _super);
  30346. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30347. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30348. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30349. _this.size = size;
  30350. _this.side = side;
  30351. return _this;
  30352. }
  30353. Plane.prototype._regenerateVertexData = function () {
  30354. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30355. };
  30356. Plane.prototype.copy = function (id) {
  30357. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30358. };
  30359. Plane.prototype.serialize = function () {
  30360. var serializationObject = _super.prototype.serialize.call(this);
  30361. serializationObject.size = this.size;
  30362. return serializationObject;
  30363. };
  30364. Plane.Parse = function (parsedPlane, scene) {
  30365. if (scene.getGeometryByID(parsedPlane.id)) {
  30366. return null; // null since geometry could be something else than a ground...
  30367. }
  30368. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30369. if (BABYLON.Tags) {
  30370. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30371. }
  30372. scene.pushGeometry(plane, true);
  30373. return plane;
  30374. };
  30375. return Plane;
  30376. }(_Primitive));
  30377. Primitives.Plane = Plane;
  30378. var TorusKnot = (function (_super) {
  30379. __extends(TorusKnot, _super);
  30380. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30381. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30382. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30383. _this.radius = radius;
  30384. _this.tube = tube;
  30385. _this.radialSegments = radialSegments;
  30386. _this.tubularSegments = tubularSegments;
  30387. _this.p = p;
  30388. _this.q = q;
  30389. _this.side = side;
  30390. return _this;
  30391. }
  30392. TorusKnot.prototype._regenerateVertexData = function () {
  30393. 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 });
  30394. };
  30395. TorusKnot.prototype.copy = function (id) {
  30396. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30397. };
  30398. TorusKnot.prototype.serialize = function () {
  30399. var serializationObject = _super.prototype.serialize.call(this);
  30400. serializationObject.radius = this.radius;
  30401. serializationObject.tube = this.tube;
  30402. serializationObject.radialSegments = this.radialSegments;
  30403. serializationObject.tubularSegments = this.tubularSegments;
  30404. serializationObject.p = this.p;
  30405. serializationObject.q = this.q;
  30406. return serializationObject;
  30407. };
  30408. ;
  30409. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30410. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30411. return null; // null since geometry could be something else than a ground...
  30412. }
  30413. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30414. if (BABYLON.Tags) {
  30415. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30416. }
  30417. scene.pushGeometry(torusKnot, true);
  30418. return torusKnot;
  30419. };
  30420. return TorusKnot;
  30421. }(_Primitive));
  30422. Primitives.TorusKnot = TorusKnot;
  30423. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30424. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30425. })(BABYLON || (BABYLON = {}));
  30426. //# sourceMappingURL=babylon.geometry.js.map
  30427. var BABYLON;
  30428. (function (BABYLON) {
  30429. var PostProcessManager = (function () {
  30430. function PostProcessManager(scene) {
  30431. this._vertexBuffers = {};
  30432. this._scene = scene;
  30433. }
  30434. PostProcessManager.prototype._prepareBuffers = function () {
  30435. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30436. return;
  30437. }
  30438. // VBO
  30439. var vertices = [];
  30440. vertices.push(1, 1);
  30441. vertices.push(-1, 1);
  30442. vertices.push(-1, -1);
  30443. vertices.push(1, -1);
  30444. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30445. this._buildIndexBuffer();
  30446. };
  30447. PostProcessManager.prototype._buildIndexBuffer = function () {
  30448. // Indices
  30449. var indices = [];
  30450. indices.push(0);
  30451. indices.push(1);
  30452. indices.push(2);
  30453. indices.push(0);
  30454. indices.push(2);
  30455. indices.push(3);
  30456. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30457. };
  30458. PostProcessManager.prototype._rebuild = function () {
  30459. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30460. return;
  30461. }
  30462. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30463. this._buildIndexBuffer();
  30464. };
  30465. // Methods
  30466. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30467. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30468. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30469. return false;
  30470. }
  30471. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30472. return true;
  30473. };
  30474. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30475. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30476. var engine = this._scene.getEngine();
  30477. for (var index = 0; index < postProcesses.length; index++) {
  30478. if (index < postProcesses.length - 1) {
  30479. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30480. }
  30481. else {
  30482. if (targetTexture) {
  30483. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30484. }
  30485. else {
  30486. engine.restoreDefaultFramebuffer();
  30487. }
  30488. }
  30489. var pp = postProcesses[index];
  30490. var effect = pp.apply();
  30491. if (effect) {
  30492. pp.onBeforeRenderObservable.notifyObservers(effect);
  30493. // VBOs
  30494. this._prepareBuffers();
  30495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30496. // Draw order
  30497. engine.draw(true, 0, 6);
  30498. pp.onAfterRenderObservable.notifyObservers(effect);
  30499. }
  30500. }
  30501. // Restore depth buffer
  30502. engine.setDepthBuffer(true);
  30503. engine.setDepthWrite(true);
  30504. };
  30505. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30506. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30507. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30508. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30509. return;
  30510. }
  30511. var engine = this._scene.getEngine();
  30512. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30513. if (index < len - 1) {
  30514. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30515. }
  30516. else {
  30517. if (targetTexture) {
  30518. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30519. }
  30520. else {
  30521. engine.restoreDefaultFramebuffer();
  30522. }
  30523. }
  30524. if (doNotPresent) {
  30525. break;
  30526. }
  30527. var pp = postProcesses[index];
  30528. var effect = pp.apply();
  30529. if (effect) {
  30530. pp.onBeforeRenderObservable.notifyObservers(effect);
  30531. // VBOs
  30532. this._prepareBuffers();
  30533. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30534. // Draw order
  30535. engine.draw(true, 0, 6);
  30536. pp.onAfterRenderObservable.notifyObservers(effect);
  30537. }
  30538. }
  30539. // Restore states
  30540. engine.setDepthBuffer(true);
  30541. engine.setDepthWrite(true);
  30542. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30543. };
  30544. PostProcessManager.prototype.dispose = function () {
  30545. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30546. if (buffer) {
  30547. buffer.dispose();
  30548. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30549. }
  30550. if (this._indexBuffer) {
  30551. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30552. this._indexBuffer = null;
  30553. }
  30554. };
  30555. return PostProcessManager;
  30556. }());
  30557. BABYLON.PostProcessManager = PostProcessManager;
  30558. })(BABYLON || (BABYLON = {}));
  30559. //# sourceMappingURL=babylon.postProcessManager.js.map
  30560. var BABYLON;
  30561. (function (BABYLON) {
  30562. /**
  30563. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30564. */
  30565. var PerformanceMonitor = (function () {
  30566. /**
  30567. * constructor
  30568. * @param frameSampleSize The number of samples required to saturate the sliding window
  30569. */
  30570. function PerformanceMonitor(frameSampleSize) {
  30571. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30572. this._enabled = true;
  30573. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30574. }
  30575. /**
  30576. * Samples current frame
  30577. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30578. */
  30579. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30580. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30581. if (!this._enabled)
  30582. return;
  30583. if (this._lastFrameTimeMs != null) {
  30584. var dt = timeMs - this._lastFrameTimeMs;
  30585. this._rollingFrameTime.add(dt);
  30586. }
  30587. this._lastFrameTimeMs = timeMs;
  30588. };
  30589. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30590. /**
  30591. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30592. * @return Average frame time in milliseconds
  30593. */
  30594. get: function () {
  30595. return this._rollingFrameTime.average;
  30596. },
  30597. enumerable: true,
  30598. configurable: true
  30599. });
  30600. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30601. /**
  30602. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30603. * @return Frame time variance in milliseconds squared
  30604. */
  30605. get: function () {
  30606. return this._rollingFrameTime.variance;
  30607. },
  30608. enumerable: true,
  30609. configurable: true
  30610. });
  30611. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30612. /**
  30613. * Returns the frame time of the most recent frame
  30614. * @return Frame time in milliseconds
  30615. */
  30616. get: function () {
  30617. return this._rollingFrameTime.history(0);
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30623. /**
  30624. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30625. * @return Framerate in frames per second
  30626. */
  30627. get: function () {
  30628. return 1000.0 / this._rollingFrameTime.average;
  30629. },
  30630. enumerable: true,
  30631. configurable: true
  30632. });
  30633. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30634. /**
  30635. * Returns the average framerate in frames per second using the most recent frame time
  30636. * @return Framerate in frames per second
  30637. */
  30638. get: function () {
  30639. return 1000.0 / this._rollingFrameTime.history(0);
  30640. },
  30641. enumerable: true,
  30642. configurable: true
  30643. });
  30644. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30645. /**
  30646. * Returns true if enough samples have been taken to completely fill the sliding window
  30647. * @return true if saturated
  30648. */
  30649. get: function () {
  30650. return this._rollingFrameTime.isSaturated();
  30651. },
  30652. enumerable: true,
  30653. configurable: true
  30654. });
  30655. /**
  30656. * Enables contributions to the sliding window sample set
  30657. */
  30658. PerformanceMonitor.prototype.enable = function () {
  30659. this._enabled = true;
  30660. };
  30661. /**
  30662. * Disables contributions to the sliding window sample set
  30663. * Samples will not be interpolated over the disabled period
  30664. */
  30665. PerformanceMonitor.prototype.disable = function () {
  30666. this._enabled = false;
  30667. //clear last sample to avoid interpolating over the disabled period when next enabled
  30668. this._lastFrameTimeMs = null;
  30669. this._lastChangeTimeMs = null;
  30670. };
  30671. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30672. /**
  30673. * Returns true if sampling is enabled
  30674. * @return true if enabled
  30675. */
  30676. get: function () {
  30677. return this._enabled;
  30678. },
  30679. enumerable: true,
  30680. configurable: true
  30681. });
  30682. /**
  30683. * Resets performance monitor
  30684. */
  30685. PerformanceMonitor.prototype.reset = function () {
  30686. //clear last sample to avoid interpolating over the disabled period when next enabled
  30687. this._lastFrameTimeMs = null;
  30688. this._lastChangeTimeMs = null;
  30689. //wipe record
  30690. this._rollingFrameTime.reset();
  30691. };
  30692. return PerformanceMonitor;
  30693. }());
  30694. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30695. /**
  30696. * RollingAverage
  30697. *
  30698. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30699. */
  30700. var RollingAverage = (function () {
  30701. /**
  30702. * constructor
  30703. * @param length The number of samples required to saturate the sliding window
  30704. */
  30705. function RollingAverage(length) {
  30706. this._samples = new Array(length);
  30707. this.reset();
  30708. }
  30709. /**
  30710. * Adds a sample to the sample set
  30711. * @param v The sample value
  30712. */
  30713. RollingAverage.prototype.add = function (v) {
  30714. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30715. var delta;
  30716. //we need to check if we've already wrapped round
  30717. if (this.isSaturated()) {
  30718. //remove bottom of stack from mean
  30719. var bottomValue = this._samples[this._pos];
  30720. delta = bottomValue - this.average;
  30721. this.average -= delta / (this._sampleCount - 1);
  30722. this._m2 -= delta * (bottomValue - this.average);
  30723. }
  30724. else {
  30725. this._sampleCount++;
  30726. }
  30727. //add new value to mean
  30728. delta = v - this.average;
  30729. this.average += delta / (this._sampleCount);
  30730. this._m2 += delta * (v - this.average);
  30731. //set the new variance
  30732. this.variance = this._m2 / (this._sampleCount - 1);
  30733. this._samples[this._pos] = v;
  30734. this._pos++;
  30735. this._pos %= this._samples.length; //positive wrap around
  30736. };
  30737. /**
  30738. * Returns previously added values or null if outside of history or outside the sliding window domain
  30739. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30740. * @return Value previously recorded with add() or null if outside of range
  30741. */
  30742. RollingAverage.prototype.history = function (i) {
  30743. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30744. return null;
  30745. }
  30746. var i0 = this._wrapPosition(this._pos - 1.0);
  30747. return this._samples[this._wrapPosition(i0 - i)];
  30748. };
  30749. /**
  30750. * Returns true if enough samples have been taken to completely fill the sliding window
  30751. * @return true if sample-set saturated
  30752. */
  30753. RollingAverage.prototype.isSaturated = function () {
  30754. return this._sampleCount >= this._samples.length;
  30755. };
  30756. /**
  30757. * Resets the rolling average (equivalent to 0 samples taken so far)
  30758. */
  30759. RollingAverage.prototype.reset = function () {
  30760. this.average = 0;
  30761. this.variance = 0;
  30762. this._sampleCount = 0;
  30763. this._pos = 0;
  30764. this._m2 = 0;
  30765. };
  30766. /**
  30767. * Wraps a value around the sample range boundaries
  30768. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30769. * @return Wrapped position in sample range
  30770. */
  30771. RollingAverage.prototype._wrapPosition = function (i) {
  30772. var max = this._samples.length;
  30773. return ((i % max) + max) % max;
  30774. };
  30775. return RollingAverage;
  30776. }());
  30777. BABYLON.RollingAverage = RollingAverage;
  30778. })(BABYLON || (BABYLON = {}));
  30779. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30780. var BABYLON;
  30781. (function (BABYLON) {
  30782. /**
  30783. * This groups together the common properties used for image processing either in direct forward pass
  30784. * or through post processing effect depending on the use of the image processing pipeline in your scene
  30785. * or not.
  30786. */
  30787. var ImageProcessingConfiguration = (function () {
  30788. function ImageProcessingConfiguration() {
  30789. /**
  30790. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  30791. */
  30792. this.colorCurves = new BABYLON.ColorCurves();
  30793. this._colorCurvesEnabled = false;
  30794. this._colorGradingEnabled = false;
  30795. this._colorGradingWithGreenDepth = false;
  30796. this._colorGradingBGR = false;
  30797. this._exposure = 1.0;
  30798. this._toneMappingEnabled = false;
  30799. this._contrast = 1.0;
  30800. /**
  30801. * Vignette stretch size.
  30802. */
  30803. this.vignetteStretch = 0;
  30804. /**
  30805. * Vignette centre X Offset.
  30806. */
  30807. this.vignetteCentreX = 0;
  30808. /**
  30809. * Vignette centre Y Offset.
  30810. */
  30811. this.vignetteCentreY = 0;
  30812. /**
  30813. * Vignette weight or intensity of the vignette effect.
  30814. */
  30815. this.vignetteWeight = 1.5;
  30816. /**
  30817. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  30818. * if vignetteEnabled is set to true.
  30819. */
  30820. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  30821. /**
  30822. * Camera field of view used by the Vignette effect.
  30823. */
  30824. this.vignetteCameraFov = 0.5;
  30825. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  30826. this._vignetteEnabled = false;
  30827. this._applyByPostProcess = false;
  30828. /**
  30829. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  30830. * @type {BABYLON.Observable}
  30831. */
  30832. this.onUpdateParameters = new BABYLON.Observable();
  30833. }
  30834. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  30835. /**
  30836. * Gets wether the color curves effect is enabled.
  30837. */
  30838. get: function () {
  30839. return this._colorCurvesEnabled;
  30840. },
  30841. /**
  30842. * Sets wether the color curves effect is enabled.
  30843. */
  30844. set: function (value) {
  30845. if (this._colorCurvesEnabled === value) {
  30846. return;
  30847. }
  30848. this._colorCurvesEnabled = value;
  30849. this._updateParameters();
  30850. },
  30851. enumerable: true,
  30852. configurable: true
  30853. });
  30854. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  30855. /**
  30856. * Gets wether the color grading effect is enabled.
  30857. */
  30858. get: function () {
  30859. return this._colorGradingEnabled;
  30860. },
  30861. /**
  30862. * Sets wether the color grading effect is enabled.
  30863. */
  30864. set: function (value) {
  30865. if (this._colorGradingEnabled === value) {
  30866. return;
  30867. }
  30868. this._colorGradingEnabled = value;
  30869. this._updateParameters();
  30870. },
  30871. enumerable: true,
  30872. configurable: true
  30873. });
  30874. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  30875. /**
  30876. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  30877. */
  30878. get: function () {
  30879. return this._colorGradingWithGreenDepth;
  30880. },
  30881. /**
  30882. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  30883. */
  30884. set: function (value) {
  30885. if (this._colorGradingWithGreenDepth === value) {
  30886. return;
  30887. }
  30888. this._colorGradingWithGreenDepth = value;
  30889. this._updateParameters();
  30890. },
  30891. enumerable: true,
  30892. configurable: true
  30893. });
  30894. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  30895. /**
  30896. * Gets wether the color grading texture contains BGR values.
  30897. */
  30898. get: function () {
  30899. return this._colorGradingBGR;
  30900. },
  30901. /**
  30902. * Sets wether the color grading texture contains BGR values.
  30903. */
  30904. set: function (value) {
  30905. if (this._colorGradingBGR === value) {
  30906. return;
  30907. }
  30908. this._colorGradingBGR = value;
  30909. this._updateParameters();
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  30915. /**
  30916. * Gets the Exposure used in the effect.
  30917. */
  30918. get: function () {
  30919. return this._exposure;
  30920. },
  30921. /**
  30922. * Sets the Exposure used in the effect.
  30923. */
  30924. set: function (value) {
  30925. if (this._exposure === value) {
  30926. return;
  30927. }
  30928. this._exposure = value;
  30929. this._updateParameters();
  30930. },
  30931. enumerable: true,
  30932. configurable: true
  30933. });
  30934. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  30935. /**
  30936. * Gets wether the tone mapping effect is enabled.
  30937. */
  30938. get: function () {
  30939. return this._toneMappingEnabled;
  30940. },
  30941. /**
  30942. * Sets wether the tone mapping effect is enabled.
  30943. */
  30944. set: function (value) {
  30945. if (this._toneMappingEnabled === value) {
  30946. return;
  30947. }
  30948. this._toneMappingEnabled = value;
  30949. this._updateParameters();
  30950. },
  30951. enumerable: true,
  30952. configurable: true
  30953. });
  30954. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  30955. /**
  30956. * Gets the contrast used in the effect.
  30957. */
  30958. get: function () {
  30959. return this._contrast;
  30960. },
  30961. /**
  30962. * Sets the contrast used in the effect.
  30963. */
  30964. set: function (value) {
  30965. if (this._contrast === value) {
  30966. return;
  30967. }
  30968. this._contrast = value;
  30969. this._updateParameters();
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  30975. /**
  30976. * Gets the vignette blend mode allowing different kind of effect.
  30977. */
  30978. get: function () {
  30979. return this._vignetteBlendMode;
  30980. },
  30981. /**
  30982. * Sets the vignette blend mode allowing different kind of effect.
  30983. */
  30984. set: function (value) {
  30985. if (this._vignetteBlendMode === value) {
  30986. return;
  30987. }
  30988. this._vignetteBlendMode = value;
  30989. this._updateParameters();
  30990. },
  30991. enumerable: true,
  30992. configurable: true
  30993. });
  30994. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  30995. /**
  30996. * Gets wether the vignette effect is enabled.
  30997. */
  30998. get: function () {
  30999. return this._vignetteEnabled;
  31000. },
  31001. /**
  31002. * Sets wether the vignette effect is enabled.
  31003. */
  31004. set: function (value) {
  31005. if (this._vignetteEnabled === value) {
  31006. return;
  31007. }
  31008. this._vignetteEnabled = value;
  31009. this._updateParameters();
  31010. },
  31011. enumerable: true,
  31012. configurable: true
  31013. });
  31014. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  31015. /**
  31016. * Gets wether the image processing is applied through a post process or not.
  31017. */
  31018. get: function () {
  31019. return this._applyByPostProcess;
  31020. },
  31021. /**
  31022. * Sets wether the image processing is applied through a post process or not.
  31023. */
  31024. set: function (value) {
  31025. if (this._applyByPostProcess === value) {
  31026. return;
  31027. }
  31028. this._applyByPostProcess = value;
  31029. this._updateParameters();
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. /**
  31035. * Method called each time the image processing information changes requires to recompile the effect.
  31036. */
  31037. ImageProcessingConfiguration.prototype._updateParameters = function () {
  31038. this.onUpdateParameters.notifyObservers(this);
  31039. };
  31040. ImageProcessingConfiguration.prototype.getClassName = function () {
  31041. return "ImageProcessingConfiguration";
  31042. };
  31043. /**
  31044. * Prepare the list of uniforms associated with the Image Processing effects.
  31045. * @param uniformsList The list of uniforms used in the effect
  31046. * @param defines the list of defines currently in use
  31047. */
  31048. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  31049. if (defines.EXPOSURE) {
  31050. uniforms.push("exposureLinear");
  31051. }
  31052. if (defines.CONTRAST) {
  31053. uniforms.push("contrast");
  31054. }
  31055. if (defines.COLORGRADING) {
  31056. uniforms.push("colorTransformSettings");
  31057. }
  31058. if (defines.VIGNETTE) {
  31059. uniforms.push("vInverseScreenSize");
  31060. uniforms.push("vignetteSettings1");
  31061. uniforms.push("vignetteSettings2");
  31062. }
  31063. if (defines.COLORCURVES) {
  31064. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31065. }
  31066. };
  31067. /**
  31068. * Prepare the list of samplers associated with the Image Processing effects.
  31069. * @param uniformsList The list of uniforms used in the effect
  31070. * @param defines the list of defines currently in use
  31071. */
  31072. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  31073. if (defines.COLORGRADING) {
  31074. samplersList.push("txColorTransform");
  31075. }
  31076. };
  31077. /**
  31078. * Prepare the list of defines associated to the shader.
  31079. * @param defines the list of defines to complete
  31080. */
  31081. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  31082. if (forPostProcess === void 0) { forPostProcess = false; }
  31083. if (forPostProcess !== this.applyByPostProcess) {
  31084. defines.VIGNETTE = false;
  31085. defines.TONEMAPPING = false;
  31086. defines.CONTRAST = false;
  31087. defines.EXPOSURE = false;
  31088. defines.COLORCURVES = false;
  31089. defines.COLORGRADING = false;
  31090. defines.IMAGEPROCESSING = false;
  31091. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31092. return;
  31093. }
  31094. defines.VIGNETTE = this.vignetteEnabled;
  31095. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  31096. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  31097. defines.TONEMAPPING = this.toneMappingEnabled;
  31098. defines.CONTRAST = (this.contrast !== 1.0);
  31099. defines.EXPOSURE = (this.exposure !== 1.0);
  31100. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  31101. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  31102. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  31103. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  31104. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31105. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  31106. };
  31107. /**
  31108. * Returns true if all the image processing information are ready.
  31109. */
  31110. ImageProcessingConfiguration.prototype.isReady = function () {
  31111. // Color Grading texure can not be none blocking.
  31112. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  31113. };
  31114. /**
  31115. * Binds the image processing to the shader.
  31116. * @param effect The effect to bind to
  31117. */
  31118. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  31119. if (aspectRatio === void 0) { aspectRatio = 1; }
  31120. // Color Curves
  31121. if (this._colorCurvesEnabled) {
  31122. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  31123. }
  31124. // Vignette
  31125. if (this._vignetteEnabled) {
  31126. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  31127. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  31128. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  31129. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  31130. var vignetteScaleX = vignetteScaleY * aspectRatio;
  31131. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  31132. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  31133. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  31134. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  31135. var vignettePower = -2.0 * this.vignetteWeight;
  31136. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  31137. }
  31138. // Exposure
  31139. effect.setFloat("exposureLinear", this.exposure);
  31140. // Contrast
  31141. effect.setFloat("contrast", this.contrast);
  31142. // Color transform settings
  31143. if (this.colorGradingTexture) {
  31144. effect.setTexture("txColorTransform", this.colorGradingTexture);
  31145. var textureSize = this.colorGradingTexture.getSize().height;
  31146. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  31147. 0.5 / textureSize, // textureOffset
  31148. textureSize, // textureSize
  31149. this.colorGradingTexture.level // weight
  31150. );
  31151. }
  31152. };
  31153. /**
  31154. * Clones the current image processing instance.
  31155. * @return The cloned image processing
  31156. */
  31157. ImageProcessingConfiguration.prototype.clone = function () {
  31158. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  31159. };
  31160. /**
  31161. * Serializes the current image processing instance to a json representation.
  31162. * @return a JSON representation
  31163. */
  31164. ImageProcessingConfiguration.prototype.serialize = function () {
  31165. return BABYLON.SerializationHelper.Serialize(this);
  31166. };
  31167. /**
  31168. * Parses the image processing from a json representation.
  31169. * @param source the JSON source to parse
  31170. * @return The parsed image processing
  31171. */
  31172. ImageProcessingConfiguration.Parse = function (source) {
  31173. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  31174. };
  31175. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  31176. /**
  31177. * Used to apply the vignette as a mix with the pixel color.
  31178. */
  31179. get: function () {
  31180. return this._VIGNETTEMODE_MULTIPLY;
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  31186. /**
  31187. * Used to apply the vignette as a replacement of the pixel color.
  31188. */
  31189. get: function () {
  31190. return this._VIGNETTEMODE_OPAQUE;
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. // Static constants associated to the image processing.
  31196. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  31197. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  31198. __decorate([
  31199. BABYLON.serializeAsColorCurves()
  31200. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  31201. __decorate([
  31202. BABYLON.serialize()
  31203. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  31204. __decorate([
  31205. BABYLON.serializeAsTexture()
  31206. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  31207. __decorate([
  31208. BABYLON.serialize()
  31209. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  31210. __decorate([
  31211. BABYLON.serialize()
  31212. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  31213. __decorate([
  31214. BABYLON.serialize()
  31215. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  31216. __decorate([
  31217. BABYLON.serialize()
  31218. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  31219. __decorate([
  31220. BABYLON.serialize()
  31221. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  31222. __decorate([
  31223. BABYLON.serialize()
  31224. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  31225. __decorate([
  31226. BABYLON.serialize()
  31227. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  31228. __decorate([
  31229. BABYLON.serialize()
  31230. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  31231. __decorate([
  31232. BABYLON.serialize()
  31233. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  31234. __decorate([
  31235. BABYLON.serialize()
  31236. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  31237. __decorate([
  31238. BABYLON.serializeAsColor4()
  31239. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  31240. __decorate([
  31241. BABYLON.serialize()
  31242. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  31243. __decorate([
  31244. BABYLON.serialize()
  31245. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  31246. __decorate([
  31247. BABYLON.serialize()
  31248. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  31249. __decorate([
  31250. BABYLON.serialize()
  31251. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  31252. return ImageProcessingConfiguration;
  31253. }());
  31254. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  31255. })(BABYLON || (BABYLON = {}));
  31256. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  31257. var BABYLON;
  31258. (function (BABYLON) {
  31259. /**
  31260. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  31261. * It can help converting any input color in a desired output one. This can then be used to create effects
  31262. * from sepia, black and white to sixties or futuristic rendering...
  31263. *
  31264. * The only supported format is currently 3dl.
  31265. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  31266. */
  31267. var ColorGradingTexture = (function (_super) {
  31268. __extends(ColorGradingTexture, _super);
  31269. /**
  31270. * Instantiates a ColorGradingTexture from the following parameters.
  31271. *
  31272. * @param url The location of the color gradind data (currently only supporting 3dl)
  31273. * @param scene The scene the texture will be used in
  31274. */
  31275. function ColorGradingTexture(url, scene) {
  31276. var _this = _super.call(this, scene) || this;
  31277. if (!url) {
  31278. return _this;
  31279. }
  31280. _this._textureMatrix = BABYLON.Matrix.Identity();
  31281. _this.name = url;
  31282. _this.url = url;
  31283. _this.hasAlpha = false;
  31284. _this.isCube = false;
  31285. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31286. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31287. _this.anisotropicFilteringLevel = 1;
  31288. _this._texture = _this._getFromCache(url, true);
  31289. if (!_this._texture) {
  31290. if (!scene.useDelayedTextureLoading) {
  31291. _this.loadTexture();
  31292. }
  31293. else {
  31294. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31295. }
  31296. }
  31297. return _this;
  31298. }
  31299. /**
  31300. * Returns the texture matrix used in most of the material.
  31301. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  31302. */
  31303. ColorGradingTexture.prototype.getTextureMatrix = function () {
  31304. return this._textureMatrix;
  31305. };
  31306. /**
  31307. * Occurs when the file being loaded is a .3dl LUT file.
  31308. */
  31309. ColorGradingTexture.prototype.load3dlTexture = function () {
  31310. var _this = this;
  31311. var mipLevels = 0;
  31312. var floatArrayView = null;
  31313. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31314. this._texture = texture;
  31315. var callback = function (text) {
  31316. var data;
  31317. var tempData;
  31318. var line;
  31319. var lines = text.split('\n');
  31320. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  31321. var maxColor = 0;
  31322. for (var i = 0; i < lines.length; i++) {
  31323. line = lines[i];
  31324. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  31325. continue;
  31326. if (line.indexOf('#') === 0)
  31327. continue;
  31328. var words = line.split(" ");
  31329. if (size === 0) {
  31330. // Number of space + one
  31331. size = words.length;
  31332. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  31333. tempData = new Float32Array(size * size * size * 4);
  31334. continue;
  31335. }
  31336. if (size != 0) {
  31337. var r = Math.max(parseInt(words[0]), 0);
  31338. var g = Math.max(parseInt(words[1]), 0);
  31339. var b = Math.max(parseInt(words[2]), 0);
  31340. maxColor = Math.max(r, maxColor);
  31341. maxColor = Math.max(g, maxColor);
  31342. maxColor = Math.max(b, maxColor);
  31343. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  31344. tempData[pixelStorageIndex + 0] = r;
  31345. tempData[pixelStorageIndex + 1] = g;
  31346. tempData[pixelStorageIndex + 2] = b;
  31347. pixelIndexSlice++;
  31348. if (pixelIndexSlice % size == 0) {
  31349. pixelIndexH++;
  31350. pixelIndexSlice = 0;
  31351. if (pixelIndexH % size == 0) {
  31352. pixelIndexW++;
  31353. pixelIndexH = 0;
  31354. }
  31355. }
  31356. }
  31357. }
  31358. for (var i = 0; i < tempData.length; i++) {
  31359. if (i > 0 && (i + 1) % 4 === 0) {
  31360. data[i] = 255;
  31361. }
  31362. else {
  31363. var value = tempData[i];
  31364. data[i] = (value / maxColor * 255);
  31365. }
  31366. }
  31367. texture.updateSize(size * size, size);
  31368. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  31369. };
  31370. BABYLON.Tools.LoadFile(this.url, callback);
  31371. return this._texture;
  31372. };
  31373. /**
  31374. * Starts the loading process of the texture.
  31375. */
  31376. ColorGradingTexture.prototype.loadTexture = function () {
  31377. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  31378. this.load3dlTexture();
  31379. }
  31380. };
  31381. /**
  31382. * Clones the color gradind texture.
  31383. */
  31384. ColorGradingTexture.prototype.clone = function () {
  31385. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  31386. // Base texture
  31387. newTexture.level = this.level;
  31388. return newTexture;
  31389. };
  31390. /**
  31391. * Called during delayed load for textures.
  31392. */
  31393. ColorGradingTexture.prototype.delayLoad = function () {
  31394. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31395. return;
  31396. }
  31397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31398. this._texture = this._getFromCache(this.url, true);
  31399. if (!this._texture) {
  31400. this.loadTexture();
  31401. }
  31402. };
  31403. /**
  31404. * Parses a color grading texture serialized by Babylon.
  31405. * @param parsedTexture The texture information being parsedTexture
  31406. * @param scene The scene to load the texture in
  31407. * @param rootUrl The root url of the data assets to load
  31408. * @return A color gradind texture
  31409. */
  31410. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31411. var texture = null;
  31412. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  31413. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  31414. texture.name = parsedTexture.name;
  31415. texture.level = parsedTexture.level;
  31416. }
  31417. return texture;
  31418. };
  31419. /**
  31420. * Serializes the LUT texture to json format.
  31421. */
  31422. ColorGradingTexture.prototype.serialize = function () {
  31423. if (!this.name) {
  31424. return null;
  31425. }
  31426. var serializationObject = {};
  31427. serializationObject.name = this.name;
  31428. serializationObject.level = this.level;
  31429. serializationObject.customType = "BABYLON.ColorGradingTexture";
  31430. return serializationObject;
  31431. };
  31432. /**
  31433. * Empty line regex stored for GC.
  31434. */
  31435. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  31436. return ColorGradingTexture;
  31437. }(BABYLON.BaseTexture));
  31438. BABYLON.ColorGradingTexture = ColorGradingTexture;
  31439. })(BABYLON || (BABYLON = {}));
  31440. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  31441. var BABYLON;
  31442. (function (BABYLON) {
  31443. /**
  31444. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31445. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31446. * 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;
  31447. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31448. */
  31449. var ColorCurves = (function () {
  31450. function ColorCurves() {
  31451. this._dirty = true;
  31452. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  31453. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  31454. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31455. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  31456. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31457. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  31458. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  31459. this._globalHue = 30;
  31460. this._globalDensity = 0;
  31461. this._globalSaturation = 0;
  31462. this._globalExposure = 0;
  31463. this._highlightsHue = 30;
  31464. this._highlightsDensity = 0;
  31465. this._highlightsSaturation = 0;
  31466. this._highlightsExposure = 0;
  31467. this._midtonesHue = 30;
  31468. this._midtonesDensity = 0;
  31469. this._midtonesSaturation = 0;
  31470. this._midtonesExposure = 0;
  31471. this._shadowsHue = 30;
  31472. this._shadowsDensity = 0;
  31473. this._shadowsSaturation = 0;
  31474. this._shadowsExposure = 0;
  31475. }
  31476. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  31477. /**
  31478. * Gets the global Hue value.
  31479. * 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).
  31480. */
  31481. get: function () {
  31482. return this._globalHue;
  31483. },
  31484. /**
  31485. * Sets the global Hue value.
  31486. * 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).
  31487. */
  31488. set: function (value) {
  31489. this._globalHue = value;
  31490. this._dirty = true;
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  31496. /**
  31497. * Gets the global Density value.
  31498. * 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.
  31499. * Values less than zero provide a filter of opposite hue.
  31500. */
  31501. get: function () {
  31502. return this._globalDensity;
  31503. },
  31504. /**
  31505. * Sets the global Density value.
  31506. * 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.
  31507. * Values less than zero provide a filter of opposite hue.
  31508. */
  31509. set: function (value) {
  31510. this._globalDensity = value;
  31511. this._dirty = true;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  31517. /**
  31518. * Gets the global Saturation value.
  31519. * 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.
  31520. */
  31521. get: function () {
  31522. return this._globalSaturation;
  31523. },
  31524. /**
  31525. * Sets the global Saturation value.
  31526. * 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.
  31527. */
  31528. set: function (value) {
  31529. this._globalSaturation = value;
  31530. this._dirty = true;
  31531. },
  31532. enumerable: true,
  31533. configurable: true
  31534. });
  31535. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  31536. /**
  31537. * Gets the highlights Hue value.
  31538. * 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).
  31539. */
  31540. get: function () {
  31541. return this._highlightsHue;
  31542. },
  31543. /**
  31544. * Sets the highlights Hue value.
  31545. * 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).
  31546. */
  31547. set: function (value) {
  31548. this._highlightsHue = value;
  31549. this._dirty = true;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  31555. /**
  31556. * Gets the highlights Density value.
  31557. * 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.
  31558. * Values less than zero provide a filter of opposite hue.
  31559. */
  31560. get: function () {
  31561. return this._highlightsDensity;
  31562. },
  31563. /**
  31564. * Sets the highlights Density value.
  31565. * 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.
  31566. * Values less than zero provide a filter of opposite hue.
  31567. */
  31568. set: function (value) {
  31569. this._highlightsDensity = value;
  31570. this._dirty = true;
  31571. },
  31572. enumerable: true,
  31573. configurable: true
  31574. });
  31575. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  31576. /**
  31577. * Gets the highlights Saturation value.
  31578. * 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.
  31579. */
  31580. get: function () {
  31581. return this._highlightsSaturation;
  31582. },
  31583. /**
  31584. * Sets the highlights Saturation value.
  31585. * 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.
  31586. */
  31587. set: function (value) {
  31588. this._highlightsSaturation = value;
  31589. this._dirty = true;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  31595. /**
  31596. * Gets the highlights Exposure value.
  31597. * 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.
  31598. */
  31599. get: function () {
  31600. return this._highlightsExposure;
  31601. },
  31602. /**
  31603. * Sets the highlights Exposure value.
  31604. * 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.
  31605. */
  31606. set: function (value) {
  31607. this._highlightsExposure = value;
  31608. this._dirty = true;
  31609. },
  31610. enumerable: true,
  31611. configurable: true
  31612. });
  31613. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  31614. /**
  31615. * Gets the midtones Hue value.
  31616. * 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).
  31617. */
  31618. get: function () {
  31619. return this._midtonesHue;
  31620. },
  31621. /**
  31622. * Sets the midtones Hue value.
  31623. * 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).
  31624. */
  31625. set: function (value) {
  31626. this._midtonesHue = value;
  31627. this._dirty = true;
  31628. },
  31629. enumerable: true,
  31630. configurable: true
  31631. });
  31632. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  31633. /**
  31634. * Gets the midtones Density value.
  31635. * 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.
  31636. * Values less than zero provide a filter of opposite hue.
  31637. */
  31638. get: function () {
  31639. return this._midtonesDensity;
  31640. },
  31641. /**
  31642. * Sets the midtones Density value.
  31643. * 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.
  31644. * Values less than zero provide a filter of opposite hue.
  31645. */
  31646. set: function (value) {
  31647. this._midtonesDensity = value;
  31648. this._dirty = true;
  31649. },
  31650. enumerable: true,
  31651. configurable: true
  31652. });
  31653. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  31654. /**
  31655. * Gets the midtones Saturation value.
  31656. * 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.
  31657. */
  31658. get: function () {
  31659. return this._midtonesSaturation;
  31660. },
  31661. /**
  31662. * Sets the midtones Saturation value.
  31663. * 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.
  31664. */
  31665. set: function (value) {
  31666. this._midtonesSaturation = value;
  31667. this._dirty = true;
  31668. },
  31669. enumerable: true,
  31670. configurable: true
  31671. });
  31672. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  31673. /**
  31674. * Gets the midtones Exposure value.
  31675. * 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.
  31676. */
  31677. get: function () {
  31678. return this._midtonesExposure;
  31679. },
  31680. /**
  31681. * Sets the midtones Exposure value.
  31682. * 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.
  31683. */
  31684. set: function (value) {
  31685. this._midtonesExposure = value;
  31686. this._dirty = true;
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  31692. /**
  31693. * Gets the shadows Hue value.
  31694. * 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).
  31695. */
  31696. get: function () {
  31697. return this._shadowsHue;
  31698. },
  31699. /**
  31700. * Sets the shadows Hue value.
  31701. * 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).
  31702. */
  31703. set: function (value) {
  31704. this._shadowsHue = value;
  31705. this._dirty = true;
  31706. },
  31707. enumerable: true,
  31708. configurable: true
  31709. });
  31710. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  31711. /**
  31712. * Gets the shadows Density value.
  31713. * 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.
  31714. * Values less than zero provide a filter of opposite hue.
  31715. */
  31716. get: function () {
  31717. return this._shadowsDensity;
  31718. },
  31719. /**
  31720. * Sets the shadows Density value.
  31721. * 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.
  31722. * Values less than zero provide a filter of opposite hue.
  31723. */
  31724. set: function (value) {
  31725. this._shadowsDensity = value;
  31726. this._dirty = true;
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  31732. /**
  31733. * Gets the shadows Saturation value.
  31734. * 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.
  31735. */
  31736. get: function () {
  31737. return this._shadowsSaturation;
  31738. },
  31739. /**
  31740. * Sets the shadows Saturation value.
  31741. * 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.
  31742. */
  31743. set: function (value) {
  31744. this._shadowsSaturation = value;
  31745. this._dirty = true;
  31746. },
  31747. enumerable: true,
  31748. configurable: true
  31749. });
  31750. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  31751. /**
  31752. * Gets the shadows Exposure value.
  31753. * 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.
  31754. */
  31755. get: function () {
  31756. return this._shadowsExposure;
  31757. },
  31758. /**
  31759. * Sets the shadows Exposure value.
  31760. * 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.
  31761. */
  31762. set: function (value) {
  31763. this._shadowsExposure = value;
  31764. this._dirty = true;
  31765. },
  31766. enumerable: true,
  31767. configurable: true
  31768. });
  31769. ColorCurves.prototype.getClassName = function () {
  31770. return "ColorCurves";
  31771. };
  31772. /**
  31773. * Binds the color curves to the shader.
  31774. * @param colorCurves The color curve to bind
  31775. * @param effect The effect to bind to
  31776. */
  31777. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  31778. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  31779. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  31780. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  31781. if (colorCurves._dirty) {
  31782. colorCurves._dirty = false;
  31783. // Fill in global info.
  31784. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  31785. // Compute highlights info.
  31786. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  31787. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  31788. // Compute midtones info.
  31789. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  31790. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  31791. // Compute shadows info.
  31792. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  31793. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  31794. // Compute deltas (neutral is midtones).
  31795. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  31796. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  31797. }
  31798. if (effect) {
  31799. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  31800. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  31801. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  31802. }
  31803. };
  31804. /**
  31805. * Prepare the list of uniforms associated with the ColorCurves effects.
  31806. * @param uniformsList The list of uniforms used in the effect
  31807. */
  31808. ColorCurves.PrepareUniforms = function (uniformsList) {
  31809. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  31810. };
  31811. /**
  31812. * Returns color grading data based on a hue, density, saturation and exposure value.
  31813. * @param filterHue The hue of the color filter.
  31814. * @param filterDensity The density of the color filter.
  31815. * @param saturation The saturation.
  31816. * @param exposure The exposure.
  31817. * @param result The result data container.
  31818. */
  31819. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  31820. if (hue == null) {
  31821. return;
  31822. }
  31823. hue = ColorCurves.clamp(hue, 0, 360);
  31824. density = ColorCurves.clamp(density, -100, 100);
  31825. saturation = ColorCurves.clamp(saturation, -100, 100);
  31826. exposure = ColorCurves.clamp(exposure, -100, 100);
  31827. // Remap the slider/config filter density with non-linear mapping and also scale by half
  31828. // so that the maximum filter density is only 50% control. This provides fine control
  31829. // for small values and reasonable range.
  31830. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  31831. density *= 0.5;
  31832. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  31833. if (density < 0) {
  31834. density *= -1;
  31835. hue = (hue + 180) % 360;
  31836. }
  31837. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  31838. result.scaleToRef(2, result);
  31839. result.a = 1 + 0.01 * saturation;
  31840. };
  31841. /**
  31842. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  31843. * @param value The input slider value in range [-100,100].
  31844. * @returns Adjusted value.
  31845. */
  31846. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  31847. value /= 100;
  31848. var x = Math.abs(value);
  31849. x = Math.pow(x, 2);
  31850. if (value < 0) {
  31851. x *= -1;
  31852. }
  31853. x *= 100;
  31854. return x;
  31855. };
  31856. /**
  31857. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  31858. * @param hue The hue (H) input.
  31859. * @param saturation The saturation (S) input.
  31860. * @param brightness The brightness (B) input.
  31861. * @result An RGBA color represented as Vector4.
  31862. */
  31863. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  31864. var h = ColorCurves.clamp(hue, 0, 360);
  31865. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  31866. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  31867. if (s === 0) {
  31868. result.r = v;
  31869. result.g = v;
  31870. result.b = v;
  31871. }
  31872. else {
  31873. // sector 0 to 5
  31874. h /= 60;
  31875. var i = Math.floor(h);
  31876. // fractional part of h
  31877. var f = h - i;
  31878. var p = v * (1 - s);
  31879. var q = v * (1 - s * f);
  31880. var t = v * (1 - s * (1 - f));
  31881. switch (i) {
  31882. case 0:
  31883. result.r = v;
  31884. result.g = t;
  31885. result.b = p;
  31886. break;
  31887. case 1:
  31888. result.r = q;
  31889. result.g = v;
  31890. result.b = p;
  31891. break;
  31892. case 2:
  31893. result.r = p;
  31894. result.g = v;
  31895. result.b = t;
  31896. break;
  31897. case 3:
  31898. result.r = p;
  31899. result.g = q;
  31900. result.b = v;
  31901. break;
  31902. case 4:
  31903. result.r = t;
  31904. result.g = p;
  31905. result.b = v;
  31906. break;
  31907. default:// case 5:
  31908. result.r = v;
  31909. result.g = p;
  31910. result.b = q;
  31911. break;
  31912. }
  31913. }
  31914. result.a = 1;
  31915. };
  31916. /**
  31917. * Returns a value clamped between min and max
  31918. * @param value The value to clamp
  31919. * @param min The minimum of value
  31920. * @param max The maximum of value
  31921. * @returns The clamped value.
  31922. */
  31923. ColorCurves.clamp = function (value, min, max) {
  31924. return Math.min(Math.max(value, min), max);
  31925. };
  31926. /**
  31927. * Clones the current color curve instance.
  31928. * @return The cloned curves
  31929. */
  31930. ColorCurves.prototype.clone = function () {
  31931. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  31932. };
  31933. /**
  31934. * Serializes the current color curve instance to a json representation.
  31935. * @return a JSON representation
  31936. */
  31937. ColorCurves.prototype.serialize = function () {
  31938. return BABYLON.SerializationHelper.Serialize(this);
  31939. };
  31940. /**
  31941. * Parses the color curve from a json representation.
  31942. * @param source the JSON source to parse
  31943. * @return The parsed curves
  31944. */
  31945. ColorCurves.Parse = function (source) {
  31946. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  31947. };
  31948. __decorate([
  31949. BABYLON.serialize()
  31950. ], ColorCurves.prototype, "_globalHue", void 0);
  31951. __decorate([
  31952. BABYLON.serialize()
  31953. ], ColorCurves.prototype, "_globalDensity", void 0);
  31954. __decorate([
  31955. BABYLON.serialize()
  31956. ], ColorCurves.prototype, "_globalSaturation", void 0);
  31957. __decorate([
  31958. BABYLON.serialize()
  31959. ], ColorCurves.prototype, "_globalExposure", void 0);
  31960. __decorate([
  31961. BABYLON.serialize()
  31962. ], ColorCurves.prototype, "_highlightsHue", void 0);
  31963. __decorate([
  31964. BABYLON.serialize()
  31965. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  31966. __decorate([
  31967. BABYLON.serialize()
  31968. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  31969. __decorate([
  31970. BABYLON.serialize()
  31971. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  31972. __decorate([
  31973. BABYLON.serialize()
  31974. ], ColorCurves.prototype, "_midtonesHue", void 0);
  31975. __decorate([
  31976. BABYLON.serialize()
  31977. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  31978. __decorate([
  31979. BABYLON.serialize()
  31980. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  31981. __decorate([
  31982. BABYLON.serialize()
  31983. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  31984. return ColorCurves;
  31985. }());
  31986. BABYLON.ColorCurves = ColorCurves;
  31987. })(BABYLON || (BABYLON = {}));
  31988. //# sourceMappingURL=babylon.colorCurves.js.map
  31989. var BABYLON;
  31990. (function (BABYLON) {
  31991. var StandardMaterialDefines = (function (_super) {
  31992. __extends(StandardMaterialDefines, _super);
  31993. function StandardMaterialDefines() {
  31994. var _this = _super.call(this) || this;
  31995. _this.MAINUV1 = false;
  31996. _this.MAINUV2 = false;
  31997. _this.DIFFUSE = false;
  31998. _this.DIFFUSEDIRECTUV = 0;
  31999. _this.AMBIENT = false;
  32000. _this.AMBIENTDIRECTUV = 0;
  32001. _this.OPACITY = false;
  32002. _this.OPACITYDIRECTUV = 0;
  32003. _this.OPACITYRGB = false;
  32004. _this.REFLECTION = false;
  32005. _this.EMISSIVE = false;
  32006. _this.EMISSIVEDIRECTUV = 0;
  32007. _this.SPECULAR = false;
  32008. _this.SPECULARDIRECTUV = 0;
  32009. _this.BUMP = false;
  32010. _this.BUMPDIRECTUV = 0;
  32011. _this.PARALLAX = false;
  32012. _this.PARALLAXOCCLUSION = false;
  32013. _this.SPECULAROVERALPHA = false;
  32014. _this.CLIPPLANE = false;
  32015. _this.ALPHATEST = false;
  32016. _this.DEPTHPREPASS = false;
  32017. _this.ALPHAFROMDIFFUSE = false;
  32018. _this.POINTSIZE = false;
  32019. _this.FOG = false;
  32020. _this.SPECULARTERM = false;
  32021. _this.DIFFUSEFRESNEL = false;
  32022. _this.OPACITYFRESNEL = false;
  32023. _this.REFLECTIONFRESNEL = false;
  32024. _this.REFRACTIONFRESNEL = false;
  32025. _this.EMISSIVEFRESNEL = false;
  32026. _this.FRESNEL = false;
  32027. _this.NORMAL = false;
  32028. _this.UV1 = false;
  32029. _this.UV2 = false;
  32030. _this.VERTEXCOLOR = false;
  32031. _this.VERTEXALPHA = false;
  32032. _this.NUM_BONE_INFLUENCERS = 0;
  32033. _this.BonesPerMesh = 0;
  32034. _this.INSTANCES = false;
  32035. _this.GLOSSINESS = false;
  32036. _this.ROUGHNESS = false;
  32037. _this.EMISSIVEASILLUMINATION = false;
  32038. _this.LINKEMISSIVEWITHDIFFUSE = false;
  32039. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  32040. _this.LIGHTMAP = false;
  32041. _this.LIGHTMAPDIRECTUV = 0;
  32042. _this.USELIGHTMAPASSHADOWMAP = false;
  32043. _this.REFLECTIONMAP_3D = false;
  32044. _this.REFLECTIONMAP_SPHERICAL = false;
  32045. _this.REFLECTIONMAP_PLANAR = false;
  32046. _this.REFLECTIONMAP_CUBIC = false;
  32047. _this.REFLECTIONMAP_PROJECTION = false;
  32048. _this.REFLECTIONMAP_SKYBOX = false;
  32049. _this.REFLECTIONMAP_EXPLICIT = false;
  32050. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32051. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32052. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32053. _this.INVERTCUBICMAP = false;
  32054. _this.LOGARITHMICDEPTH = false;
  32055. _this.REFRACTION = false;
  32056. _this.REFRACTIONMAP_3D = false;
  32057. _this.REFLECTIONOVERALPHA = false;
  32058. _this.TWOSIDEDLIGHTING = false;
  32059. _this.SHADOWFLOAT = false;
  32060. _this.MORPHTARGETS = false;
  32061. _this.MORPHTARGETS_NORMAL = false;
  32062. _this.MORPHTARGETS_TANGENT = false;
  32063. _this.NUM_MORPH_INFLUENCERS = 0;
  32064. _this.IMAGEPROCESSING = false;
  32065. _this.VIGNETTE = false;
  32066. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32067. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32068. _this.TONEMAPPING = false;
  32069. _this.CONTRAST = false;
  32070. _this.COLORCURVES = false;
  32071. _this.COLORGRADING = false;
  32072. _this.SAMPLER3DGREENDEPTH = false;
  32073. _this.SAMPLER3DBGRMAP = false;
  32074. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32075. _this.EXPOSURE = false;
  32076. _this.rebuild();
  32077. return _this;
  32078. }
  32079. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  32080. var modes = [
  32081. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  32082. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  32083. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  32084. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  32085. ];
  32086. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  32087. var mode = modes_1[_i];
  32088. this[mode] = (mode === modeToEnable);
  32089. }
  32090. };
  32091. return StandardMaterialDefines;
  32092. }(BABYLON.MaterialDefines));
  32093. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  32094. var StandardMaterial = (function (_super) {
  32095. __extends(StandardMaterial, _super);
  32096. function StandardMaterial(name, scene) {
  32097. var _this = _super.call(this, name, scene) || this;
  32098. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32099. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  32100. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  32101. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32102. _this.specularPower = 64;
  32103. _this._useAlphaFromDiffuseTexture = false;
  32104. _this._useEmissiveAsIllumination = false;
  32105. _this._linkEmissiveWithDiffuse = false;
  32106. _this._useSpecularOverAlpha = false;
  32107. _this._useReflectionOverAlpha = false;
  32108. _this._disableLighting = false;
  32109. _this._useParallax = false;
  32110. _this._useParallaxOcclusion = false;
  32111. _this.parallaxScaleBias = 0.05;
  32112. _this._roughness = 0;
  32113. _this.indexOfRefraction = 0.98;
  32114. _this.invertRefractionY = true;
  32115. _this._useLightmapAsShadowmap = false;
  32116. _this._useReflectionFresnelFromSpecular = false;
  32117. _this._useGlossinessFromSpecularMapAlpha = false;
  32118. _this._maxSimultaneousLights = 4;
  32119. /**
  32120. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32121. */
  32122. _this._invertNormalMapX = false;
  32123. /**
  32124. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32125. */
  32126. _this._invertNormalMapY = false;
  32127. /**
  32128. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32129. */
  32130. _this._twoSidedLighting = false;
  32131. _this._renderTargets = new BABYLON.SmartArray(16);
  32132. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32133. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32134. // Setup the default processing configuration to the scene.
  32135. _this._attachImageProcessingConfiguration(null);
  32136. _this.getRenderTargetTextures = function () {
  32137. _this._renderTargets.reset();
  32138. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32139. _this._renderTargets.push(_this._reflectionTexture);
  32140. }
  32141. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32142. _this._renderTargets.push(_this._refractionTexture);
  32143. }
  32144. return _this._renderTargets;
  32145. };
  32146. return _this;
  32147. }
  32148. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  32149. /**
  32150. * Gets the image processing configuration used either in this material.
  32151. */
  32152. get: function () {
  32153. return this._imageProcessingConfiguration;
  32154. },
  32155. /**
  32156. * Sets the Default image processing configuration used either in the this material.
  32157. *
  32158. * If sets to null, the scene one is in use.
  32159. */
  32160. set: function (value) {
  32161. this._attachImageProcessingConfiguration(value);
  32162. // Ensure the effect will be rebuilt.
  32163. this._markAllSubMeshesAsTexturesDirty();
  32164. },
  32165. enumerable: true,
  32166. configurable: true
  32167. });
  32168. /**
  32169. * Attaches a new image processing configuration to the Standard Material.
  32170. * @param configuration
  32171. */
  32172. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32173. var _this = this;
  32174. if (configuration === this._imageProcessingConfiguration) {
  32175. return;
  32176. }
  32177. // Detaches observer.
  32178. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32179. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32180. }
  32181. // Pick the scene configuration if needed.
  32182. if (!configuration) {
  32183. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32184. }
  32185. else {
  32186. this._imageProcessingConfiguration = configuration;
  32187. }
  32188. // Attaches observer.
  32189. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32190. _this._markAllSubMeshesAsImageProcessingDirty();
  32191. });
  32192. };
  32193. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  32194. /**
  32195. * Gets wether the color curves effect is enabled.
  32196. */
  32197. get: function () {
  32198. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32199. },
  32200. /**
  32201. * Sets wether the color curves effect is enabled.
  32202. */
  32203. set: function (value) {
  32204. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32205. },
  32206. enumerable: true,
  32207. configurable: true
  32208. });
  32209. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  32210. /**
  32211. * Gets wether the color grading effect is enabled.
  32212. */
  32213. get: function () {
  32214. return this.imageProcessingConfiguration.colorGradingEnabled;
  32215. },
  32216. /**
  32217. * Gets wether the color grading effect is enabled.
  32218. */
  32219. set: function (value) {
  32220. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32221. },
  32222. enumerable: true,
  32223. configurable: true
  32224. });
  32225. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  32226. /**
  32227. * Gets wether tonemapping is enabled or not.
  32228. */
  32229. get: function () {
  32230. return this._imageProcessingConfiguration.toneMappingEnabled;
  32231. },
  32232. /**
  32233. * Sets wether tonemapping is enabled or not
  32234. */
  32235. set: function (value) {
  32236. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32237. },
  32238. enumerable: true,
  32239. configurable: true
  32240. });
  32241. ;
  32242. ;
  32243. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  32244. /**
  32245. * The camera exposure used on this material.
  32246. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32247. * This corresponds to a photographic exposure.
  32248. */
  32249. get: function () {
  32250. return this._imageProcessingConfiguration.exposure;
  32251. },
  32252. /**
  32253. * The camera exposure used on this material.
  32254. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32255. * This corresponds to a photographic exposure.
  32256. */
  32257. set: function (value) {
  32258. this._imageProcessingConfiguration.exposure = value;
  32259. },
  32260. enumerable: true,
  32261. configurable: true
  32262. });
  32263. ;
  32264. ;
  32265. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  32266. /**
  32267. * Gets The camera contrast used on this material.
  32268. */
  32269. get: function () {
  32270. return this._imageProcessingConfiguration.contrast;
  32271. },
  32272. /**
  32273. * Sets The camera contrast used on this material.
  32274. */
  32275. set: function (value) {
  32276. this._imageProcessingConfiguration.contrast = value;
  32277. },
  32278. enumerable: true,
  32279. configurable: true
  32280. });
  32281. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  32282. /**
  32283. * Gets the Color Grading 2D Lookup Texture.
  32284. */
  32285. get: function () {
  32286. return this._imageProcessingConfiguration.colorGradingTexture;
  32287. },
  32288. /**
  32289. * Sets the Color Grading 2D Lookup Texture.
  32290. */
  32291. set: function (value) {
  32292. this._imageProcessingConfiguration.colorGradingTexture = value;
  32293. },
  32294. enumerable: true,
  32295. configurable: true
  32296. });
  32297. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  32298. /**
  32299. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32300. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32301. * 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;
  32302. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32303. */
  32304. get: function () {
  32305. return this._imageProcessingConfiguration.colorCurves;
  32306. },
  32307. /**
  32308. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32309. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32310. * 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;
  32311. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32312. */
  32313. set: function (value) {
  32314. this._imageProcessingConfiguration.colorCurves = value;
  32315. },
  32316. enumerable: true,
  32317. configurable: true
  32318. });
  32319. StandardMaterial.prototype.getClassName = function () {
  32320. return "StandardMaterial";
  32321. };
  32322. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  32323. get: function () {
  32324. return this._useLogarithmicDepth;
  32325. },
  32326. set: function (value) {
  32327. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32328. this._markAllSubMeshesAsMiscDirty();
  32329. },
  32330. enumerable: true,
  32331. configurable: true
  32332. });
  32333. StandardMaterial.prototype.needAlphaBlending = function () {
  32334. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  32335. };
  32336. StandardMaterial.prototype.needAlphaTesting = function () {
  32337. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  32338. };
  32339. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  32340. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  32341. };
  32342. StandardMaterial.prototype.getAlphaTestTexture = function () {
  32343. return this._diffuseTexture;
  32344. };
  32345. /**
  32346. * Child classes can use it to update shaders
  32347. */
  32348. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32349. if (this.isFrozen) {
  32350. if (this._wasPreviouslyReady && subMesh.effect) {
  32351. return true;
  32352. }
  32353. }
  32354. if (!subMesh._materialDefines) {
  32355. subMesh._materialDefines = new StandardMaterialDefines();
  32356. }
  32357. var scene = this.getScene();
  32358. var defines = subMesh._materialDefines;
  32359. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32360. if (defines._renderId === scene.getRenderId()) {
  32361. return true;
  32362. }
  32363. }
  32364. var engine = scene.getEngine();
  32365. // Lights
  32366. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32367. // Textures
  32368. if (defines._areTexturesDirty) {
  32369. defines._needUVs = false;
  32370. defines.MAINUV1 = false;
  32371. defines.MAINUV2 = false;
  32372. if (scene.texturesEnabled) {
  32373. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32374. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  32375. return false;
  32376. }
  32377. else {
  32378. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  32379. }
  32380. }
  32381. else {
  32382. defines.DIFFUSE = false;
  32383. }
  32384. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32385. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32386. return false;
  32387. }
  32388. else {
  32389. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32390. }
  32391. }
  32392. else {
  32393. defines.AMBIENT = false;
  32394. }
  32395. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32396. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32397. return false;
  32398. }
  32399. else {
  32400. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32401. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32402. }
  32403. }
  32404. else {
  32405. defines.OPACITY = false;
  32406. }
  32407. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32408. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  32409. return false;
  32410. }
  32411. else {
  32412. defines._needNormals = true;
  32413. defines.REFLECTION = true;
  32414. defines.ROUGHNESS = (this._roughness > 0);
  32415. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  32416. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  32417. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  32418. switch (this._reflectionTexture.coordinatesMode) {
  32419. case BABYLON.Texture.CUBIC_MODE:
  32420. case BABYLON.Texture.INVCUBIC_MODE:
  32421. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  32422. break;
  32423. case BABYLON.Texture.EXPLICIT_MODE:
  32424. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  32425. break;
  32426. case BABYLON.Texture.PLANAR_MODE:
  32427. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  32428. break;
  32429. case BABYLON.Texture.PROJECTION_MODE:
  32430. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  32431. break;
  32432. case BABYLON.Texture.SKYBOX_MODE:
  32433. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  32434. break;
  32435. case BABYLON.Texture.SPHERICAL_MODE:
  32436. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  32437. break;
  32438. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32439. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  32440. break;
  32441. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32442. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  32443. break;
  32444. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32445. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  32446. break;
  32447. }
  32448. }
  32449. }
  32450. else {
  32451. defines.REFLECTION = false;
  32452. }
  32453. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32454. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32455. return false;
  32456. }
  32457. else {
  32458. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32459. }
  32460. }
  32461. else {
  32462. defines.EMISSIVE = false;
  32463. }
  32464. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32465. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32466. return false;
  32467. }
  32468. else {
  32469. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32470. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32471. }
  32472. }
  32473. else {
  32474. defines.LIGHTMAP = false;
  32475. }
  32476. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32477. if (!this._specularTexture.isReadyOrNotBlocking()) {
  32478. return false;
  32479. }
  32480. else {
  32481. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  32482. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  32483. }
  32484. }
  32485. else {
  32486. defines.SPECULAR = false;
  32487. }
  32488. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  32489. // Bump texure can not be not blocking.
  32490. if (!this._bumpTexture.isReady()) {
  32491. return false;
  32492. }
  32493. else {
  32494. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32495. defines.PARALLAX = this._useParallax;
  32496. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  32497. }
  32498. }
  32499. else {
  32500. defines.BUMP = false;
  32501. }
  32502. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32503. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  32504. return false;
  32505. }
  32506. else {
  32507. defines._needUVs = true;
  32508. defines.REFRACTION = true;
  32509. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  32510. }
  32511. }
  32512. else {
  32513. defines.REFRACTION = false;
  32514. }
  32515. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  32516. }
  32517. else {
  32518. defines.DIFFUSE = false;
  32519. defines.AMBIENT = false;
  32520. defines.OPACITY = false;
  32521. defines.REFLECTION = false;
  32522. defines.EMISSIVE = false;
  32523. defines.LIGHTMAP = false;
  32524. defines.BUMP = false;
  32525. defines.REFRACTION = false;
  32526. }
  32527. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  32528. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  32529. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  32530. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  32531. }
  32532. if (defines._areImageProcessingDirty) {
  32533. if (!this._imageProcessingConfiguration.isReady()) {
  32534. return false;
  32535. }
  32536. this._imageProcessingConfiguration.prepareDefines(defines);
  32537. }
  32538. if (defines._areFresnelDirty) {
  32539. if (StandardMaterial.FresnelEnabled) {
  32540. // Fresnel
  32541. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  32542. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  32543. this._reflectionFresnelParameters) {
  32544. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  32545. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  32546. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  32547. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  32548. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  32549. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  32550. defines._needNormals = true;
  32551. defines.FRESNEL = true;
  32552. }
  32553. }
  32554. else {
  32555. defines.FRESNEL = false;
  32556. }
  32557. }
  32558. // Misc.
  32559. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32560. // Attribs
  32561. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  32562. // Values that need to be evaluated on every frame
  32563. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  32564. // Get correct effect
  32565. if (defines.isDirty) {
  32566. defines.markAsProcessed();
  32567. scene.resetCachedMaterial();
  32568. // Fallbacks
  32569. var fallbacks = new BABYLON.EffectFallbacks();
  32570. if (defines.REFLECTION) {
  32571. fallbacks.addFallback(0, "REFLECTION");
  32572. }
  32573. if (defines.SPECULAR) {
  32574. fallbacks.addFallback(0, "SPECULAR");
  32575. }
  32576. if (defines.BUMP) {
  32577. fallbacks.addFallback(0, "BUMP");
  32578. }
  32579. if (defines.PARALLAX) {
  32580. fallbacks.addFallback(1, "PARALLAX");
  32581. }
  32582. if (defines.PARALLAXOCCLUSION) {
  32583. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32584. }
  32585. if (defines.SPECULAROVERALPHA) {
  32586. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32587. }
  32588. if (defines.FOG) {
  32589. fallbacks.addFallback(1, "FOG");
  32590. }
  32591. if (defines.POINTSIZE) {
  32592. fallbacks.addFallback(0, "POINTSIZE");
  32593. }
  32594. if (defines.LOGARITHMICDEPTH) {
  32595. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32596. }
  32597. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32598. if (defines.SPECULARTERM) {
  32599. fallbacks.addFallback(0, "SPECULARTERM");
  32600. }
  32601. if (defines.DIFFUSEFRESNEL) {
  32602. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  32603. }
  32604. if (defines.OPACITYFRESNEL) {
  32605. fallbacks.addFallback(2, "OPACITYFRESNEL");
  32606. }
  32607. if (defines.REFLECTIONFRESNEL) {
  32608. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  32609. }
  32610. if (defines.EMISSIVEFRESNEL) {
  32611. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  32612. }
  32613. if (defines.FRESNEL) {
  32614. fallbacks.addFallback(4, "FRESNEL");
  32615. }
  32616. //Attributes
  32617. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32618. if (defines.NORMAL) {
  32619. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32620. }
  32621. if (defines.UV1) {
  32622. attribs.push(BABYLON.VertexBuffer.UVKind);
  32623. }
  32624. if (defines.UV2) {
  32625. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32626. }
  32627. if (defines.VERTEXCOLOR) {
  32628. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32629. }
  32630. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32631. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32632. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32633. var shaderName = "default";
  32634. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  32635. "vFogInfos", "vFogColor", "pointSize",
  32636. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32637. "mBones",
  32638. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32639. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  32640. "logarithmicDepthConstant", "vTangentSpaceParams"
  32641. ];
  32642. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  32643. var uniformBuffers = ["Material", "Scene"];
  32644. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32645. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32646. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32647. uniformsNames: uniforms,
  32648. uniformBuffersNames: uniformBuffers,
  32649. samplers: samplers,
  32650. defines: defines,
  32651. maxSimultaneousLights: this._maxSimultaneousLights
  32652. });
  32653. if (this.customShaderNameResolve) {
  32654. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  32655. }
  32656. var join = defines.toString();
  32657. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  32658. attributes: attribs,
  32659. uniformsNames: uniforms,
  32660. uniformBuffersNames: uniformBuffers,
  32661. samplers: samplers,
  32662. defines: join,
  32663. fallbacks: fallbacks,
  32664. onCompiled: this.onCompiled,
  32665. onError: this.onError,
  32666. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32667. }, engine), defines);
  32668. this.buildUniformLayout();
  32669. }
  32670. if (!subMesh.effect.isReady()) {
  32671. return false;
  32672. }
  32673. defines._renderId = scene.getRenderId();
  32674. this._wasPreviouslyReady = true;
  32675. return true;
  32676. };
  32677. StandardMaterial.prototype.buildUniformLayout = function () {
  32678. // Order is important !
  32679. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  32680. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  32681. this._uniformBuffer.addUniform("opacityParts", 4);
  32682. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  32683. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  32684. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  32685. this._uniformBuffer.addUniform("refractionRightColor", 4);
  32686. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  32687. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  32688. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  32689. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  32690. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32691. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32692. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32693. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32694. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  32695. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32696. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  32697. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32698. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32699. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32700. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32701. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32702. this._uniformBuffer.addUniform("specularMatrix", 16);
  32703. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32704. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  32705. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32706. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32707. this._uniformBuffer.addUniform("vSpecularColor", 4);
  32708. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32709. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  32710. this._uniformBuffer.addUniform("pointSize", 1);
  32711. this._uniformBuffer.create();
  32712. };
  32713. StandardMaterial.prototype.unbind = function () {
  32714. if (this._activeEffect) {
  32715. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32716. this._activeEffect.setTexture("reflection2DSampler", null);
  32717. }
  32718. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32719. this._activeEffect.setTexture("refraction2DSampler", null);
  32720. }
  32721. }
  32722. _super.prototype.unbind.call(this);
  32723. };
  32724. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32725. var scene = this.getScene();
  32726. var defines = subMesh._materialDefines;
  32727. if (!defines) {
  32728. return;
  32729. }
  32730. var effect = subMesh.effect;
  32731. this._activeEffect = effect;
  32732. // Matrices
  32733. this.bindOnlyWorldMatrix(world);
  32734. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32735. // Bones
  32736. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  32737. if (mustRebind) {
  32738. this._uniformBuffer.bindToEffect(effect, "Material");
  32739. this.bindViewProjection(effect);
  32740. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32741. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  32742. // Fresnel
  32743. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  32744. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  32745. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  32746. }
  32747. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  32748. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  32749. }
  32750. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  32751. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  32752. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  32753. }
  32754. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  32755. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  32756. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  32757. }
  32758. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  32759. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  32760. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  32761. }
  32762. }
  32763. // Textures
  32764. if (scene.texturesEnabled) {
  32765. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32766. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  32767. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  32768. }
  32769. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32770. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  32771. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32772. }
  32773. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32774. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32775. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32776. }
  32777. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32778. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  32779. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  32780. }
  32781. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32782. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32783. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32784. }
  32785. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32786. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32787. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32788. }
  32789. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32790. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  32791. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  32792. }
  32793. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32794. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  32795. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32796. if (scene._mirroredCameraPosition) {
  32797. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 1.0 : -1.0);
  32798. }
  32799. else {
  32800. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? -1.0 : 1.0);
  32801. }
  32802. }
  32803. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32804. var depth = 1.0;
  32805. if (!this._refractionTexture.isCube) {
  32806. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  32807. if (this._refractionTexture.depth) {
  32808. depth = this._refractionTexture.depth;
  32809. }
  32810. }
  32811. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  32812. }
  32813. }
  32814. // Point size
  32815. if (this.pointsCloud) {
  32816. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32817. }
  32818. if (defines.SPECULARTERM) {
  32819. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  32820. }
  32821. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  32822. // Diffuse
  32823. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  32824. }
  32825. // Textures
  32826. if (scene.texturesEnabled) {
  32827. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32828. effect.setTexture("diffuseSampler", this._diffuseTexture);
  32829. }
  32830. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32831. effect.setTexture("ambientSampler", this._ambientTexture);
  32832. }
  32833. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32834. effect.setTexture("opacitySampler", this._opacityTexture);
  32835. }
  32836. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32837. if (this._reflectionTexture.isCube) {
  32838. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  32839. }
  32840. else {
  32841. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  32842. }
  32843. }
  32844. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32845. effect.setTexture("emissiveSampler", this._emissiveTexture);
  32846. }
  32847. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32848. effect.setTexture("lightmapSampler", this._lightmapTexture);
  32849. }
  32850. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32851. effect.setTexture("specularSampler", this._specularTexture);
  32852. }
  32853. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32854. effect.setTexture("bumpSampler", this._bumpTexture);
  32855. }
  32856. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32857. var depth = 1.0;
  32858. if (this._refractionTexture.isCube) {
  32859. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  32860. }
  32861. else {
  32862. effect.setTexture("refraction2DSampler", this._refractionTexture);
  32863. }
  32864. }
  32865. }
  32866. // Clip plane
  32867. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  32868. // Colors
  32869. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  32870. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  32871. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32872. }
  32873. if (mustRebind || !this.isFrozen) {
  32874. // Lights
  32875. if (scene.lightsEnabled && !this._disableLighting) {
  32876. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  32877. }
  32878. // View
  32879. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  32880. this.bindView(effect);
  32881. }
  32882. // Fog
  32883. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  32884. // Morph targets
  32885. if (defines.NUM_MORPH_INFLUENCERS) {
  32886. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  32887. }
  32888. // Log. depth
  32889. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  32890. // image processing
  32891. this._imageProcessingConfiguration.bind(this._activeEffect);
  32892. }
  32893. this._uniformBuffer.update();
  32894. this._afterBind(mesh, this._activeEffect);
  32895. };
  32896. StandardMaterial.prototype.getAnimatables = function () {
  32897. var results = [];
  32898. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  32899. results.push(this._diffuseTexture);
  32900. }
  32901. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32902. results.push(this._ambientTexture);
  32903. }
  32904. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32905. results.push(this._opacityTexture);
  32906. }
  32907. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32908. results.push(this._reflectionTexture);
  32909. }
  32910. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32911. results.push(this._emissiveTexture);
  32912. }
  32913. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  32914. results.push(this._specularTexture);
  32915. }
  32916. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32917. results.push(this._bumpTexture);
  32918. }
  32919. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32920. results.push(this._lightmapTexture);
  32921. }
  32922. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32923. results.push(this._refractionTexture);
  32924. }
  32925. return results;
  32926. };
  32927. StandardMaterial.prototype.getActiveTextures = function () {
  32928. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32929. if (this._diffuseTexture) {
  32930. activeTextures.push(this._diffuseTexture);
  32931. }
  32932. if (this._ambientTexture) {
  32933. activeTextures.push(this._ambientTexture);
  32934. }
  32935. if (this._opacityTexture) {
  32936. activeTextures.push(this._opacityTexture);
  32937. }
  32938. if (this._reflectionTexture) {
  32939. activeTextures.push(this._reflectionTexture);
  32940. }
  32941. if (this._emissiveTexture) {
  32942. activeTextures.push(this._emissiveTexture);
  32943. }
  32944. if (this._specularTexture) {
  32945. activeTextures.push(this._specularTexture);
  32946. }
  32947. if (this._bumpTexture) {
  32948. activeTextures.push(this._bumpTexture);
  32949. }
  32950. if (this._lightmapTexture) {
  32951. activeTextures.push(this._lightmapTexture);
  32952. }
  32953. if (this._refractionTexture) {
  32954. activeTextures.push(this._refractionTexture);
  32955. }
  32956. return activeTextures;
  32957. };
  32958. StandardMaterial.prototype.hasTexture = function (texture) {
  32959. if (_super.prototype.hasTexture.call(this, texture)) {
  32960. return true;
  32961. }
  32962. if (this._diffuseTexture === texture) {
  32963. return true;
  32964. }
  32965. if (this._ambientTexture === texture) {
  32966. return true;
  32967. }
  32968. if (this._opacityTexture === texture) {
  32969. return true;
  32970. }
  32971. if (this._reflectionTexture === texture) {
  32972. return true;
  32973. }
  32974. if (this._emissiveTexture === texture) {
  32975. return true;
  32976. }
  32977. if (this._specularTexture === texture) {
  32978. return true;
  32979. }
  32980. if (this._bumpTexture === texture) {
  32981. return true;
  32982. }
  32983. if (this._lightmapTexture === texture) {
  32984. return true;
  32985. }
  32986. if (this._refractionTexture === texture) {
  32987. return true;
  32988. }
  32989. return false;
  32990. };
  32991. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32992. if (forceDisposeTextures) {
  32993. if (this._diffuseTexture) {
  32994. this._diffuseTexture.dispose();
  32995. }
  32996. if (this._ambientTexture) {
  32997. this._ambientTexture.dispose();
  32998. }
  32999. if (this._opacityTexture) {
  33000. this._opacityTexture.dispose();
  33001. }
  33002. if (this._reflectionTexture) {
  33003. this._reflectionTexture.dispose();
  33004. }
  33005. if (this._emissiveTexture) {
  33006. this._emissiveTexture.dispose();
  33007. }
  33008. if (this._specularTexture) {
  33009. this._specularTexture.dispose();
  33010. }
  33011. if (this._bumpTexture) {
  33012. this._bumpTexture.dispose();
  33013. }
  33014. if (this._lightmapTexture) {
  33015. this._lightmapTexture.dispose();
  33016. }
  33017. if (this._refractionTexture) {
  33018. this._refractionTexture.dispose();
  33019. }
  33020. }
  33021. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33022. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33023. }
  33024. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  33025. };
  33026. StandardMaterial.prototype.clone = function (name) {
  33027. var _this = this;
  33028. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  33029. result.name = name;
  33030. result.id = name;
  33031. return result;
  33032. };
  33033. StandardMaterial.prototype.serialize = function () {
  33034. return BABYLON.SerializationHelper.Serialize(this);
  33035. };
  33036. // Statics
  33037. StandardMaterial.Parse = function (source, scene, rootUrl) {
  33038. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  33039. };
  33040. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  33041. get: function () {
  33042. return StandardMaterial._DiffuseTextureEnabled;
  33043. },
  33044. set: function (value) {
  33045. if (StandardMaterial._DiffuseTextureEnabled === value) {
  33046. return;
  33047. }
  33048. StandardMaterial._DiffuseTextureEnabled = value;
  33049. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33050. },
  33051. enumerable: true,
  33052. configurable: true
  33053. });
  33054. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  33055. get: function () {
  33056. return StandardMaterial._AmbientTextureEnabled;
  33057. },
  33058. set: function (value) {
  33059. if (StandardMaterial._AmbientTextureEnabled === value) {
  33060. return;
  33061. }
  33062. StandardMaterial._AmbientTextureEnabled = value;
  33063. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33064. },
  33065. enumerable: true,
  33066. configurable: true
  33067. });
  33068. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  33069. get: function () {
  33070. return StandardMaterial._OpacityTextureEnabled;
  33071. },
  33072. set: function (value) {
  33073. if (StandardMaterial._OpacityTextureEnabled === value) {
  33074. return;
  33075. }
  33076. StandardMaterial._OpacityTextureEnabled = value;
  33077. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33078. },
  33079. enumerable: true,
  33080. configurable: true
  33081. });
  33082. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  33083. get: function () {
  33084. return StandardMaterial._ReflectionTextureEnabled;
  33085. },
  33086. set: function (value) {
  33087. if (StandardMaterial._ReflectionTextureEnabled === value) {
  33088. return;
  33089. }
  33090. StandardMaterial._ReflectionTextureEnabled = value;
  33091. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33092. },
  33093. enumerable: true,
  33094. configurable: true
  33095. });
  33096. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  33097. get: function () {
  33098. return StandardMaterial._EmissiveTextureEnabled;
  33099. },
  33100. set: function (value) {
  33101. if (StandardMaterial._EmissiveTextureEnabled === value) {
  33102. return;
  33103. }
  33104. StandardMaterial._EmissiveTextureEnabled = value;
  33105. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33106. },
  33107. enumerable: true,
  33108. configurable: true
  33109. });
  33110. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  33111. get: function () {
  33112. return StandardMaterial._SpecularTextureEnabled;
  33113. },
  33114. set: function (value) {
  33115. if (StandardMaterial._SpecularTextureEnabled === value) {
  33116. return;
  33117. }
  33118. StandardMaterial._SpecularTextureEnabled = value;
  33119. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33120. },
  33121. enumerable: true,
  33122. configurable: true
  33123. });
  33124. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  33125. get: function () {
  33126. return StandardMaterial._BumpTextureEnabled;
  33127. },
  33128. set: function (value) {
  33129. if (StandardMaterial._BumpTextureEnabled === value) {
  33130. return;
  33131. }
  33132. StandardMaterial._BumpTextureEnabled = value;
  33133. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33134. },
  33135. enumerable: true,
  33136. configurable: true
  33137. });
  33138. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  33139. get: function () {
  33140. return StandardMaterial._LightmapTextureEnabled;
  33141. },
  33142. set: function (value) {
  33143. if (StandardMaterial._LightmapTextureEnabled === value) {
  33144. return;
  33145. }
  33146. StandardMaterial._LightmapTextureEnabled = value;
  33147. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33148. },
  33149. enumerable: true,
  33150. configurable: true
  33151. });
  33152. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  33153. get: function () {
  33154. return StandardMaterial._RefractionTextureEnabled;
  33155. },
  33156. set: function (value) {
  33157. if (StandardMaterial._RefractionTextureEnabled === value) {
  33158. return;
  33159. }
  33160. StandardMaterial._RefractionTextureEnabled = value;
  33161. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33162. },
  33163. enumerable: true,
  33164. configurable: true
  33165. });
  33166. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  33167. get: function () {
  33168. return StandardMaterial._ColorGradingTextureEnabled;
  33169. },
  33170. set: function (value) {
  33171. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  33172. return;
  33173. }
  33174. StandardMaterial._ColorGradingTextureEnabled = value;
  33175. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33176. },
  33177. enumerable: true,
  33178. configurable: true
  33179. });
  33180. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  33181. get: function () {
  33182. return StandardMaterial._FresnelEnabled;
  33183. },
  33184. set: function (value) {
  33185. if (StandardMaterial._FresnelEnabled === value) {
  33186. return;
  33187. }
  33188. StandardMaterial._FresnelEnabled = value;
  33189. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  33190. },
  33191. enumerable: true,
  33192. configurable: true
  33193. });
  33194. // Flags used to enable or disable a type of texture for all Standard Materials
  33195. StandardMaterial._DiffuseTextureEnabled = true;
  33196. StandardMaterial._AmbientTextureEnabled = true;
  33197. StandardMaterial._OpacityTextureEnabled = true;
  33198. StandardMaterial._ReflectionTextureEnabled = true;
  33199. StandardMaterial._EmissiveTextureEnabled = true;
  33200. StandardMaterial._SpecularTextureEnabled = true;
  33201. StandardMaterial._BumpTextureEnabled = true;
  33202. StandardMaterial._LightmapTextureEnabled = true;
  33203. StandardMaterial._RefractionTextureEnabled = true;
  33204. StandardMaterial._ColorGradingTextureEnabled = true;
  33205. StandardMaterial._FresnelEnabled = true;
  33206. __decorate([
  33207. BABYLON.serializeAsTexture("diffuseTexture")
  33208. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  33209. __decorate([
  33210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33211. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  33212. __decorate([
  33213. BABYLON.serializeAsTexture("ambientTexture")
  33214. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  33215. __decorate([
  33216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33217. ], StandardMaterial.prototype, "ambientTexture", void 0);
  33218. __decorate([
  33219. BABYLON.serializeAsTexture("opacityTexture")
  33220. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  33221. __decorate([
  33222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33223. ], StandardMaterial.prototype, "opacityTexture", void 0);
  33224. __decorate([
  33225. BABYLON.serializeAsTexture("reflectionTexture")
  33226. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  33227. __decorate([
  33228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33229. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  33230. __decorate([
  33231. BABYLON.serializeAsTexture("emissiveTexture")
  33232. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  33233. __decorate([
  33234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33235. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  33236. __decorate([
  33237. BABYLON.serializeAsTexture("specularTexture")
  33238. ], StandardMaterial.prototype, "_specularTexture", void 0);
  33239. __decorate([
  33240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33241. ], StandardMaterial.prototype, "specularTexture", void 0);
  33242. __decorate([
  33243. BABYLON.serializeAsTexture("bumpTexture")
  33244. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  33245. __decorate([
  33246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33247. ], StandardMaterial.prototype, "bumpTexture", void 0);
  33248. __decorate([
  33249. BABYLON.serializeAsTexture("lightmapTexture")
  33250. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  33251. __decorate([
  33252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33253. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  33254. __decorate([
  33255. BABYLON.serializeAsTexture("refractionTexture")
  33256. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  33257. __decorate([
  33258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33259. ], StandardMaterial.prototype, "refractionTexture", void 0);
  33260. __decorate([
  33261. BABYLON.serializeAsColor3("ambient")
  33262. ], StandardMaterial.prototype, "ambientColor", void 0);
  33263. __decorate([
  33264. BABYLON.serializeAsColor3("diffuse")
  33265. ], StandardMaterial.prototype, "diffuseColor", void 0);
  33266. __decorate([
  33267. BABYLON.serializeAsColor3("specular")
  33268. ], StandardMaterial.prototype, "specularColor", void 0);
  33269. __decorate([
  33270. BABYLON.serializeAsColor3("emissive")
  33271. ], StandardMaterial.prototype, "emissiveColor", void 0);
  33272. __decorate([
  33273. BABYLON.serialize()
  33274. ], StandardMaterial.prototype, "specularPower", void 0);
  33275. __decorate([
  33276. BABYLON.serialize("useAlphaFromDiffuseTexture")
  33277. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  33278. __decorate([
  33279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33280. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  33281. __decorate([
  33282. BABYLON.serialize("useEmissiveAsIllumination")
  33283. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  33284. __decorate([
  33285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33286. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  33287. __decorate([
  33288. BABYLON.serialize("linkEmissiveWithDiffuse")
  33289. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  33290. __decorate([
  33291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33292. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  33293. __decorate([
  33294. BABYLON.serialize("useSpecularOverAlpha")
  33295. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  33296. __decorate([
  33297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33298. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  33299. __decorate([
  33300. BABYLON.serialize("useReflectionOverAlpha")
  33301. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  33302. __decorate([
  33303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33304. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  33305. __decorate([
  33306. BABYLON.serialize("disableLighting")
  33307. ], StandardMaterial.prototype, "_disableLighting", void 0);
  33308. __decorate([
  33309. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33310. ], StandardMaterial.prototype, "disableLighting", void 0);
  33311. __decorate([
  33312. BABYLON.serialize("useParallax")
  33313. ], StandardMaterial.prototype, "_useParallax", void 0);
  33314. __decorate([
  33315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33316. ], StandardMaterial.prototype, "useParallax", void 0);
  33317. __decorate([
  33318. BABYLON.serialize("useParallaxOcclusion")
  33319. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  33320. __decorate([
  33321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33322. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  33323. __decorate([
  33324. BABYLON.serialize()
  33325. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  33326. __decorate([
  33327. BABYLON.serialize("roughness")
  33328. ], StandardMaterial.prototype, "_roughness", void 0);
  33329. __decorate([
  33330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33331. ], StandardMaterial.prototype, "roughness", void 0);
  33332. __decorate([
  33333. BABYLON.serialize()
  33334. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  33335. __decorate([
  33336. BABYLON.serialize()
  33337. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  33338. __decorate([
  33339. BABYLON.serialize("useLightmapAsShadowmap")
  33340. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  33341. __decorate([
  33342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33343. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33344. __decorate([
  33345. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  33346. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  33347. __decorate([
  33348. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33349. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  33350. __decorate([
  33351. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  33352. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  33353. __decorate([
  33354. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33355. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  33356. __decorate([
  33357. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  33358. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  33359. __decorate([
  33360. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33361. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  33362. __decorate([
  33363. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  33364. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  33365. __decorate([
  33366. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33367. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  33368. __decorate([
  33369. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  33370. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  33371. __decorate([
  33372. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33373. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  33374. __decorate([
  33375. BABYLON.serialize("useReflectionFresnelFromSpecular")
  33376. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  33377. __decorate([
  33378. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33379. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  33380. __decorate([
  33381. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  33382. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  33383. __decorate([
  33384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33385. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  33386. __decorate([
  33387. BABYLON.serialize("maxSimultaneousLights")
  33388. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  33389. __decorate([
  33390. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33391. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  33392. __decorate([
  33393. BABYLON.serialize("invertNormalMapX")
  33394. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  33395. __decorate([
  33396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33397. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  33398. __decorate([
  33399. BABYLON.serialize("invertNormalMapY")
  33400. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  33401. __decorate([
  33402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33403. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  33404. __decorate([
  33405. BABYLON.serialize("twoSidedLighting")
  33406. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  33407. __decorate([
  33408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33409. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  33410. __decorate([
  33411. BABYLON.serialize()
  33412. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  33413. return StandardMaterial;
  33414. }(BABYLON.PushMaterial));
  33415. BABYLON.StandardMaterial = StandardMaterial;
  33416. })(BABYLON || (BABYLON = {}));
  33417. //# sourceMappingURL=babylon.standardMaterial.js.map
  33418. var BABYLON;
  33419. (function (BABYLON) {
  33420. var PBRMaterialDefines = (function (_super) {
  33421. __extends(PBRMaterialDefines, _super);
  33422. function PBRMaterialDefines() {
  33423. var _this = _super.call(this) || this;
  33424. _this.PBR = true;
  33425. _this.MAINUV1 = false;
  33426. _this.MAINUV2 = false;
  33427. _this.UV1 = false;
  33428. _this.UV2 = false;
  33429. _this.ALBEDO = false;
  33430. _this.ALBEDODIRECTUV = 0;
  33431. _this.VERTEXCOLOR = false;
  33432. _this.AMBIENT = false;
  33433. _this.AMBIENTDIRECTUV = 0;
  33434. _this.AMBIENTINGRAYSCALE = false;
  33435. _this.OPACITY = false;
  33436. _this.VERTEXALPHA = false;
  33437. _this.OPACITYDIRECTUV = 0;
  33438. _this.OPACITYRGB = false;
  33439. _this.ALPHATEST = false;
  33440. _this.DEPTHPREPASS = false;
  33441. _this.ALPHABLEND = false;
  33442. _this.ALPHAFROMALBEDO = false;
  33443. _this.ALPHATESTVALUE = 0.5;
  33444. _this.SPECULAROVERALPHA = false;
  33445. _this.RADIANCEOVERALPHA = false;
  33446. _this.ALPHAFRESNEL = false;
  33447. _this.PREMULTIPLYALPHA = false;
  33448. _this.EMISSIVE = false;
  33449. _this.EMISSIVEDIRECTUV = 0;
  33450. _this.REFLECTIVITY = false;
  33451. _this.REFLECTIVITYDIRECTUV = 0;
  33452. _this.SPECULARTERM = false;
  33453. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  33454. _this.MICROSURFACEAUTOMATIC = false;
  33455. _this.LODBASEDMICROSFURACE = false;
  33456. _this.MICROSURFACEMAP = false;
  33457. _this.MICROSURFACEMAPDIRECTUV = 0;
  33458. _this.METALLICWORKFLOW = false;
  33459. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  33460. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  33461. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  33462. _this.AOSTOREINMETALMAPRED = false;
  33463. _this.ENVIRONMENTBRDF = false;
  33464. _this.NORMAL = false;
  33465. _this.TANGENT = false;
  33466. _this.BUMP = false;
  33467. _this.BUMPDIRECTUV = 0;
  33468. _this.PARALLAX = false;
  33469. _this.PARALLAXOCCLUSION = false;
  33470. _this.NORMALXYSCALE = true;
  33471. _this.LIGHTMAP = false;
  33472. _this.LIGHTMAPDIRECTUV = 0;
  33473. _this.USELIGHTMAPASSHADOWMAP = false;
  33474. _this.REFLECTION = false;
  33475. _this.REFLECTIONMAP_3D = false;
  33476. _this.REFLECTIONMAP_SPHERICAL = false;
  33477. _this.REFLECTIONMAP_PLANAR = false;
  33478. _this.REFLECTIONMAP_CUBIC = false;
  33479. _this.REFLECTIONMAP_PROJECTION = false;
  33480. _this.REFLECTIONMAP_SKYBOX = false;
  33481. _this.REFLECTIONMAP_EXPLICIT = false;
  33482. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33483. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33484. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33485. _this.INVERTCUBICMAP = false;
  33486. _this.USESPHERICALFROMREFLECTIONMAP = false;
  33487. _this.USESPHERICALINFRAGMENT = false;
  33488. _this.REFLECTIONMAP_OPPOSITEZ = false;
  33489. _this.LODINREFLECTIONALPHA = false;
  33490. _this.GAMMAREFLECTION = false;
  33491. _this.REFRACTION = false;
  33492. _this.REFRACTIONMAP_3D = false;
  33493. _this.REFRACTIONMAP_OPPOSITEZ = false;
  33494. _this.LODINREFRACTIONALPHA = false;
  33495. _this.GAMMAREFRACTION = false;
  33496. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  33497. _this.INSTANCES = false;
  33498. _this.NUM_BONE_INFLUENCERS = 0;
  33499. _this.BonesPerMesh = 0;
  33500. _this.MORPHTARGETS = false;
  33501. _this.MORPHTARGETS_NORMAL = false;
  33502. _this.MORPHTARGETS_TANGENT = false;
  33503. _this.NUM_MORPH_INFLUENCERS = 0;
  33504. _this.IMAGEPROCESSING = false;
  33505. _this.VIGNETTE = false;
  33506. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33507. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33508. _this.TONEMAPPING = false;
  33509. _this.CONTRAST = false;
  33510. _this.COLORCURVES = false;
  33511. _this.COLORGRADING = false;
  33512. _this.SAMPLER3DGREENDEPTH = false;
  33513. _this.SAMPLER3DBGRMAP = false;
  33514. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33515. _this.EXPOSURE = false;
  33516. _this.USEPHYSICALLIGHTFALLOFF = false;
  33517. _this.TWOSIDEDLIGHTING = false;
  33518. _this.SHADOWFLOAT = false;
  33519. _this.CLIPPLANE = false;
  33520. _this.POINTSIZE = false;
  33521. _this.FOG = false;
  33522. _this.LOGARITHMICDEPTH = false;
  33523. _this.FORCENORMALFORWARD = false;
  33524. _this.rebuild();
  33525. return _this;
  33526. }
  33527. PBRMaterialDefines.prototype.reset = function () {
  33528. _super.prototype.reset.call(this);
  33529. this.ALPHATESTVALUE = 0.5;
  33530. this.PBR = true;
  33531. };
  33532. return PBRMaterialDefines;
  33533. }(BABYLON.MaterialDefines));
  33534. /**
  33535. * The Physically based material base class of BJS.
  33536. *
  33537. * This offers the main features of a standard PBR material.
  33538. * For more information, please refer to the documentation :
  33539. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33540. */
  33541. var PBRBaseMaterial = (function (_super) {
  33542. __extends(PBRBaseMaterial, _super);
  33543. /**
  33544. * Instantiates a new PBRMaterial instance.
  33545. *
  33546. * @param name The material name
  33547. * @param scene The scene the material will be use in.
  33548. */
  33549. function PBRBaseMaterial(name, scene) {
  33550. var _this = _super.call(this, name, scene) || this;
  33551. /**
  33552. * Intensity of the direct lights e.g. the four lights available in your scene.
  33553. * This impacts both the direct diffuse and specular highlights.
  33554. */
  33555. _this._directIntensity = 1.0;
  33556. /**
  33557. * Intensity of the emissive part of the material.
  33558. * This helps controlling the emissive effect without modifying the emissive color.
  33559. */
  33560. _this._emissiveIntensity = 1.0;
  33561. /**
  33562. * Intensity of the environment e.g. how much the environment will light the object
  33563. * either through harmonics for rough material or through the refelction for shiny ones.
  33564. */
  33565. _this._environmentIntensity = 1.0;
  33566. /**
  33567. * This is a special control allowing the reduction of the specular highlights coming from the
  33568. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33569. */
  33570. _this._specularIntensity = 1.0;
  33571. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  33572. /**
  33573. * Debug Control allowing disabling the bump map on this material.
  33574. */
  33575. _this._disableBumpMap = false;
  33576. /**
  33577. * AKA Occlusion Texture Intensity in other nomenclature.
  33578. */
  33579. _this._ambientTextureStrength = 1.0;
  33580. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  33581. /**
  33582. * AKA Diffuse Color in other nomenclature.
  33583. */
  33584. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  33585. /**
  33586. * AKA Specular Color in other nomenclature.
  33587. */
  33588. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33589. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  33590. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  33591. /**
  33592. * AKA Glossiness in other nomenclature.
  33593. */
  33594. _this._microSurface = 0.9;
  33595. /**
  33596. * source material index of refraction (IOR)' / 'destination material IOR.
  33597. */
  33598. _this._indexOfRefraction = 0.66;
  33599. /**
  33600. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33601. */
  33602. _this._invertRefractionY = false;
  33603. /**
  33604. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33605. * Materials half opaque for instance using refraction could benefit from this control.
  33606. */
  33607. _this._linkRefractionWithTransparency = false;
  33608. _this._useLightmapAsShadowmap = false;
  33609. /**
  33610. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33611. */
  33612. _this._useAlphaFromAlbedoTexture = false;
  33613. /**
  33614. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33615. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33616. */
  33617. _this._useSpecularOverAlpha = true;
  33618. /**
  33619. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33620. */
  33621. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  33622. /**
  33623. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33624. */
  33625. _this._useRoughnessFromMetallicTextureAlpha = true;
  33626. /**
  33627. * Specifies if the metallic texture contains the roughness information in its green channel.
  33628. */
  33629. _this._useRoughnessFromMetallicTextureGreen = false;
  33630. /**
  33631. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33632. */
  33633. _this._useMetallnessFromMetallicTextureBlue = false;
  33634. /**
  33635. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33636. */
  33637. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  33638. /**
  33639. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33640. */
  33641. _this._useAmbientInGrayScale = false;
  33642. /**
  33643. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33644. * The material will try to infer what glossiness each pixel should be.
  33645. */
  33646. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  33647. /**
  33648. * BJS is using an harcoded light falloff based on a manually sets up range.
  33649. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33650. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33651. */
  33652. _this._usePhysicalLightFalloff = true;
  33653. /**
  33654. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33655. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33656. */
  33657. _this._useRadianceOverAlpha = true;
  33658. /**
  33659. * Allows using the bump map in parallax mode.
  33660. */
  33661. _this._useParallax = false;
  33662. /**
  33663. * Allows using the bump map in parallax occlusion mode.
  33664. */
  33665. _this._useParallaxOcclusion = false;
  33666. /**
  33667. * Controls the scale bias of the parallax mode.
  33668. */
  33669. _this._parallaxScaleBias = 0.05;
  33670. /**
  33671. * If sets to true, disables all the lights affecting the material.
  33672. */
  33673. _this._disableLighting = false;
  33674. /**
  33675. * Number of Simultaneous lights allowed on the material.
  33676. */
  33677. _this._maxSimultaneousLights = 4;
  33678. /**
  33679. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  33680. */
  33681. _this._invertNormalMapX = false;
  33682. /**
  33683. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  33684. */
  33685. _this._invertNormalMapY = false;
  33686. /**
  33687. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33688. */
  33689. _this._twoSidedLighting = false;
  33690. /**
  33691. * Defines the alpha limits in alpha test mode.
  33692. */
  33693. _this._alphaCutOff = 0.4;
  33694. /**
  33695. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33696. */
  33697. _this._forceAlphaTest = false;
  33698. /**
  33699. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33700. * in your scene composition.
  33701. */
  33702. _this._preMultiplyAlpha = false;
  33703. /**
  33704. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33705. * And/Or occlude the blended part.
  33706. */
  33707. _this._useAlphaFresnel = false;
  33708. /**
  33709. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  33710. * from cos thetav and roughness:
  33711. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  33712. */
  33713. _this._environmentBRDFTexture = null;
  33714. /**
  33715. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33716. */
  33717. _this._forceIrradianceInFragment = false;
  33718. /**
  33719. * Force normal to face away from face.
  33720. * (Temporary internal fix to remove before 3.1)
  33721. */
  33722. _this._forceNormalForward = false;
  33723. _this._renderTargets = new BABYLON.SmartArray(16);
  33724. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33725. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33726. _this._tempColor = new BABYLON.Color3();
  33727. // Setup the default processing configuration to the scene.
  33728. _this._attachImageProcessingConfiguration(null);
  33729. _this.getRenderTargetTextures = function () {
  33730. _this._renderTargets.reset();
  33731. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33732. _this._renderTargets.push(_this._reflectionTexture);
  33733. }
  33734. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33735. _this._renderTargets.push(_this._refractionTexture);
  33736. }
  33737. return _this._renderTargets;
  33738. };
  33739. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33740. return _this;
  33741. }
  33742. /**
  33743. * Attaches a new image processing configuration to the PBR Material.
  33744. * @param configuration
  33745. */
  33746. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33747. var _this = this;
  33748. if (configuration === this._imageProcessingConfiguration) {
  33749. return;
  33750. }
  33751. // Detaches observer.
  33752. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33753. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33754. }
  33755. // Pick the scene configuration if needed.
  33756. if (!configuration) {
  33757. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33758. }
  33759. else {
  33760. this._imageProcessingConfiguration = configuration;
  33761. }
  33762. // Attaches observer.
  33763. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33764. _this._markAllSubMeshesAsImageProcessingDirty();
  33765. });
  33766. };
  33767. PBRBaseMaterial.prototype.getClassName = function () {
  33768. return "PBRBaseMaterial";
  33769. };
  33770. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  33771. get: function () {
  33772. return this._useLogarithmicDepth;
  33773. },
  33774. set: function (value) {
  33775. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33776. },
  33777. enumerable: true,
  33778. configurable: true
  33779. });
  33780. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  33781. if (this._linkRefractionWithTransparency) {
  33782. return false;
  33783. }
  33784. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  33785. };
  33786. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  33787. if (this._forceAlphaTest) {
  33788. return true;
  33789. }
  33790. if (this._linkRefractionWithTransparency) {
  33791. return false;
  33792. }
  33793. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  33794. };
  33795. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33796. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  33797. };
  33798. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  33799. return this._albedoTexture;
  33800. };
  33801. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33802. if (this.isFrozen) {
  33803. if (this._wasPreviouslyReady) {
  33804. return true;
  33805. }
  33806. }
  33807. if (!subMesh._materialDefines) {
  33808. subMesh._materialDefines = new PBRMaterialDefines();
  33809. }
  33810. var scene = this.getScene();
  33811. var defines = subMesh._materialDefines;
  33812. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33813. if (defines._renderId === scene.getRenderId()) {
  33814. return true;
  33815. }
  33816. }
  33817. var engine = scene.getEngine();
  33818. // Lights
  33819. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33820. defines._needNormals = true;
  33821. // Textures
  33822. if (defines._areTexturesDirty) {
  33823. defines._needUVs = false;
  33824. if (scene.texturesEnabled) {
  33825. if (scene.getEngine().getCaps().textureLOD) {
  33826. defines.LODBASEDMICROSFURACE = true;
  33827. }
  33828. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33829. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  33830. return false;
  33831. }
  33832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  33833. }
  33834. else {
  33835. defines.ALBEDO = false;
  33836. }
  33837. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  33838. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33839. return false;
  33840. }
  33841. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33842. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  33843. }
  33844. else {
  33845. defines.AMBIENT = false;
  33846. }
  33847. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  33848. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33849. return false;
  33850. }
  33851. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33852. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33853. }
  33854. else {
  33855. defines.OPACITY = false;
  33856. }
  33857. var reflectionTexture = this._getReflectionTexture();
  33858. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  33859. if (!reflectionTexture.isReadyOrNotBlocking()) {
  33860. return false;
  33861. }
  33862. defines.REFLECTION = true;
  33863. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  33864. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  33865. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  33866. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  33867. defines.INVERTCUBICMAP = true;
  33868. }
  33869. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  33870. switch (reflectionTexture.coordinatesMode) {
  33871. case BABYLON.Texture.CUBIC_MODE:
  33872. case BABYLON.Texture.INVCUBIC_MODE:
  33873. defines.REFLECTIONMAP_CUBIC = true;
  33874. break;
  33875. case BABYLON.Texture.EXPLICIT_MODE:
  33876. defines.REFLECTIONMAP_EXPLICIT = true;
  33877. break;
  33878. case BABYLON.Texture.PLANAR_MODE:
  33879. defines.REFLECTIONMAP_PLANAR = true;
  33880. break;
  33881. case BABYLON.Texture.PROJECTION_MODE:
  33882. defines.REFLECTIONMAP_PROJECTION = true;
  33883. break;
  33884. case BABYLON.Texture.SKYBOX_MODE:
  33885. defines.REFLECTIONMAP_SKYBOX = true;
  33886. break;
  33887. case BABYLON.Texture.SPHERICAL_MODE:
  33888. defines.REFLECTIONMAP_SPHERICAL = true;
  33889. break;
  33890. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33891. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  33892. break;
  33893. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33894. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  33895. break;
  33896. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33897. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  33898. break;
  33899. }
  33900. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  33901. if (reflectionTexture.sphericalPolynomial) {
  33902. defines.USESPHERICALFROMREFLECTIONMAP = true;
  33903. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  33904. defines.USESPHERICALINFRAGMENT = true;
  33905. }
  33906. }
  33907. }
  33908. }
  33909. else {
  33910. defines.REFLECTION = false;
  33911. defines.REFLECTIONMAP_3D = false;
  33912. defines.REFLECTIONMAP_SPHERICAL = false;
  33913. defines.REFLECTIONMAP_PLANAR = false;
  33914. defines.REFLECTIONMAP_CUBIC = false;
  33915. defines.REFLECTIONMAP_PROJECTION = false;
  33916. defines.REFLECTIONMAP_SKYBOX = false;
  33917. defines.REFLECTIONMAP_EXPLICIT = false;
  33918. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33919. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33920. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33921. defines.INVERTCUBICMAP = false;
  33922. defines.USESPHERICALFROMREFLECTIONMAP = false;
  33923. defines.USESPHERICALINFRAGMENT = false;
  33924. defines.REFLECTIONMAP_OPPOSITEZ = false;
  33925. defines.LODINREFLECTIONALPHA = false;
  33926. defines.GAMMAREFLECTION = false;
  33927. }
  33928. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  33929. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33930. return false;
  33931. }
  33932. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33933. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33934. }
  33935. else {
  33936. defines.LIGHTMAP = false;
  33937. }
  33938. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  33939. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33940. return false;
  33941. }
  33942. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33943. }
  33944. else {
  33945. defines.EMISSIVE = false;
  33946. }
  33947. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  33948. if (this._metallicTexture) {
  33949. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  33950. return false;
  33951. }
  33952. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  33953. defines.METALLICWORKFLOW = true;
  33954. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  33955. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  33956. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  33957. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  33958. }
  33959. else if (this._reflectivityTexture) {
  33960. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  33961. return false;
  33962. }
  33963. defines.METALLICWORKFLOW = false;
  33964. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  33965. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  33966. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  33967. }
  33968. else {
  33969. defines.METALLICWORKFLOW = false;
  33970. defines.REFLECTIVITY = false;
  33971. }
  33972. if (this._microSurfaceTexture) {
  33973. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  33974. return false;
  33975. }
  33976. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  33977. }
  33978. else {
  33979. defines.MICROSURFACEMAP = false;
  33980. }
  33981. }
  33982. else {
  33983. defines.REFLECTIVITY = false;
  33984. defines.MICROSURFACEMAP = false;
  33985. }
  33986. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  33987. // Bump texure can not be none blocking.
  33988. if (!this._bumpTexture.isReady()) {
  33989. return false;
  33990. }
  33991. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33992. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33993. defines.PARALLAX = true;
  33994. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  33995. }
  33996. else {
  33997. defines.PARALLAX = false;
  33998. }
  33999. }
  34000. else {
  34001. defines.BUMP = false;
  34002. }
  34003. var refractionTexture = this._getRefractionTexture();
  34004. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34005. if (!refractionTexture.isReadyOrNotBlocking()) {
  34006. return false;
  34007. }
  34008. defines.REFRACTION = true;
  34009. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  34010. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  34011. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  34012. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  34013. if (this._linkRefractionWithTransparency) {
  34014. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34015. }
  34016. }
  34017. else {
  34018. defines.REFRACTION = false;
  34019. }
  34020. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34021. // This is blocking.
  34022. if (!this._environmentBRDFTexture.isReady()) {
  34023. return false;
  34024. }
  34025. defines.ENVIRONMENTBRDF = true;
  34026. }
  34027. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34028. defines.ALPHAFROMALBEDO = true;
  34029. }
  34030. }
  34031. if (this._useSpecularOverAlpha) {
  34032. defines.SPECULAROVERALPHA = true;
  34033. }
  34034. if (this._usePhysicalLightFalloff) {
  34035. defines.USEPHYSICALLIGHTFALLOFF = true;
  34036. }
  34037. if (this._useRadianceOverAlpha) {
  34038. defines.RADIANCEOVERALPHA = true;
  34039. }
  34040. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34041. defines.METALLICWORKFLOW = true;
  34042. }
  34043. if (!this.backFaceCulling && this._twoSidedLighting) {
  34044. defines.TWOSIDEDLIGHTING = true;
  34045. }
  34046. defines.ALPHATESTVALUE = this._alphaCutOff;
  34047. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  34048. defines.ALPHABLEND = this.needAlphaBlending();
  34049. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  34050. }
  34051. if (defines._areImageProcessingDirty) {
  34052. if (!this._imageProcessingConfiguration.isReady()) {
  34053. return false;
  34054. }
  34055. this._imageProcessingConfiguration.prepareDefines(defines);
  34056. }
  34057. defines.FORCENORMALFORWARD = this._forceNormalForward;
  34058. // Misc.
  34059. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34060. // Values that need to be evaluated on every frame
  34061. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  34062. // Attribs
  34063. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  34064. if (mesh) {
  34065. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34066. mesh.createNormals(true);
  34067. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  34068. }
  34069. }
  34070. }
  34071. // Get correct effect
  34072. if (defines.isDirty) {
  34073. defines.markAsProcessed();
  34074. scene.resetCachedMaterial();
  34075. // Fallbacks
  34076. var fallbacks = new BABYLON.EffectFallbacks();
  34077. if (defines.ENVIRONMENTBRDF) {
  34078. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  34079. }
  34080. if (defines.REFLECTION) {
  34081. fallbacks.addFallback(0, "REFLECTION");
  34082. }
  34083. if (defines.REFRACTION) {
  34084. fallbacks.addFallback(0, "REFRACTION");
  34085. }
  34086. if (defines.REFLECTIVITY) {
  34087. fallbacks.addFallback(0, "REFLECTIVITY");
  34088. }
  34089. if (defines.BUMP) {
  34090. fallbacks.addFallback(0, "BUMP");
  34091. }
  34092. if (defines.PARALLAX) {
  34093. fallbacks.addFallback(1, "PARALLAX");
  34094. }
  34095. if (defines.PARALLAXOCCLUSION) {
  34096. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34097. }
  34098. if (defines.SPECULAROVERALPHA) {
  34099. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34100. }
  34101. if (defines.FOG) {
  34102. fallbacks.addFallback(1, "FOG");
  34103. }
  34104. if (defines.POINTSIZE) {
  34105. fallbacks.addFallback(0, "POINTSIZE");
  34106. }
  34107. if (defines.LOGARITHMICDEPTH) {
  34108. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34109. }
  34110. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34111. if (defines.SPECULARTERM) {
  34112. fallbacks.addFallback(0, "SPECULARTERM");
  34113. }
  34114. if (defines.NUM_BONE_INFLUENCERS > 0) {
  34115. fallbacks.addCPUSkinningFallback(0, mesh);
  34116. }
  34117. //Attributes
  34118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34119. if (defines.NORMAL) {
  34120. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34121. }
  34122. if (defines.TANGENT) {
  34123. attribs.push(BABYLON.VertexBuffer.TangentKind);
  34124. }
  34125. if (defines.UV1) {
  34126. attribs.push(BABYLON.VertexBuffer.UVKind);
  34127. }
  34128. if (defines.UV2) {
  34129. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34130. }
  34131. if (defines.VERTEXCOLOR) {
  34132. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34133. }
  34134. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34135. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34136. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34137. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  34138. "vFogInfos", "vFogColor", "pointSize",
  34139. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34140. "mBones",
  34141. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34142. "vLightingIntensity",
  34143. "logarithmicDepthConstant",
  34144. "vSphericalX", "vSphericalY", "vSphericalZ",
  34145. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  34146. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  34147. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  34148. "vTangentSpaceParams"
  34149. ];
  34150. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  34151. "bumpSampler", "lightmapSampler", "opacitySampler",
  34152. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  34153. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  34154. "microSurfaceSampler", "environmentBrdfSampler"];
  34155. var uniformBuffers = ["Material", "Scene"];
  34156. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34157. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34158. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34159. uniformsNames: uniforms,
  34160. uniformBuffersNames: uniformBuffers,
  34161. samplers: samplers,
  34162. defines: defines,
  34163. maxSimultaneousLights: this._maxSimultaneousLights
  34164. });
  34165. var onCompiled = function (effect) {
  34166. if (this.onCompiled) {
  34167. this.onCompiled(effect);
  34168. }
  34169. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  34170. }.bind(this);
  34171. var join = defines.toString();
  34172. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  34173. attributes: attribs,
  34174. uniformsNames: uniforms,
  34175. uniformBuffersNames: uniformBuffers,
  34176. samplers: samplers,
  34177. defines: join,
  34178. fallbacks: fallbacks,
  34179. onCompiled: onCompiled,
  34180. onError: this.onError,
  34181. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34182. }, engine), defines);
  34183. this.buildUniformLayout();
  34184. }
  34185. if (!subMesh.effect.isReady()) {
  34186. return false;
  34187. }
  34188. defines._renderId = scene.getRenderId();
  34189. this._wasPreviouslyReady = true;
  34190. return true;
  34191. };
  34192. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  34193. // Order is important !
  34194. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  34195. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  34196. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34197. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34198. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34199. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  34200. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  34201. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34202. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34203. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34204. this._uniformBuffer.addUniform("albedoMatrix", 16);
  34205. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34206. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34207. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34208. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34209. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  34210. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  34211. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34212. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34213. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34214. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34215. this._uniformBuffer.addUniform("vReflectionColor", 3);
  34216. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  34217. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  34218. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  34219. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  34220. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  34221. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34222. this._uniformBuffer.addUniform("pointSize", 1);
  34223. this._uniformBuffer.create();
  34224. };
  34225. PBRBaseMaterial.prototype.unbind = function () {
  34226. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34227. this._uniformBuffer.setTexture("reflectionSampler", null);
  34228. }
  34229. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34230. this._uniformBuffer.setTexture("refractionSampler", null);
  34231. }
  34232. _super.prototype.unbind.call(this);
  34233. };
  34234. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34235. this._activeEffect.setMatrix("world", world);
  34236. };
  34237. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34238. var scene = this.getScene();
  34239. var defines = subMesh._materialDefines;
  34240. if (!defines) {
  34241. return;
  34242. }
  34243. var effect = subMesh.effect;
  34244. this._activeEffect = effect;
  34245. // Matrices
  34246. this.bindOnlyWorldMatrix(world);
  34247. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34248. // Bones
  34249. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  34250. if (mustRebind) {
  34251. this._uniformBuffer.bindToEffect(effect, "Material");
  34252. this.bindViewProjection(effect);
  34253. var reflectionTexture = this._getReflectionTexture();
  34254. var refractionTexture = this._getRefractionTexture();
  34255. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34256. // Texture uniforms
  34257. if (scene.texturesEnabled) {
  34258. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34259. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  34260. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  34261. }
  34262. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34263. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  34264. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34265. }
  34266. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34267. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34268. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34269. }
  34270. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34271. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  34272. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  34273. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  34274. var polynomials = reflectionTexture.sphericalPolynomial;
  34275. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  34276. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  34277. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  34278. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  34279. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  34280. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  34281. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  34282. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  34283. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  34284. }
  34285. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  34286. }
  34287. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34288. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34289. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34290. }
  34291. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34292. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34293. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34294. }
  34295. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34296. if (this._metallicTexture) {
  34297. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  34298. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  34299. }
  34300. else if (this._reflectivityTexture) {
  34301. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  34302. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  34303. }
  34304. if (this._microSurfaceTexture) {
  34305. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  34306. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  34307. }
  34308. }
  34309. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34310. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  34311. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34312. if (scene._mirroredCameraPosition) {
  34313. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34314. }
  34315. else {
  34316. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34317. }
  34318. }
  34319. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34320. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  34321. var depth = 1.0;
  34322. if (!refractionTexture.isCube) {
  34323. if (refractionTexture.depth) {
  34324. depth = refractionTexture.depth;
  34325. }
  34326. }
  34327. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  34328. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  34329. }
  34330. }
  34331. // Point size
  34332. if (this.pointsCloud) {
  34333. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34334. }
  34335. // Colors
  34336. if (defines.METALLICWORKFLOW) {
  34337. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  34338. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  34339. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  34340. }
  34341. else {
  34342. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  34343. }
  34344. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  34345. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  34346. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  34347. // Misc
  34348. this._lightingInfos.x = this._directIntensity;
  34349. this._lightingInfos.y = this._emissiveIntensity;
  34350. this._lightingInfos.z = this._environmentIntensity;
  34351. this._lightingInfos.w = this._specularIntensity;
  34352. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  34353. }
  34354. // Textures
  34355. if (scene.texturesEnabled) {
  34356. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34357. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  34358. }
  34359. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34360. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  34361. }
  34362. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34363. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  34364. }
  34365. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34366. if (defines.LODBASEDMICROSFURACE) {
  34367. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  34368. }
  34369. else {
  34370. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  34371. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  34372. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  34373. }
  34374. }
  34375. if (defines.ENVIRONMENTBRDF) {
  34376. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  34377. }
  34378. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34379. if (defines.LODBASEDMICROSFURACE) {
  34380. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  34381. }
  34382. else {
  34383. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  34384. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  34385. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  34386. }
  34387. }
  34388. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34389. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  34390. }
  34391. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34392. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  34393. }
  34394. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34395. if (this._metallicTexture) {
  34396. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  34397. }
  34398. else if (this._reflectivityTexture) {
  34399. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  34400. }
  34401. if (this._microSurfaceTexture) {
  34402. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  34403. }
  34404. }
  34405. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34406. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  34407. }
  34408. }
  34409. // Clip plane
  34410. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  34411. // Colors
  34412. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  34413. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  34414. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  34415. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  34416. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34417. }
  34418. if (mustRebind || !this.isFrozen) {
  34419. // Lights
  34420. if (scene.lightsEnabled && !this._disableLighting) {
  34421. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  34422. }
  34423. // View
  34424. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  34425. this.bindView(effect);
  34426. }
  34427. // Fog
  34428. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  34429. // Morph targets
  34430. if (defines.NUM_MORPH_INFLUENCERS) {
  34431. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  34432. }
  34433. // image processing
  34434. this._imageProcessingConfiguration.bind(this._activeEffect);
  34435. // Log. depth
  34436. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  34437. }
  34438. this._uniformBuffer.update();
  34439. this._afterBind(mesh);
  34440. scene = null;
  34441. };
  34442. PBRBaseMaterial.prototype.getAnimatables = function () {
  34443. var results = [];
  34444. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  34445. results.push(this._albedoTexture);
  34446. }
  34447. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34448. results.push(this._ambientTexture);
  34449. }
  34450. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34451. results.push(this._opacityTexture);
  34452. }
  34453. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34454. results.push(this._reflectionTexture);
  34455. }
  34456. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34457. results.push(this._emissiveTexture);
  34458. }
  34459. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  34460. results.push(this._metallicTexture);
  34461. }
  34462. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  34463. results.push(this._reflectivityTexture);
  34464. }
  34465. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34466. results.push(this._bumpTexture);
  34467. }
  34468. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34469. results.push(this._lightmapTexture);
  34470. }
  34471. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34472. results.push(this._refractionTexture);
  34473. }
  34474. return results;
  34475. };
  34476. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  34477. if (this._reflectionTexture) {
  34478. return this._reflectionTexture;
  34479. }
  34480. return this.getScene().environmentTexture;
  34481. };
  34482. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  34483. if (this._refractionTexture) {
  34484. return this._refractionTexture;
  34485. }
  34486. if (this._linkRefractionWithTransparency) {
  34487. return this.getScene().environmentTexture;
  34488. }
  34489. return null;
  34490. };
  34491. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34492. if (forceDisposeTextures) {
  34493. if (this._albedoTexture) {
  34494. this._albedoTexture.dispose();
  34495. }
  34496. if (this._ambientTexture) {
  34497. this._ambientTexture.dispose();
  34498. }
  34499. if (this._opacityTexture) {
  34500. this._opacityTexture.dispose();
  34501. }
  34502. if (this._reflectionTexture) {
  34503. this._reflectionTexture.dispose();
  34504. }
  34505. if (this._environmentBRDFTexture) {
  34506. this._environmentBRDFTexture.dispose();
  34507. }
  34508. if (this._emissiveTexture) {
  34509. this._emissiveTexture.dispose();
  34510. }
  34511. if (this._metallicTexture) {
  34512. this._metallicTexture.dispose();
  34513. }
  34514. if (this._reflectivityTexture) {
  34515. this._reflectivityTexture.dispose();
  34516. }
  34517. if (this._bumpTexture) {
  34518. this._bumpTexture.dispose();
  34519. }
  34520. if (this._lightmapTexture) {
  34521. this._lightmapTexture.dispose();
  34522. }
  34523. if (this._refractionTexture) {
  34524. this._refractionTexture.dispose();
  34525. }
  34526. }
  34527. this._renderTargets.dispose();
  34528. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34529. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34530. }
  34531. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34532. };
  34533. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  34534. __decorate([
  34535. BABYLON.serializeAsImageProcessingConfiguration()
  34536. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  34537. __decorate([
  34538. BABYLON.serialize()
  34539. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  34540. return PBRBaseMaterial;
  34541. }(BABYLON.PushMaterial));
  34542. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  34543. })(BABYLON || (BABYLON = {}));
  34544. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  34545. var BABYLON;
  34546. (function (BABYLON) {
  34547. var Internals;
  34548. (function (Internals) {
  34549. /**
  34550. * The Physically based simple base material of BJS.
  34551. *
  34552. * This enables better naming and convention enforcements on top of the pbrMaterial.
  34553. * It is used as the base class for both the specGloss and metalRough conventions.
  34554. */
  34555. var PBRBaseSimpleMaterial = (function (_super) {
  34556. __extends(PBRBaseSimpleMaterial, _super);
  34557. /**
  34558. * Instantiates a new PBRMaterial instance.
  34559. *
  34560. * @param name The material name
  34561. * @param scene The scene the material will be use in.
  34562. */
  34563. function PBRBaseSimpleMaterial(name, scene) {
  34564. var _this = _super.call(this, name, scene) || this;
  34565. /**
  34566. * Number of Simultaneous lights allowed on the material.
  34567. */
  34568. _this.maxSimultaneousLights = 4;
  34569. /**
  34570. * If sets to true, disables all the lights affecting the material.
  34571. */
  34572. _this.disableLighting = false;
  34573. /**
  34574. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34575. */
  34576. _this.invertNormalMapX = false;
  34577. /**
  34578. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34579. */
  34580. _this.invertNormalMapY = false;
  34581. /**
  34582. * Emissivie color used to self-illuminate the model.
  34583. */
  34584. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34585. /**
  34586. * Occlusion Channel Strenght.
  34587. */
  34588. _this.occlusionStrength = 1.0;
  34589. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34590. _this._useAmbientInGrayScale = true;
  34591. return _this;
  34592. }
  34593. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  34594. /**
  34595. * Gets the current transparency mode.
  34596. */
  34597. get: function () {
  34598. return this._transparencyMode;
  34599. },
  34600. /**
  34601. * Sets the transparency mode of the material.
  34602. */
  34603. set: function (value) {
  34604. if (this._transparencyMode === value) {
  34605. return;
  34606. }
  34607. this._transparencyMode = value;
  34608. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  34609. this._forceAlphaTest = true;
  34610. }
  34611. else {
  34612. this._forceAlphaTest = false;
  34613. }
  34614. this._markAllSubMeshesAsTexturesDirty();
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  34620. /**
  34621. * Gets the current double sided mode.
  34622. */
  34623. get: function () {
  34624. return this._twoSidedLighting;
  34625. },
  34626. /**
  34627. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34628. */
  34629. set: function (value) {
  34630. if (this._twoSidedLighting === value) {
  34631. return;
  34632. }
  34633. this._twoSidedLighting = value;
  34634. this.backFaceCulling = !value;
  34635. this._markAllSubMeshesAsTexturesDirty();
  34636. },
  34637. enumerable: true,
  34638. configurable: true
  34639. });
  34640. /**
  34641. * Specifies wether or not the alpha value of the albedo texture should be used.
  34642. */
  34643. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34644. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34645. };
  34646. /**
  34647. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  34648. */
  34649. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  34650. if (this._linkRefractionWithTransparency) {
  34651. return false;
  34652. }
  34653. return (this.alpha < 1.0) ||
  34654. (this._shouldUseAlphaFromAlbedoTexture() &&
  34655. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  34656. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  34657. };
  34658. /**
  34659. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  34660. */
  34661. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  34662. if (this._linkRefractionWithTransparency) {
  34663. return false;
  34664. }
  34665. return this._shouldUseAlphaFromAlbedoTexture() &&
  34666. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  34667. };
  34668. /**
  34669. * Return the active textures of the material.
  34670. */
  34671. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  34672. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34673. if (this.environmentTexture) {
  34674. activeTextures.push(this.environmentTexture);
  34675. }
  34676. if (this.normalTexture) {
  34677. activeTextures.push(this.normalTexture);
  34678. }
  34679. if (this.emissiveTexture) {
  34680. activeTextures.push(this.emissiveTexture);
  34681. }
  34682. if (this.occlusionTexture) {
  34683. activeTextures.push(this.occlusionTexture);
  34684. }
  34685. return activeTextures;
  34686. };
  34687. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  34688. return "PBRBaseSimpleMaterial";
  34689. };
  34690. __decorate([
  34691. BABYLON.serialize(),
  34692. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34693. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  34694. __decorate([
  34695. BABYLON.serialize(),
  34696. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34697. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  34698. __decorate([
  34699. BABYLON.serializeAsTexture(),
  34700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  34701. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  34702. __decorate([
  34703. BABYLON.serialize(),
  34704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34705. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  34706. __decorate([
  34707. BABYLON.serialize(),
  34708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34709. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  34710. __decorate([
  34711. BABYLON.serializeAsTexture(),
  34712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  34713. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  34714. __decorate([
  34715. BABYLON.serializeAsColor3("emissive"),
  34716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34717. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  34718. __decorate([
  34719. BABYLON.serializeAsTexture(),
  34720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34721. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  34722. __decorate([
  34723. BABYLON.serialize(),
  34724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  34725. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  34726. __decorate([
  34727. BABYLON.serializeAsTexture(),
  34728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  34729. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  34730. __decorate([
  34731. BABYLON.serialize(),
  34732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  34733. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  34734. __decorate([
  34735. BABYLON.serialize()
  34736. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  34737. __decorate([
  34738. BABYLON.serialize()
  34739. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  34740. return PBRBaseSimpleMaterial;
  34741. }(BABYLON.PBRBaseMaterial));
  34742. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  34743. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34744. })(BABYLON || (BABYLON = {}));
  34745. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  34746. var BABYLON;
  34747. (function (BABYLON) {
  34748. /**
  34749. * The Physically based material of BJS.
  34750. *
  34751. * This offers the main features of a standard PBR material.
  34752. * For more information, please refer to the documentation :
  34753. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34754. */
  34755. var PBRMaterial = (function (_super) {
  34756. __extends(PBRMaterial, _super);
  34757. /**
  34758. * Instantiates a new PBRMaterial instance.
  34759. *
  34760. * @param name The material name
  34761. * @param scene The scene the material will be use in.
  34762. */
  34763. function PBRMaterial(name, scene) {
  34764. var _this = _super.call(this, name, scene) || this;
  34765. /**
  34766. * Intensity of the direct lights e.g. the four lights available in your scene.
  34767. * This impacts both the direct diffuse and specular highlights.
  34768. */
  34769. _this.directIntensity = 1.0;
  34770. /**
  34771. * Intensity of the emissive part of the material.
  34772. * This helps controlling the emissive effect without modifying the emissive color.
  34773. */
  34774. _this.emissiveIntensity = 1.0;
  34775. /**
  34776. * Intensity of the environment e.g. how much the environment will light the object
  34777. * either through harmonics for rough material or through the refelction for shiny ones.
  34778. */
  34779. _this.environmentIntensity = 1.0;
  34780. /**
  34781. * This is a special control allowing the reduction of the specular highlights coming from the
  34782. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34783. */
  34784. _this.specularIntensity = 1.0;
  34785. /**
  34786. * Debug Control allowing disabling the bump map on this material.
  34787. */
  34788. _this.disableBumpMap = false;
  34789. /**
  34790. * AKA Occlusion Texture Intensity in other nomenclature.
  34791. */
  34792. _this.ambientTextureStrength = 1.0;
  34793. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34794. /**
  34795. * AKA Diffuse Color in other nomenclature.
  34796. */
  34797. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34798. /**
  34799. * AKA Specular Color in other nomenclature.
  34800. */
  34801. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34802. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  34803. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34804. /**
  34805. * AKA Glossiness in other nomenclature.
  34806. */
  34807. _this.microSurface = 1.0;
  34808. /**
  34809. * source material index of refraction (IOR)' / 'destination material IOR.
  34810. */
  34811. _this.indexOfRefraction = 0.66;
  34812. /**
  34813. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34814. */
  34815. _this.invertRefractionY = false;
  34816. /**
  34817. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34818. * Materials half opaque for instance using refraction could benefit from this control.
  34819. */
  34820. _this.linkRefractionWithTransparency = false;
  34821. _this.useLightmapAsShadowmap = false;
  34822. /**
  34823. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34824. */
  34825. _this.useAlphaFromAlbedoTexture = false;
  34826. /**
  34827. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34828. */
  34829. _this.forceAlphaTest = false;
  34830. /**
  34831. * Defines the alpha limits in alpha test mode.
  34832. */
  34833. _this.alphaCutOff = 0.4;
  34834. /**
  34835. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34836. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34837. */
  34838. _this.useSpecularOverAlpha = true;
  34839. /**
  34840. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34841. */
  34842. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  34843. /**
  34844. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34845. */
  34846. _this.useRoughnessFromMetallicTextureAlpha = true;
  34847. /**
  34848. * Specifies if the metallic texture contains the roughness information in its green channel.
  34849. */
  34850. _this.useRoughnessFromMetallicTextureGreen = false;
  34851. /**
  34852. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34853. */
  34854. _this.useMetallnessFromMetallicTextureBlue = false;
  34855. /**
  34856. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34857. */
  34858. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  34859. /**
  34860. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34861. */
  34862. _this.useAmbientInGrayScale = false;
  34863. /**
  34864. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34865. * The material will try to infer what glossiness each pixel should be.
  34866. */
  34867. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  34868. /**
  34869. * BJS is using an harcoded light falloff based on a manually sets up range.
  34870. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34871. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34872. */
  34873. _this.usePhysicalLightFalloff = true;
  34874. /**
  34875. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34876. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34877. */
  34878. _this.useRadianceOverAlpha = true;
  34879. /**
  34880. * Allows using the bump map in parallax mode.
  34881. */
  34882. _this.useParallax = false;
  34883. /**
  34884. * Allows using the bump map in parallax occlusion mode.
  34885. */
  34886. _this.useParallaxOcclusion = false;
  34887. /**
  34888. * Controls the scale bias of the parallax mode.
  34889. */
  34890. _this.parallaxScaleBias = 0.05;
  34891. /**
  34892. * If sets to true, disables all the lights affecting the material.
  34893. */
  34894. _this.disableLighting = false;
  34895. /**
  34896. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34897. */
  34898. _this.forceIrradianceInFragment = false;
  34899. /**
  34900. * Number of Simultaneous lights allowed on the material.
  34901. */
  34902. _this.maxSimultaneousLights = 4;
  34903. /**
  34904. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34905. */
  34906. _this.invertNormalMapX = false;
  34907. /**
  34908. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34909. */
  34910. _this.invertNormalMapY = false;
  34911. /**
  34912. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34913. */
  34914. _this.twoSidedLighting = false;
  34915. /**
  34916. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  34917. * in your scene composition.
  34918. */
  34919. _this.preMultiplyAlpha = false;
  34920. /**
  34921. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34922. * And/Or occlude the blended part.
  34923. */
  34924. _this.useAlphaFresnel = false;
  34925. /**
  34926. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34927. * And/Or occlude the blended part.
  34928. */
  34929. _this.environmentBRDFTexture = null;
  34930. /**
  34931. * Force normal to face away from face.
  34932. * (Temporary internal fix to remove before 3.1)
  34933. */
  34934. _this.forceNormalForward = false;
  34935. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34936. return _this;
  34937. }
  34938. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  34939. /**
  34940. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  34941. */
  34942. get: function () {
  34943. return this._PBRMATERIAL_OPAQUE;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  34949. /**
  34950. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  34951. */
  34952. get: function () {
  34953. return this._PBRMATERIAL_ALPHATEST;
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  34959. /**
  34960. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  34961. */
  34962. get: function () {
  34963. return this._PBRMATERIAL_ALPHABLEND;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  34969. /**
  34970. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  34971. * They are also discarded below the alpha cutoff threshold to improve performances.
  34972. */
  34973. get: function () {
  34974. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  34980. /**
  34981. * Gets the image processing configuration used either in this material.
  34982. */
  34983. get: function () {
  34984. return this._imageProcessingConfiguration;
  34985. },
  34986. /**
  34987. * Sets the Default image processing configuration used either in the this material.
  34988. *
  34989. * If sets to null, the scene one is in use.
  34990. */
  34991. set: function (value) {
  34992. this._attachImageProcessingConfiguration(value);
  34993. // Ensure the effect will be rebuilt.
  34994. this._markAllSubMeshesAsTexturesDirty();
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35000. /**
  35001. * Gets wether the color curves effect is enabled.
  35002. */
  35003. get: function () {
  35004. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35005. },
  35006. /**
  35007. * Sets wether the color curves effect is enabled.
  35008. */
  35009. set: function (value) {
  35010. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  35016. /**
  35017. * Gets wether the color grading effect is enabled.
  35018. */
  35019. get: function () {
  35020. return this.imageProcessingConfiguration.colorGradingEnabled;
  35021. },
  35022. /**
  35023. * Gets wether the color grading effect is enabled.
  35024. */
  35025. set: function (value) {
  35026. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  35032. /**
  35033. * Gets wether tonemapping is enabled or not.
  35034. */
  35035. get: function () {
  35036. return this._imageProcessingConfiguration.toneMappingEnabled;
  35037. },
  35038. /**
  35039. * Sets wether tonemapping is enabled or not
  35040. */
  35041. set: function (value) {
  35042. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. ;
  35048. ;
  35049. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  35050. /**
  35051. * The camera exposure used on this material.
  35052. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35053. * This corresponds to a photographic exposure.
  35054. */
  35055. get: function () {
  35056. return this._imageProcessingConfiguration.exposure;
  35057. },
  35058. /**
  35059. * The camera exposure used on this material.
  35060. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35061. * This corresponds to a photographic exposure.
  35062. */
  35063. set: function (value) {
  35064. this._imageProcessingConfiguration.exposure = value;
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. ;
  35070. ;
  35071. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  35072. /**
  35073. * Gets The camera contrast used on this material.
  35074. */
  35075. get: function () {
  35076. return this._imageProcessingConfiguration.contrast;
  35077. },
  35078. /**
  35079. * Sets The camera contrast used on this material.
  35080. */
  35081. set: function (value) {
  35082. this._imageProcessingConfiguration.contrast = value;
  35083. },
  35084. enumerable: true,
  35085. configurable: true
  35086. });
  35087. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  35088. /**
  35089. * Gets the Color Grading 2D Lookup Texture.
  35090. */
  35091. get: function () {
  35092. return this._imageProcessingConfiguration.colorGradingTexture;
  35093. },
  35094. /**
  35095. * Sets the Color Grading 2D Lookup Texture.
  35096. */
  35097. set: function (value) {
  35098. this._imageProcessingConfiguration.colorGradingTexture = value;
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  35104. /**
  35105. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35106. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35107. * 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;
  35108. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35109. */
  35110. get: function () {
  35111. return this._imageProcessingConfiguration.colorCurves;
  35112. },
  35113. /**
  35114. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35115. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35116. * 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;
  35117. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35118. */
  35119. set: function (value) {
  35120. this._imageProcessingConfiguration.colorCurves = value;
  35121. },
  35122. enumerable: true,
  35123. configurable: true
  35124. });
  35125. PBRMaterial.prototype.getClassName = function () {
  35126. return "PBRMaterial";
  35127. };
  35128. PBRMaterial.prototype.getActiveTextures = function () {
  35129. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35130. if (this._albedoTexture) {
  35131. activeTextures.push(this._albedoTexture);
  35132. }
  35133. if (this._ambientTexture) {
  35134. activeTextures.push(this._ambientTexture);
  35135. }
  35136. if (this._opacityTexture) {
  35137. activeTextures.push(this._opacityTexture);
  35138. }
  35139. if (this._reflectionTexture) {
  35140. activeTextures.push(this._reflectionTexture);
  35141. }
  35142. if (this._emissiveTexture) {
  35143. activeTextures.push(this._emissiveTexture);
  35144. }
  35145. if (this._reflectivityTexture) {
  35146. activeTextures.push(this._reflectivityTexture);
  35147. }
  35148. if (this._metallicTexture) {
  35149. activeTextures.push(this._metallicTexture);
  35150. }
  35151. if (this._microSurfaceTexture) {
  35152. activeTextures.push(this._microSurfaceTexture);
  35153. }
  35154. if (this._bumpTexture) {
  35155. activeTextures.push(this._bumpTexture);
  35156. }
  35157. if (this._lightmapTexture) {
  35158. activeTextures.push(this._lightmapTexture);
  35159. }
  35160. if (this._refractionTexture) {
  35161. activeTextures.push(this._refractionTexture);
  35162. }
  35163. return activeTextures;
  35164. };
  35165. PBRMaterial.prototype.hasTexture = function (texture) {
  35166. if (_super.prototype.hasTexture.call(this, texture)) {
  35167. return true;
  35168. }
  35169. if (this._albedoTexture === texture) {
  35170. return true;
  35171. }
  35172. if (this._ambientTexture === texture) {
  35173. return true;
  35174. }
  35175. if (this._opacityTexture === texture) {
  35176. return true;
  35177. }
  35178. if (this._reflectionTexture === texture) {
  35179. return true;
  35180. }
  35181. if (this._reflectivityTexture === texture) {
  35182. return true;
  35183. }
  35184. if (this._metallicTexture === texture) {
  35185. return true;
  35186. }
  35187. if (this._microSurfaceTexture === texture) {
  35188. return true;
  35189. }
  35190. if (this._bumpTexture === texture) {
  35191. return true;
  35192. }
  35193. if (this._lightmapTexture === texture) {
  35194. return true;
  35195. }
  35196. if (this._refractionTexture === texture) {
  35197. return true;
  35198. }
  35199. return false;
  35200. };
  35201. PBRMaterial.prototype.clone = function (name) {
  35202. var _this = this;
  35203. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35204. clone.id = name;
  35205. clone.name = name;
  35206. return clone;
  35207. };
  35208. PBRMaterial.prototype.serialize = function () {
  35209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35210. serializationObject.customType = "BABYLON.PBRMaterial";
  35211. return serializationObject;
  35212. };
  35213. // Statics
  35214. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35215. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35216. };
  35217. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35218. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35219. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35220. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35221. __decorate([
  35222. BABYLON.serialize(),
  35223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35224. ], PBRMaterial.prototype, "directIntensity", void 0);
  35225. __decorate([
  35226. BABYLON.serialize(),
  35227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35228. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35229. __decorate([
  35230. BABYLON.serialize(),
  35231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35232. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35233. __decorate([
  35234. BABYLON.serialize(),
  35235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35236. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35237. __decorate([
  35238. BABYLON.serialize(),
  35239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35240. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35241. __decorate([
  35242. BABYLON.serializeAsTexture(),
  35243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35244. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35245. __decorate([
  35246. BABYLON.serializeAsTexture(),
  35247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35248. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35249. __decorate([
  35250. BABYLON.serialize(),
  35251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35252. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35253. __decorate([
  35254. BABYLON.serializeAsTexture(),
  35255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35256. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35257. __decorate([
  35258. BABYLON.serializeAsTexture(),
  35259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35260. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  35261. __decorate([
  35262. BABYLON.serializeAsTexture(),
  35263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35264. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  35265. __decorate([
  35266. BABYLON.serializeAsTexture(),
  35267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35268. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  35269. __decorate([
  35270. BABYLON.serializeAsTexture(),
  35271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35272. ], PBRMaterial.prototype, "metallicTexture", void 0);
  35273. __decorate([
  35274. BABYLON.serialize(),
  35275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35276. ], PBRMaterial.prototype, "metallic", void 0);
  35277. __decorate([
  35278. BABYLON.serialize(),
  35279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35280. ], PBRMaterial.prototype, "roughness", void 0);
  35281. __decorate([
  35282. BABYLON.serializeAsTexture(),
  35283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35284. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  35285. __decorate([
  35286. BABYLON.serializeAsTexture(),
  35287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35288. ], PBRMaterial.prototype, "bumpTexture", void 0);
  35289. __decorate([
  35290. BABYLON.serializeAsTexture(),
  35291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  35292. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  35293. __decorate([
  35294. BABYLON.serializeAsTexture(),
  35295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35296. ], PBRMaterial.prototype, "refractionTexture", void 0);
  35297. __decorate([
  35298. BABYLON.serializeAsColor3("ambient"),
  35299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35300. ], PBRMaterial.prototype, "ambientColor", void 0);
  35301. __decorate([
  35302. BABYLON.serializeAsColor3("albedo"),
  35303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35304. ], PBRMaterial.prototype, "albedoColor", void 0);
  35305. __decorate([
  35306. BABYLON.serializeAsColor3("reflectivity"),
  35307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35308. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  35309. __decorate([
  35310. BABYLON.serializeAsColor3("reflection"),
  35311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35312. ], PBRMaterial.prototype, "reflectionColor", void 0);
  35313. __decorate([
  35314. BABYLON.serializeAsColor3("emissive"),
  35315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35316. ], PBRMaterial.prototype, "emissiveColor", void 0);
  35317. __decorate([
  35318. BABYLON.serialize(),
  35319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35320. ], PBRMaterial.prototype, "microSurface", void 0);
  35321. __decorate([
  35322. BABYLON.serialize(),
  35323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35324. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  35325. __decorate([
  35326. BABYLON.serialize(),
  35327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35328. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  35329. __decorate([
  35330. BABYLON.serialize(),
  35331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35332. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  35333. __decorate([
  35334. BABYLON.serialize(),
  35335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35336. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35337. __decorate([
  35338. BABYLON.serialize(),
  35339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35340. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  35341. __decorate([
  35342. BABYLON.serialize(),
  35343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35344. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  35345. __decorate([
  35346. BABYLON.serialize(),
  35347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35348. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  35349. __decorate([
  35350. BABYLON.serialize(),
  35351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35352. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  35353. __decorate([
  35354. BABYLON.serialize(),
  35355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35356. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  35357. __decorate([
  35358. BABYLON.serialize(),
  35359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35360. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  35361. __decorate([
  35362. BABYLON.serialize(),
  35363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35364. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  35365. __decorate([
  35366. BABYLON.serialize(),
  35367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35368. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  35369. __decorate([
  35370. BABYLON.serialize(),
  35371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35372. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  35373. __decorate([
  35374. BABYLON.serialize(),
  35375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35376. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  35377. __decorate([
  35378. BABYLON.serialize(),
  35379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35380. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  35381. __decorate([
  35382. BABYLON.serialize(),
  35383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35384. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  35385. __decorate([
  35386. BABYLON.serialize(),
  35387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35388. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  35389. __decorate([
  35390. BABYLON.serialize(),
  35391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35392. ], PBRMaterial.prototype, "useParallax", void 0);
  35393. __decorate([
  35394. BABYLON.serialize(),
  35395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35396. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  35397. __decorate([
  35398. BABYLON.serialize(),
  35399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35400. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  35401. __decorate([
  35402. BABYLON.serialize(),
  35403. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35404. ], PBRMaterial.prototype, "disableLighting", void 0);
  35405. __decorate([
  35406. BABYLON.serialize(),
  35407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35408. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  35409. __decorate([
  35410. BABYLON.serialize(),
  35411. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35412. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  35413. __decorate([
  35414. BABYLON.serialize(),
  35415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35416. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  35417. __decorate([
  35418. BABYLON.serialize(),
  35419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35420. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  35421. __decorate([
  35422. BABYLON.serialize(),
  35423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35424. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  35425. __decorate([
  35426. BABYLON.serialize(),
  35427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35428. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  35429. __decorate([
  35430. BABYLON.serialize(),
  35431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35432. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  35433. __decorate([
  35434. BABYLON.serializeAsTexture(),
  35435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35436. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  35437. __decorate([
  35438. BABYLON.serialize(),
  35439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35440. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  35441. return PBRMaterial;
  35442. }(BABYLON.PBRBaseMaterial));
  35443. BABYLON.PBRMaterial = PBRMaterial;
  35444. })(BABYLON || (BABYLON = {}));
  35445. //# sourceMappingURL=babylon.pbrMaterial.js.map
  35446. var BABYLON;
  35447. (function (BABYLON) {
  35448. /**
  35449. * The PBR material of BJS following the metal roughness convention.
  35450. *
  35451. * This fits to the PBR convention in the GLTF definition:
  35452. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  35453. */
  35454. var PBRMetallicRoughnessMaterial = (function (_super) {
  35455. __extends(PBRMetallicRoughnessMaterial, _super);
  35456. /**
  35457. * Instantiates a new PBRMetalRoughnessMaterial instance.
  35458. *
  35459. * @param name The material name
  35460. * @param scene The scene the material will be use in.
  35461. */
  35462. function PBRMetallicRoughnessMaterial(name, scene) {
  35463. var _this = _super.call(this, name, scene) || this;
  35464. _this._useRoughnessFromMetallicTextureAlpha = false;
  35465. _this._useRoughnessFromMetallicTextureGreen = true;
  35466. _this._useMetallnessFromMetallicTextureBlue = true;
  35467. return _this;
  35468. }
  35469. /**
  35470. * Return the currrent class name of the material.
  35471. */
  35472. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  35473. return "PBRMetallicRoughnessMaterial";
  35474. };
  35475. /**
  35476. * Return the active textures of the material.
  35477. */
  35478. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  35479. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35480. if (this.baseTexture) {
  35481. activeTextures.push(this.baseTexture);
  35482. }
  35483. if (this.metallicRoughnessTexture) {
  35484. activeTextures.push(this.metallicRoughnessTexture);
  35485. }
  35486. return activeTextures;
  35487. };
  35488. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  35489. if (_super.prototype.hasTexture.call(this, texture)) {
  35490. return true;
  35491. }
  35492. if (this.baseTexture === texture) {
  35493. return true;
  35494. }
  35495. if (this.metallicRoughnessTexture === texture) {
  35496. return true;
  35497. }
  35498. return false;
  35499. };
  35500. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  35501. var _this = this;
  35502. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  35503. clone.id = name;
  35504. clone.name = name;
  35505. return clone;
  35506. };
  35507. /**
  35508. * Serialize the material to a parsable JSON object.
  35509. */
  35510. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  35511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35512. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  35513. return serializationObject;
  35514. };
  35515. /**
  35516. * Parses a JSON object correponding to the serialize function.
  35517. */
  35518. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  35519. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  35520. };
  35521. __decorate([
  35522. BABYLON.serializeAsColor3(),
  35523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35524. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  35525. __decorate([
  35526. BABYLON.serializeAsTexture(),
  35527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35528. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  35529. __decorate([
  35530. BABYLON.serialize(),
  35531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35532. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  35533. __decorate([
  35534. BABYLON.serialize(),
  35535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35536. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  35537. __decorate([
  35538. BABYLON.serializeAsTexture(),
  35539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  35540. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  35541. return PBRMetallicRoughnessMaterial;
  35542. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35543. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  35544. })(BABYLON || (BABYLON = {}));
  35545. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  35546. var BABYLON;
  35547. (function (BABYLON) {
  35548. /**
  35549. * The PBR material of BJS following the specular glossiness convention.
  35550. *
  35551. * This fits to the PBR convention in the GLTF definition:
  35552. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  35553. */
  35554. var PBRSpecularGlossinessMaterial = (function (_super) {
  35555. __extends(PBRSpecularGlossinessMaterial, _super);
  35556. /**
  35557. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  35558. *
  35559. * @param name The material name
  35560. * @param scene The scene the material will be use in.
  35561. */
  35562. function PBRSpecularGlossinessMaterial(name, scene) {
  35563. var _this = _super.call(this, name, scene) || this;
  35564. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  35565. return _this;
  35566. }
  35567. /**
  35568. * Return the currrent class name of the material.
  35569. */
  35570. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  35571. return "PBRSpecularGlossinessMaterial";
  35572. };
  35573. /**
  35574. * Return the active textures of the material.
  35575. */
  35576. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  35577. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35578. if (this.diffuseTexture) {
  35579. activeTextures.push(this.diffuseTexture);
  35580. }
  35581. if (this.specularGlossinessTexture) {
  35582. activeTextures.push(this.specularGlossinessTexture);
  35583. }
  35584. return activeTextures;
  35585. };
  35586. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  35587. if (_super.prototype.hasTexture.call(this, texture)) {
  35588. return true;
  35589. }
  35590. if (this.diffuseTexture === texture) {
  35591. return true;
  35592. }
  35593. if (this.specularGlossinessTexture === texture) {
  35594. return true;
  35595. }
  35596. return false;
  35597. };
  35598. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  35599. var _this = this;
  35600. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  35601. clone.id = name;
  35602. clone.name = name;
  35603. return clone;
  35604. };
  35605. /**
  35606. * Serialize the material to a parsable JSON object.
  35607. */
  35608. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  35609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35610. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  35611. return serializationObject;
  35612. };
  35613. /**
  35614. * Parses a JSON object correponding to the serialize function.
  35615. */
  35616. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  35617. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  35618. };
  35619. __decorate([
  35620. BABYLON.serializeAsColor3("diffuse"),
  35621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35622. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  35623. __decorate([
  35624. BABYLON.serializeAsTexture(),
  35625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35626. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  35627. __decorate([
  35628. BABYLON.serializeAsColor3("specular"),
  35629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  35630. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  35631. __decorate([
  35632. BABYLON.serialize(),
  35633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  35634. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  35635. __decorate([
  35636. BABYLON.serializeAsTexture(),
  35637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  35638. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  35639. return PBRSpecularGlossinessMaterial;
  35640. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35641. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  35642. })(BABYLON || (BABYLON = {}));
  35643. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  35644. var BABYLON;
  35645. (function (BABYLON) {
  35646. BABYLON.CameraInputTypes = {};
  35647. var CameraInputsManager = (function () {
  35648. function CameraInputsManager(camera) {
  35649. this.attached = {};
  35650. this.camera = camera;
  35651. this.checkInputs = function () { };
  35652. }
  35653. CameraInputsManager.prototype.add = function (input) {
  35654. var type = input.getSimpleName();
  35655. if (this.attached[type]) {
  35656. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  35657. return;
  35658. }
  35659. this.attached[type] = input;
  35660. input.camera = this.camera;
  35661. //for checkInputs, we are dynamically creating a function
  35662. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  35663. if (input.checkInputs) {
  35664. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35665. }
  35666. if (this.attachedElement) {
  35667. input.attachControl(this.attachedElement);
  35668. }
  35669. };
  35670. CameraInputsManager.prototype.remove = function (inputToRemove) {
  35671. for (var cam in this.attached) {
  35672. var input = this.attached[cam];
  35673. if (input === inputToRemove) {
  35674. input.detachControl(this.attachedElement);
  35675. input.camera = null;
  35676. delete this.attached[cam];
  35677. this.rebuildInputCheck();
  35678. }
  35679. }
  35680. };
  35681. CameraInputsManager.prototype.removeByType = function (inputType) {
  35682. for (var cam in this.attached) {
  35683. var input = this.attached[cam];
  35684. if (input.getClassName() === inputType) {
  35685. input.detachControl(this.attachedElement);
  35686. input.camera = null;
  35687. delete this.attached[cam];
  35688. this.rebuildInputCheck();
  35689. }
  35690. }
  35691. };
  35692. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  35693. var current = this.checkInputs;
  35694. return function () {
  35695. current();
  35696. fn();
  35697. };
  35698. };
  35699. CameraInputsManager.prototype.attachInput = function (input) {
  35700. input.attachControl(this.attachedElement, this.noPreventDefault);
  35701. };
  35702. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  35703. if (this.attachedElement) {
  35704. return;
  35705. }
  35706. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35707. this.attachedElement = element;
  35708. this.noPreventDefault = noPreventDefault;
  35709. for (var cam in this.attached) {
  35710. var input = this.attached[cam];
  35711. this.attached[cam].attachControl(element, noPreventDefault);
  35712. }
  35713. };
  35714. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  35715. if (disconnect === void 0) { disconnect = false; }
  35716. if (this.attachedElement !== element) {
  35717. return;
  35718. }
  35719. for (var cam in this.attached) {
  35720. var input = this.attached[cam];
  35721. this.attached[cam].detachControl(element);
  35722. if (disconnect) {
  35723. this.attached[cam].camera = null;
  35724. }
  35725. }
  35726. this.attachedElement = null;
  35727. };
  35728. CameraInputsManager.prototype.rebuildInputCheck = function () {
  35729. this.checkInputs = function () { };
  35730. for (var cam in this.attached) {
  35731. var input = this.attached[cam];
  35732. if (input.checkInputs) {
  35733. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35734. }
  35735. }
  35736. };
  35737. CameraInputsManager.prototype.clear = function () {
  35738. if (this.attachedElement) {
  35739. this.detachElement(this.attachedElement, true);
  35740. }
  35741. this.attached = {};
  35742. this.attachedElement = null;
  35743. this.checkInputs = function () { };
  35744. };
  35745. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  35746. var inputs = {};
  35747. for (var cam in this.attached) {
  35748. var input = this.attached[cam];
  35749. var res = BABYLON.SerializationHelper.Serialize(input);
  35750. inputs[input.getClassName()] = res;
  35751. }
  35752. serializedCamera.inputsmgr = inputs;
  35753. };
  35754. CameraInputsManager.prototype.parse = function (parsedCamera) {
  35755. var parsedInputs = parsedCamera.inputsmgr;
  35756. if (parsedInputs) {
  35757. this.clear();
  35758. for (var n in parsedInputs) {
  35759. var construct = BABYLON.CameraInputTypes[n];
  35760. if (construct) {
  35761. var parsedinput = parsedInputs[n];
  35762. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  35763. this.add(input);
  35764. }
  35765. }
  35766. }
  35767. else {
  35768. //2016-03-08 this part is for managing backward compatibility
  35769. for (var n in this.attached) {
  35770. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  35771. if (construct) {
  35772. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  35773. this.remove(this.attached[n]);
  35774. this.add(input);
  35775. }
  35776. }
  35777. }
  35778. };
  35779. return CameraInputsManager;
  35780. }());
  35781. BABYLON.CameraInputsManager = CameraInputsManager;
  35782. })(BABYLON || (BABYLON = {}));
  35783. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  35784. var BABYLON;
  35785. (function (BABYLON) {
  35786. var FreeCameraMouseInput = (function () {
  35787. function FreeCameraMouseInput(touchEnabled) {
  35788. if (touchEnabled === void 0) { touchEnabled = true; }
  35789. this.touchEnabled = touchEnabled;
  35790. this.buttons = [0, 1, 2];
  35791. this.angularSensibility = 2000.0;
  35792. }
  35793. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  35794. var _this = this;
  35795. var engine = this.camera.getEngine();
  35796. if (!this._pointerInput) {
  35797. this._pointerInput = function (p, s) {
  35798. var evt = p.event;
  35799. if (engine.isInVRExclusivePointerMode) {
  35800. return;
  35801. }
  35802. if (!_this.touchEnabled && evt.pointerType === "touch") {
  35803. return;
  35804. }
  35805. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35806. return;
  35807. }
  35808. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35809. try {
  35810. evt.srcElement.setPointerCapture(evt.pointerId);
  35811. }
  35812. catch (e) {
  35813. //Nothing to do with the error. Execution will continue.
  35814. }
  35815. _this.previousPosition = {
  35816. x: evt.clientX,
  35817. y: evt.clientY
  35818. };
  35819. if (!noPreventDefault) {
  35820. evt.preventDefault();
  35821. element.focus();
  35822. }
  35823. }
  35824. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35825. try {
  35826. evt.srcElement.releasePointerCapture(evt.pointerId);
  35827. }
  35828. catch (e) {
  35829. //Nothing to do with the error.
  35830. }
  35831. _this.previousPosition = null;
  35832. if (!noPreventDefault) {
  35833. evt.preventDefault();
  35834. }
  35835. }
  35836. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35837. if (!_this.previousPosition || engine.isPointerLock) {
  35838. return;
  35839. }
  35840. var offsetX = evt.clientX - _this.previousPosition.x;
  35841. var offsetY = evt.clientY - _this.previousPosition.y;
  35842. if (_this.camera.getScene().useRightHandedSystem) {
  35843. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  35844. }
  35845. else {
  35846. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  35847. }
  35848. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  35849. _this.previousPosition = {
  35850. x: evt.clientX,
  35851. y: evt.clientY
  35852. };
  35853. if (!noPreventDefault) {
  35854. evt.preventDefault();
  35855. }
  35856. }
  35857. };
  35858. }
  35859. this._onMouseMove = function (evt) {
  35860. if (!engine.isPointerLock) {
  35861. return;
  35862. }
  35863. if (engine.isInVRExclusivePointerMode) {
  35864. return;
  35865. }
  35866. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35867. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35868. if (_this.camera.getScene().useRightHandedSystem) {
  35869. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  35870. }
  35871. else {
  35872. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  35873. }
  35874. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  35875. _this.previousPosition = null;
  35876. if (!noPreventDefault) {
  35877. evt.preventDefault();
  35878. }
  35879. };
  35880. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  35881. element.addEventListener("mousemove", this._onMouseMove, false);
  35882. };
  35883. FreeCameraMouseInput.prototype.detachControl = function (element) {
  35884. if (this._observer && element) {
  35885. this.camera.getScene().onPointerObservable.remove(this._observer);
  35886. element.removeEventListener("mousemove", this._onMouseMove);
  35887. this._observer = null;
  35888. this._onMouseMove = null;
  35889. this.previousPosition = null;
  35890. }
  35891. };
  35892. FreeCameraMouseInput.prototype.getClassName = function () {
  35893. return "FreeCameraMouseInput";
  35894. };
  35895. FreeCameraMouseInput.prototype.getSimpleName = function () {
  35896. return "mouse";
  35897. };
  35898. __decorate([
  35899. BABYLON.serialize()
  35900. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  35901. __decorate([
  35902. BABYLON.serialize()
  35903. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  35904. return FreeCameraMouseInput;
  35905. }());
  35906. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  35907. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  35908. })(BABYLON || (BABYLON = {}));
  35909. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  35910. var BABYLON;
  35911. (function (BABYLON) {
  35912. var FreeCameraKeyboardMoveInput = (function () {
  35913. function FreeCameraKeyboardMoveInput() {
  35914. this._keys = new Array();
  35915. this.keysUp = [38];
  35916. this.keysDown = [40];
  35917. this.keysLeft = [37];
  35918. this.keysRight = [39];
  35919. }
  35920. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35921. var _this = this;
  35922. if (this._onCanvasBlurObserver) {
  35923. return;
  35924. }
  35925. this._scene = this.camera.getScene();
  35926. this._engine = this._scene.getEngine();
  35927. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35928. _this._keys = [];
  35929. });
  35930. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35931. var evt = info.event;
  35932. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35933. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35934. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35935. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35936. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  35937. var index = _this._keys.indexOf(evt.keyCode);
  35938. if (index === -1) {
  35939. _this._keys.push(evt.keyCode);
  35940. }
  35941. if (!noPreventDefault) {
  35942. evt.preventDefault();
  35943. }
  35944. }
  35945. }
  35946. else {
  35947. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35948. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35949. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35950. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  35951. var index = _this._keys.indexOf(evt.keyCode);
  35952. if (index >= 0) {
  35953. _this._keys.splice(index, 1);
  35954. }
  35955. if (!noPreventDefault) {
  35956. evt.preventDefault();
  35957. }
  35958. }
  35959. }
  35960. });
  35961. };
  35962. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35963. if (this._scene) {
  35964. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35965. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35966. this._onKeyboardObserver = null;
  35967. this._onCanvasBlurObserver = null;
  35968. }
  35969. this._keys = [];
  35970. };
  35971. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35972. if (this._onKeyboardObserver) {
  35973. var camera = this.camera;
  35974. // Keyboard
  35975. for (var index = 0; index < this._keys.length; index++) {
  35976. var keyCode = this._keys[index];
  35977. var speed = camera._computeLocalCameraSpeed();
  35978. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35979. camera._localDirection.copyFromFloats(-speed, 0, 0);
  35980. }
  35981. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35982. camera._localDirection.copyFromFloats(0, 0, speed);
  35983. }
  35984. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35985. camera._localDirection.copyFromFloats(speed, 0, 0);
  35986. }
  35987. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35988. camera._localDirection.copyFromFloats(0, 0, -speed);
  35989. }
  35990. if (camera.getScene().useRightHandedSystem) {
  35991. camera._localDirection.z *= -1;
  35992. }
  35993. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  35994. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  35995. camera.cameraDirection.addInPlace(camera._transformedDirection);
  35996. }
  35997. }
  35998. };
  35999. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  36000. return "FreeCameraKeyboardMoveInput";
  36001. };
  36002. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  36003. this._keys = [];
  36004. };
  36005. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36006. return "keyboard";
  36007. };
  36008. __decorate([
  36009. BABYLON.serialize()
  36010. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36011. __decorate([
  36012. BABYLON.serialize()
  36013. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36014. __decorate([
  36015. BABYLON.serialize()
  36016. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36017. __decorate([
  36018. BABYLON.serialize()
  36019. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36020. return FreeCameraKeyboardMoveInput;
  36021. }());
  36022. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  36023. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  36024. })(BABYLON || (BABYLON = {}));
  36025. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  36026. var BABYLON;
  36027. (function (BABYLON) {
  36028. var FreeCameraInputsManager = (function (_super) {
  36029. __extends(FreeCameraInputsManager, _super);
  36030. function FreeCameraInputsManager(camera) {
  36031. return _super.call(this, camera) || this;
  36032. }
  36033. FreeCameraInputsManager.prototype.addKeyboard = function () {
  36034. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  36035. return this;
  36036. };
  36037. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  36038. if (touchEnabled === void 0) { touchEnabled = true; }
  36039. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  36040. return this;
  36041. };
  36042. FreeCameraInputsManager.prototype.addGamepad = function () {
  36043. this.add(new BABYLON.FreeCameraGamepadInput());
  36044. return this;
  36045. };
  36046. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  36047. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  36048. return this;
  36049. };
  36050. FreeCameraInputsManager.prototype.addTouch = function () {
  36051. this.add(new BABYLON.FreeCameraTouchInput());
  36052. return this;
  36053. };
  36054. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  36055. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  36056. return this;
  36057. };
  36058. return FreeCameraInputsManager;
  36059. }(BABYLON.CameraInputsManager));
  36060. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  36061. })(BABYLON || (BABYLON = {}));
  36062. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  36063. /// <reference path="babylon.camera.ts" />
  36064. var BABYLON;
  36065. (function (BABYLON) {
  36066. var TargetCamera = (function (_super) {
  36067. __extends(TargetCamera, _super);
  36068. function TargetCamera(name, position, scene) {
  36069. var _this = _super.call(this, name, position, scene) || this;
  36070. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36071. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  36072. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  36073. _this.speed = 2.0;
  36074. _this.noRotationConstraint = false;
  36075. _this.lockedTarget = null;
  36076. _this._currentTarget = BABYLON.Vector3.Zero();
  36077. _this._viewMatrix = BABYLON.Matrix.Zero();
  36078. _this._camMatrix = BABYLON.Matrix.Zero();
  36079. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  36080. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  36081. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  36082. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  36083. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  36084. _this._lookAtTemp = BABYLON.Matrix.Zero();
  36085. _this._tempMatrix = BABYLON.Matrix.Zero();
  36086. return _this;
  36087. }
  36088. TargetCamera.prototype.getFrontPosition = function (distance) {
  36089. var direction = this.getTarget().subtract(this.position);
  36090. direction.normalize();
  36091. direction.scaleInPlace(distance);
  36092. return this.globalPosition.add(direction);
  36093. };
  36094. TargetCamera.prototype._getLockedTargetPosition = function () {
  36095. if (!this.lockedTarget) {
  36096. return null;
  36097. }
  36098. if (this.lockedTarget.absolutePosition) {
  36099. this.lockedTarget.computeWorldMatrix();
  36100. }
  36101. return this.lockedTarget.absolutePosition || this.lockedTarget;
  36102. };
  36103. TargetCamera.prototype.storeState = function () {
  36104. this._storedPosition = this.position.clone();
  36105. this._storedRotation = this.rotation.clone();
  36106. if (this.rotationQuaternion) {
  36107. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  36108. }
  36109. return _super.prototype.storeState.call(this);
  36110. };
  36111. /**
  36112. * Restored camera state. You must call storeState() first
  36113. */
  36114. TargetCamera.prototype._restoreStateValues = function () {
  36115. if (!_super.prototype._restoreStateValues.call(this)) {
  36116. return false;
  36117. }
  36118. this.position = this._storedPosition.clone();
  36119. this.rotation = this._storedRotation.clone();
  36120. if (this.rotationQuaternion) {
  36121. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  36122. }
  36123. this.cameraDirection.copyFromFloats(0, 0, 0);
  36124. this.cameraRotation.copyFromFloats(0, 0);
  36125. return true;
  36126. };
  36127. // Cache
  36128. TargetCamera.prototype._initCache = function () {
  36129. _super.prototype._initCache.call(this);
  36130. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36131. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36132. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36133. };
  36134. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  36135. if (!ignoreParentClass) {
  36136. _super.prototype._updateCache.call(this);
  36137. }
  36138. var lockedTargetPosition = this._getLockedTargetPosition();
  36139. if (!lockedTargetPosition) {
  36140. this._cache.lockedTarget = null;
  36141. }
  36142. else {
  36143. if (!this._cache.lockedTarget) {
  36144. this._cache.lockedTarget = lockedTargetPosition.clone();
  36145. }
  36146. else {
  36147. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  36148. }
  36149. }
  36150. this._cache.rotation.copyFrom(this.rotation);
  36151. if (this.rotationQuaternion)
  36152. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36153. };
  36154. // Synchronized
  36155. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  36156. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  36157. return false;
  36158. }
  36159. var lockedTargetPosition = this._getLockedTargetPosition();
  36160. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  36161. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  36162. };
  36163. // Methods
  36164. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  36165. var engine = this.getEngine();
  36166. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  36167. };
  36168. // Target
  36169. TargetCamera.prototype.setTarget = function (target) {
  36170. this.upVector.normalize();
  36171. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  36172. this._camMatrix.invert();
  36173. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  36174. var vDir = target.subtract(this.position);
  36175. if (vDir.x >= 0.0) {
  36176. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  36177. }
  36178. else {
  36179. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  36180. }
  36181. this.rotation.z = 0;
  36182. if (isNaN(this.rotation.x)) {
  36183. this.rotation.x = 0;
  36184. }
  36185. if (isNaN(this.rotation.y)) {
  36186. this.rotation.y = 0;
  36187. }
  36188. if (isNaN(this.rotation.z)) {
  36189. this.rotation.z = 0;
  36190. }
  36191. if (this.rotationQuaternion) {
  36192. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36193. }
  36194. };
  36195. /**
  36196. * Return the current target position of the camera. This value is expressed in local space.
  36197. */
  36198. TargetCamera.prototype.getTarget = function () {
  36199. return this._currentTarget;
  36200. };
  36201. TargetCamera.prototype._decideIfNeedsToMove = function () {
  36202. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36203. };
  36204. TargetCamera.prototype._updatePosition = function () {
  36205. if (this.parent) {
  36206. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  36207. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  36208. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  36209. return;
  36210. }
  36211. this.position.addInPlace(this.cameraDirection);
  36212. };
  36213. TargetCamera.prototype._checkInputs = function () {
  36214. var needToMove = this._decideIfNeedsToMove();
  36215. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  36216. // Move
  36217. if (needToMove) {
  36218. this._updatePosition();
  36219. }
  36220. // Rotate
  36221. if (needToRotate) {
  36222. this.rotation.x += this.cameraRotation.x;
  36223. this.rotation.y += this.cameraRotation.y;
  36224. //rotate, if quaternion is set and rotation was used
  36225. if (this.rotationQuaternion) {
  36226. var len = this.rotation.lengthSquared();
  36227. if (len) {
  36228. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36229. }
  36230. }
  36231. if (!this.noRotationConstraint) {
  36232. var limit = (Math.PI / 2) * 0.95;
  36233. if (this.rotation.x > limit)
  36234. this.rotation.x = limit;
  36235. if (this.rotation.x < -limit)
  36236. this.rotation.x = -limit;
  36237. }
  36238. }
  36239. // Inertia
  36240. if (needToMove) {
  36241. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  36242. this.cameraDirection.x = 0;
  36243. }
  36244. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  36245. this.cameraDirection.y = 0;
  36246. }
  36247. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  36248. this.cameraDirection.z = 0;
  36249. }
  36250. this.cameraDirection.scaleInPlace(this.inertia);
  36251. }
  36252. if (needToRotate) {
  36253. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  36254. this.cameraRotation.x = 0;
  36255. }
  36256. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  36257. this.cameraRotation.y = 0;
  36258. }
  36259. this.cameraRotation.scaleInPlace(this.inertia);
  36260. }
  36261. _super.prototype._checkInputs.call(this);
  36262. };
  36263. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  36264. if (this.rotationQuaternion) {
  36265. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  36266. //update the up vector!
  36267. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  36268. }
  36269. else {
  36270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  36271. }
  36272. };
  36273. TargetCamera.prototype._getViewMatrix = function () {
  36274. if (!this.lockedTarget) {
  36275. // Compute
  36276. this._updateCameraRotationMatrix();
  36277. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  36278. // Computing target and final matrix
  36279. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  36280. }
  36281. else {
  36282. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  36283. }
  36284. if (this.getScene().useRightHandedSystem) {
  36285. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36286. }
  36287. else {
  36288. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36289. }
  36290. return this._viewMatrix;
  36291. };
  36292. /**
  36293. * @override
  36294. * Override Camera.createRigCamera
  36295. */
  36296. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36297. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  36298. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  36299. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  36300. if (!this.rotationQuaternion) {
  36301. this.rotationQuaternion = new BABYLON.Quaternion();
  36302. }
  36303. rigCamera._cameraRigParams = {};
  36304. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  36305. }
  36306. return rigCamera;
  36307. }
  36308. return null;
  36309. };
  36310. /**
  36311. * @override
  36312. * Override Camera._updateRigCameras
  36313. */
  36314. TargetCamera.prototype._updateRigCameras = function () {
  36315. var camLeft = this._rigCameras[0];
  36316. var camRight = this._rigCameras[1];
  36317. switch (this.cameraRigMode) {
  36318. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36319. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36320. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36321. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36322. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  36323. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  36324. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  36325. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  36326. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  36327. camLeft.setTarget(this.getTarget());
  36328. camRight.setTarget(this.getTarget());
  36329. break;
  36330. case BABYLON.Camera.RIG_MODE_VR:
  36331. if (camLeft.rotationQuaternion) {
  36332. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36333. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36334. }
  36335. else {
  36336. camLeft.rotation.copyFrom(this.rotation);
  36337. camRight.rotation.copyFrom(this.rotation);
  36338. }
  36339. camLeft.position.copyFrom(this.position);
  36340. camRight.position.copyFrom(this.position);
  36341. break;
  36342. }
  36343. _super.prototype._updateRigCameras.call(this);
  36344. };
  36345. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  36346. if (!this._rigCamTransformMatrix) {
  36347. this._rigCamTransformMatrix = new BABYLON.Matrix();
  36348. }
  36349. var target = this.getTarget();
  36350. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  36351. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  36352. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  36353. };
  36354. TargetCamera.prototype.getClassName = function () {
  36355. return "TargetCamera";
  36356. };
  36357. __decorate([
  36358. BABYLON.serializeAsVector3()
  36359. ], TargetCamera.prototype, "rotation", void 0);
  36360. __decorate([
  36361. BABYLON.serialize()
  36362. ], TargetCamera.prototype, "speed", void 0);
  36363. __decorate([
  36364. BABYLON.serializeAsMeshReference("lockedTargetId")
  36365. ], TargetCamera.prototype, "lockedTarget", void 0);
  36366. return TargetCamera;
  36367. }(BABYLON.Camera));
  36368. BABYLON.TargetCamera = TargetCamera;
  36369. })(BABYLON || (BABYLON = {}));
  36370. //# sourceMappingURL=babylon.targetCamera.js.map
  36371. var BABYLON;
  36372. (function (BABYLON) {
  36373. var FreeCamera = (function (_super) {
  36374. __extends(FreeCamera, _super);
  36375. function FreeCamera(name, position, scene) {
  36376. var _this = _super.call(this, name, position, scene) || this;
  36377. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  36378. _this.checkCollisions = false;
  36379. _this.applyGravity = false;
  36380. _this._needMoveForGravity = false;
  36381. _this._oldPosition = BABYLON.Vector3.Zero();
  36382. _this._diffPosition = BABYLON.Vector3.Zero();
  36383. _this._newPosition = BABYLON.Vector3.Zero();
  36384. // Collisions
  36385. _this._collisionMask = -1;
  36386. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  36387. if (collidedMesh === void 0) { collidedMesh = null; }
  36388. //TODO move this to the collision coordinator!
  36389. if (_this.getScene().workerCollisions)
  36390. newPosition.multiplyInPlace(_this._collider.radius);
  36391. var updatePosition = function (newPos) {
  36392. _this._newPosition.copyFrom(newPos);
  36393. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  36394. var oldPosition = _this.position.clone();
  36395. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  36396. _this.position.addInPlace(_this._diffPosition);
  36397. if (_this.onCollide && collidedMesh) {
  36398. _this.onCollide(collidedMesh);
  36399. }
  36400. }
  36401. };
  36402. updatePosition(newPosition);
  36403. };
  36404. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  36405. _this.inputs.addKeyboard().addMouse();
  36406. return _this;
  36407. }
  36408. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  36409. //-- begin properties for backward compatibility for inputs
  36410. get: function () {
  36411. var mouse = this.inputs.attached["mouse"];
  36412. if (mouse)
  36413. return mouse.angularSensibility;
  36414. },
  36415. set: function (value) {
  36416. var mouse = this.inputs.attached["mouse"];
  36417. if (mouse)
  36418. mouse.angularSensibility = value;
  36419. },
  36420. enumerable: true,
  36421. configurable: true
  36422. });
  36423. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  36424. get: function () {
  36425. var keyboard = this.inputs.attached["keyboard"];
  36426. if (keyboard)
  36427. return keyboard.keysUp;
  36428. },
  36429. set: function (value) {
  36430. var keyboard = this.inputs.attached["keyboard"];
  36431. if (keyboard)
  36432. keyboard.keysUp = value;
  36433. },
  36434. enumerable: true,
  36435. configurable: true
  36436. });
  36437. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  36438. get: function () {
  36439. var keyboard = this.inputs.attached["keyboard"];
  36440. if (keyboard)
  36441. return keyboard.keysDown;
  36442. },
  36443. set: function (value) {
  36444. var keyboard = this.inputs.attached["keyboard"];
  36445. if (keyboard)
  36446. keyboard.keysDown = value;
  36447. },
  36448. enumerable: true,
  36449. configurable: true
  36450. });
  36451. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  36452. get: function () {
  36453. var keyboard = this.inputs.attached["keyboard"];
  36454. if (keyboard)
  36455. return keyboard.keysLeft;
  36456. },
  36457. set: function (value) {
  36458. var keyboard = this.inputs.attached["keyboard"];
  36459. if (keyboard)
  36460. keyboard.keysLeft = value;
  36461. },
  36462. enumerable: true,
  36463. configurable: true
  36464. });
  36465. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  36466. get: function () {
  36467. var keyboard = this.inputs.attached["keyboard"];
  36468. if (keyboard)
  36469. return keyboard.keysRight;
  36470. },
  36471. set: function (value) {
  36472. var keyboard = this.inputs.attached["keyboard"];
  36473. if (keyboard)
  36474. keyboard.keysRight = value;
  36475. },
  36476. enumerable: true,
  36477. configurable: true
  36478. });
  36479. // Controls
  36480. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36481. this.inputs.attachElement(element, noPreventDefault);
  36482. };
  36483. FreeCamera.prototype.detachControl = function (element) {
  36484. this.inputs.detachElement(element);
  36485. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36486. this.cameraRotation = new BABYLON.Vector2(0, 0);
  36487. };
  36488. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  36489. get: function () {
  36490. return this._collisionMask;
  36491. },
  36492. set: function (mask) {
  36493. this._collisionMask = !isNaN(mask) ? mask : -1;
  36494. },
  36495. enumerable: true,
  36496. configurable: true
  36497. });
  36498. FreeCamera.prototype._collideWithWorld = function (displacement) {
  36499. var globalPosition;
  36500. if (this.parent) {
  36501. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  36502. }
  36503. else {
  36504. globalPosition = this.position;
  36505. }
  36506. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  36507. if (!this._collider) {
  36508. this._collider = new BABYLON.Collider();
  36509. }
  36510. this._collider.radius = this.ellipsoid;
  36511. this._collider.collisionMask = this._collisionMask;
  36512. //no need for clone, as long as gravity is not on.
  36513. var actualDisplacement = displacement;
  36514. //add gravity to the direction to prevent the dual-collision checking
  36515. if (this.applyGravity) {
  36516. //this prevents mending with cameraDirection, a global variable of the free camera class.
  36517. actualDisplacement = displacement.add(this.getScene().gravity);
  36518. }
  36519. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36520. };
  36521. FreeCamera.prototype._checkInputs = function () {
  36522. if (!this._localDirection) {
  36523. this._localDirection = BABYLON.Vector3.Zero();
  36524. this._transformedDirection = BABYLON.Vector3.Zero();
  36525. }
  36526. this.inputs.checkInputs();
  36527. _super.prototype._checkInputs.call(this);
  36528. };
  36529. FreeCamera.prototype._decideIfNeedsToMove = function () {
  36530. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36531. };
  36532. FreeCamera.prototype._updatePosition = function () {
  36533. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  36534. this._collideWithWorld(this.cameraDirection);
  36535. }
  36536. else {
  36537. _super.prototype._updatePosition.call(this);
  36538. }
  36539. };
  36540. FreeCamera.prototype.dispose = function () {
  36541. this.inputs.clear();
  36542. _super.prototype.dispose.call(this);
  36543. };
  36544. FreeCamera.prototype.getClassName = function () {
  36545. return "FreeCamera";
  36546. };
  36547. __decorate([
  36548. BABYLON.serializeAsVector3()
  36549. ], FreeCamera.prototype, "ellipsoid", void 0);
  36550. __decorate([
  36551. BABYLON.serialize()
  36552. ], FreeCamera.prototype, "checkCollisions", void 0);
  36553. __decorate([
  36554. BABYLON.serialize()
  36555. ], FreeCamera.prototype, "applyGravity", void 0);
  36556. return FreeCamera;
  36557. }(BABYLON.TargetCamera));
  36558. BABYLON.FreeCamera = FreeCamera;
  36559. })(BABYLON || (BABYLON = {}));
  36560. //# sourceMappingURL=babylon.freeCamera.js.map
  36561. var BABYLON;
  36562. (function (BABYLON) {
  36563. var ArcRotateCameraKeyboardMoveInput = (function () {
  36564. function ArcRotateCameraKeyboardMoveInput() {
  36565. this._keys = new Array();
  36566. this.keysUp = [38];
  36567. this.keysDown = [40];
  36568. this.keysLeft = [37];
  36569. this.keysRight = [39];
  36570. this.keysReset = [220];
  36571. this.panningSensibility = 50.0;
  36572. this.zoomingSensibility = 25.0;
  36573. this.useAltToZoom = true;
  36574. }
  36575. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36576. var _this = this;
  36577. if (this._onCanvasBlurObserver) {
  36578. return;
  36579. }
  36580. this._scene = this.camera.getScene();
  36581. this._engine = this._scene.getEngine();
  36582. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36583. _this._keys = [];
  36584. });
  36585. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36586. var evt = info.event;
  36587. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36588. _this._ctrlPressed = evt.ctrlKey;
  36589. _this._altPressed = evt.altKey;
  36590. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36591. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36592. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36593. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36594. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36595. var index = _this._keys.indexOf(evt.keyCode);
  36596. if (index === -1) {
  36597. _this._keys.push(evt.keyCode);
  36598. }
  36599. if (evt.preventDefault) {
  36600. if (!noPreventDefault) {
  36601. evt.preventDefault();
  36602. }
  36603. }
  36604. }
  36605. }
  36606. else {
  36607. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36608. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36609. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36610. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36611. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36612. var index = _this._keys.indexOf(evt.keyCode);
  36613. if (index >= 0) {
  36614. _this._keys.splice(index, 1);
  36615. }
  36616. if (evt.preventDefault) {
  36617. if (!noPreventDefault) {
  36618. evt.preventDefault();
  36619. }
  36620. }
  36621. }
  36622. }
  36623. });
  36624. };
  36625. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36626. if (this._scene) {
  36627. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36628. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36629. this._onKeyboardObserver = null;
  36630. this._onCanvasBlurObserver = null;
  36631. }
  36632. this._keys = [];
  36633. };
  36634. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36635. if (this._onKeyboardObserver) {
  36636. var camera = this.camera;
  36637. for (var index = 0; index < this._keys.length; index++) {
  36638. var keyCode = this._keys[index];
  36639. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36640. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36641. camera.inertialPanningX -= 1 / this.panningSensibility;
  36642. }
  36643. else {
  36644. camera.inertialAlphaOffset -= 0.01;
  36645. }
  36646. }
  36647. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36648. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36649. camera.inertialPanningY += 1 / this.panningSensibility;
  36650. }
  36651. else if (this._altPressed && this.useAltToZoom) {
  36652. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  36653. }
  36654. else {
  36655. camera.inertialBetaOffset -= 0.01;
  36656. }
  36657. }
  36658. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36659. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36660. camera.inertialPanningX += 1 / this.panningSensibility;
  36661. }
  36662. else {
  36663. camera.inertialAlphaOffset += 0.01;
  36664. }
  36665. }
  36666. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36667. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36668. camera.inertialPanningY -= 1 / this.panningSensibility;
  36669. }
  36670. else if (this._altPressed && this.useAltToZoom) {
  36671. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  36672. }
  36673. else {
  36674. camera.inertialBetaOffset += 0.01;
  36675. }
  36676. }
  36677. else if (this.keysReset.indexOf(keyCode) !== -1) {
  36678. camera.restoreState();
  36679. }
  36680. }
  36681. }
  36682. };
  36683. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  36684. return "ArcRotateCameraKeyboardMoveInput";
  36685. };
  36686. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36687. return "keyboard";
  36688. };
  36689. __decorate([
  36690. BABYLON.serialize()
  36691. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36692. __decorate([
  36693. BABYLON.serialize()
  36694. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36695. __decorate([
  36696. BABYLON.serialize()
  36697. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36698. __decorate([
  36699. BABYLON.serialize()
  36700. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36701. __decorate([
  36702. BABYLON.serialize()
  36703. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  36704. __decorate([
  36705. BABYLON.serialize()
  36706. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  36707. __decorate([
  36708. BABYLON.serialize()
  36709. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  36710. __decorate([
  36711. BABYLON.serialize()
  36712. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  36713. return ArcRotateCameraKeyboardMoveInput;
  36714. }());
  36715. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  36716. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  36717. })(BABYLON || (BABYLON = {}));
  36718. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  36719. var BABYLON;
  36720. (function (BABYLON) {
  36721. var ArcRotateCameraMouseWheelInput = (function () {
  36722. function ArcRotateCameraMouseWheelInput() {
  36723. this.wheelPrecision = 3.0;
  36724. /**
  36725. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  36726. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  36727. */
  36728. this.wheelDeltaPercentage = 0;
  36729. }
  36730. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  36731. var _this = this;
  36732. this._wheel = function (p, s) {
  36733. //sanity check - this should be a PointerWheel event.
  36734. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  36735. return;
  36736. var event = p.event;
  36737. var delta = 0;
  36738. if (event.wheelDelta) {
  36739. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  36740. }
  36741. else if (event.detail) {
  36742. delta = -event.detail / _this.wheelPrecision;
  36743. }
  36744. if (delta)
  36745. _this.camera.inertialRadiusOffset += delta;
  36746. if (event.preventDefault) {
  36747. if (!noPreventDefault) {
  36748. event.preventDefault();
  36749. }
  36750. }
  36751. };
  36752. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  36753. };
  36754. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  36755. if (this._observer && element) {
  36756. this.camera.getScene().onPointerObservable.remove(this._observer);
  36757. this._observer = null;
  36758. this._wheel = null;
  36759. }
  36760. };
  36761. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  36762. return "ArcRotateCameraMouseWheelInput";
  36763. };
  36764. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  36765. return "mousewheel";
  36766. };
  36767. __decorate([
  36768. BABYLON.serialize()
  36769. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  36770. __decorate([
  36771. BABYLON.serialize()
  36772. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  36773. return ArcRotateCameraMouseWheelInput;
  36774. }());
  36775. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  36776. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  36777. })(BABYLON || (BABYLON = {}));
  36778. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  36779. var BABYLON;
  36780. (function (BABYLON) {
  36781. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  36782. var ArcRotateCameraPointersInput = (function () {
  36783. function ArcRotateCameraPointersInput() {
  36784. this.buttons = [0, 1, 2];
  36785. this.angularSensibilityX = 1000.0;
  36786. this.angularSensibilityY = 1000.0;
  36787. this.pinchPrecision = 12.0;
  36788. /**
  36789. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  36790. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  36791. */
  36792. this.pinchDeltaPercentage = 0;
  36793. this.panningSensibility = 1000.0;
  36794. this.multiTouchPanning = true;
  36795. this.multiTouchPanAndZoom = true;
  36796. this._isPanClick = false;
  36797. this.pinchInwards = true;
  36798. }
  36799. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  36800. var _this = this;
  36801. var engine = this.camera.getEngine();
  36802. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  36803. var pointA, pointB;
  36804. var previousPinchSquaredDistance = 0;
  36805. var initialDistance = 0;
  36806. var twoFingerActivityCount = 0;
  36807. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  36808. this._pointerInput = function (p, s) {
  36809. var evt = p.event;
  36810. if (engine.isInVRExclusivePointerMode) {
  36811. return;
  36812. }
  36813. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36814. return;
  36815. }
  36816. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  36817. try {
  36818. evt.srcElement.setPointerCapture(evt.pointerId);
  36819. }
  36820. catch (e) {
  36821. //Nothing to do with the error. Execution will continue.
  36822. }
  36823. // Manage panning with pan button click
  36824. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  36825. // manage pointers
  36826. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  36827. if (pointA === undefined) {
  36828. pointA = cacheSoloPointer;
  36829. }
  36830. else if (pointB === undefined) {
  36831. pointB = cacheSoloPointer;
  36832. }
  36833. if (!noPreventDefault) {
  36834. evt.preventDefault();
  36835. element.focus();
  36836. }
  36837. }
  36838. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  36839. _this.camera.restoreState();
  36840. }
  36841. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  36842. try {
  36843. evt.srcElement.releasePointerCapture(evt.pointerId);
  36844. }
  36845. catch (e) {
  36846. //Nothing to do with the error.
  36847. }
  36848. cacheSoloPointer = null;
  36849. previousPinchSquaredDistance = 0;
  36850. previousMultiTouchPanPosition.isPaning = false;
  36851. previousMultiTouchPanPosition.isPinching = false;
  36852. twoFingerActivityCount = 0;
  36853. initialDistance = 0;
  36854. if (p.event.pointerType !== "touch") {
  36855. pointB = undefined; // Mouse and pen are mono pointer
  36856. }
  36857. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  36858. //but emptying completly pointers collection is required to fix a bug on iPhone :
  36859. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  36860. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  36861. if (engine.badOS) {
  36862. pointA = pointB = undefined;
  36863. }
  36864. else {
  36865. //only remove the impacted pointer in case of multitouch allowing on most
  36866. //platforms switching from rotate to zoom and pan seamlessly.
  36867. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  36868. pointA = pointB;
  36869. pointB = undefined;
  36870. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  36871. }
  36872. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  36873. pointB = undefined;
  36874. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  36875. }
  36876. else {
  36877. pointA = pointB = undefined;
  36878. }
  36879. }
  36880. if (!noPreventDefault) {
  36881. evt.preventDefault();
  36882. }
  36883. }
  36884. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36885. if (!noPreventDefault) {
  36886. evt.preventDefault();
  36887. }
  36888. // One button down
  36889. if (pointA && pointB === undefined) {
  36890. if (_this.panningSensibility !== 0 &&
  36891. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  36892. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  36893. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  36894. }
  36895. else {
  36896. var offsetX = evt.clientX - cacheSoloPointer.x;
  36897. var offsetY = evt.clientY - cacheSoloPointer.y;
  36898. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  36899. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  36900. }
  36901. cacheSoloPointer.x = evt.clientX;
  36902. cacheSoloPointer.y = evt.clientY;
  36903. }
  36904. else if (pointA && pointB) {
  36905. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  36906. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  36907. ed.x = evt.clientX;
  36908. ed.y = evt.clientY;
  36909. var direction = _this.pinchInwards ? 1 : -1;
  36910. var distX = pointA.x - pointB.x;
  36911. var distY = pointA.y - pointB.y;
  36912. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  36913. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  36914. if (previousPinchSquaredDistance === 0) {
  36915. initialDistance = pinchDistance;
  36916. previousPinchSquaredDistance = pinchSquaredDistance;
  36917. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  36918. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  36919. return;
  36920. }
  36921. if (_this.multiTouchPanAndZoom) {
  36922. if (_this.pinchDeltaPercentage) {
  36923. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  36924. }
  36925. else {
  36926. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  36927. (_this.pinchPrecision *
  36928. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  36929. direction);
  36930. }
  36931. if (_this.panningSensibility !== 0) {
  36932. var pointersCenterX = (pointA.x + pointB.x) / 2;
  36933. var pointersCenterY = (pointA.y + pointB.y) / 2;
  36934. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  36935. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  36936. previousMultiTouchPanPosition.x = pointersCenterX;
  36937. previousMultiTouchPanPosition.y = pointersCenterY;
  36938. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  36939. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  36940. }
  36941. }
  36942. else {
  36943. twoFingerActivityCount++;
  36944. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  36945. if (_this.pinchDeltaPercentage) {
  36946. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  36947. }
  36948. else {
  36949. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  36950. (_this.pinchPrecision *
  36951. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  36952. direction);
  36953. }
  36954. previousMultiTouchPanPosition.isPaning = false;
  36955. previousMultiTouchPanPosition.isPinching = true;
  36956. }
  36957. else {
  36958. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  36959. if (!previousMultiTouchPanPosition.isPaning) {
  36960. previousMultiTouchPanPosition.isPaning = true;
  36961. previousMultiTouchPanPosition.isPinching = false;
  36962. previousMultiTouchPanPosition.x = ed.x;
  36963. previousMultiTouchPanPosition.y = ed.y;
  36964. return;
  36965. }
  36966. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  36967. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  36968. }
  36969. }
  36970. if (cacheSoloPointer.pointerId === evt.pointerId) {
  36971. previousMultiTouchPanPosition.x = ed.x;
  36972. previousMultiTouchPanPosition.y = ed.y;
  36973. }
  36974. }
  36975. previousPinchSquaredDistance = pinchSquaredDistance;
  36976. }
  36977. }
  36978. };
  36979. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  36980. this._onContextMenu = function (evt) {
  36981. evt.preventDefault();
  36982. };
  36983. if (!this.camera._useCtrlForPanning) {
  36984. element.addEventListener("contextmenu", this._onContextMenu, false);
  36985. }
  36986. this._onLostFocus = function () {
  36987. //this._keys = [];
  36988. pointA = pointB = undefined;
  36989. previousPinchSquaredDistance = 0;
  36990. previousMultiTouchPanPosition.isPaning = false;
  36991. previousMultiTouchPanPosition.isPinching = false;
  36992. twoFingerActivityCount = 0;
  36993. cacheSoloPointer = null;
  36994. initialDistance = 0;
  36995. };
  36996. this._onMouseMove = function (evt) {
  36997. if (!engine.isPointerLock) {
  36998. return;
  36999. }
  37000. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37001. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37002. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  37003. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  37004. if (!noPreventDefault) {
  37005. evt.preventDefault();
  37006. }
  37007. };
  37008. this._onGestureStart = function (e) {
  37009. if (window.MSGesture === undefined) {
  37010. return;
  37011. }
  37012. if (!_this._MSGestureHandler) {
  37013. _this._MSGestureHandler = new MSGesture();
  37014. _this._MSGestureHandler.target = element;
  37015. }
  37016. _this._MSGestureHandler.addPointer(e.pointerId);
  37017. };
  37018. this._onGesture = function (e) {
  37019. _this.camera.radius *= e.scale;
  37020. if (e.preventDefault) {
  37021. if (!noPreventDefault) {
  37022. e.stopPropagation();
  37023. e.preventDefault();
  37024. }
  37025. }
  37026. };
  37027. element.addEventListener("mousemove", this._onMouseMove, false);
  37028. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  37029. element.addEventListener("MSGestureChange", this._onGesture, false);
  37030. BABYLON.Tools.RegisterTopRootEvents([
  37031. { name: "blur", handler: this._onLostFocus }
  37032. ]);
  37033. };
  37034. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  37035. BABYLON.Tools.UnregisterTopRootEvents([
  37036. { name: "blur", handler: this._onLostFocus }
  37037. ]);
  37038. if (element && this._observer) {
  37039. this.camera.getScene().onPointerObservable.remove(this._observer);
  37040. this._observer = null;
  37041. element.removeEventListener("contextmenu", this._onContextMenu);
  37042. element.removeEventListener("mousemove", this._onMouseMove);
  37043. element.removeEventListener("MSPointerDown", this._onGestureStart);
  37044. element.removeEventListener("MSGestureChange", this._onGesture);
  37045. this._isPanClick = false;
  37046. this.pinchInwards = true;
  37047. this._onMouseMove = null;
  37048. this._onGestureStart = null;
  37049. this._onGesture = null;
  37050. this._MSGestureHandler = null;
  37051. this._onLostFocus = null;
  37052. this._onContextMenu = null;
  37053. }
  37054. };
  37055. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  37056. return "ArcRotateCameraPointersInput";
  37057. };
  37058. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  37059. return "pointers";
  37060. };
  37061. __decorate([
  37062. BABYLON.serialize()
  37063. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  37064. __decorate([
  37065. BABYLON.serialize()
  37066. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  37067. __decorate([
  37068. BABYLON.serialize()
  37069. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  37070. __decorate([
  37071. BABYLON.serialize()
  37072. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  37073. __decorate([
  37074. BABYLON.serialize()
  37075. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  37076. __decorate([
  37077. BABYLON.serialize()
  37078. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  37079. __decorate([
  37080. BABYLON.serialize()
  37081. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  37082. __decorate([
  37083. BABYLON.serialize()
  37084. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  37085. return ArcRotateCameraPointersInput;
  37086. }());
  37087. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  37088. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  37089. })(BABYLON || (BABYLON = {}));
  37090. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  37091. /// <reference path="babylon.targetCamera.ts" />
  37092. /// <reference path="..\Tools\babylon.tools.ts" />
  37093. var BABYLON;
  37094. (function (BABYLON) {
  37095. var ArcRotateCamera = (function (_super) {
  37096. __extends(ArcRotateCamera, _super);
  37097. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  37098. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  37099. _this.inertialAlphaOffset = 0;
  37100. _this.inertialBetaOffset = 0;
  37101. _this.inertialRadiusOffset = 0;
  37102. _this.lowerAlphaLimit = null;
  37103. _this.upperAlphaLimit = null;
  37104. _this.lowerBetaLimit = 0.01;
  37105. _this.upperBetaLimit = Math.PI;
  37106. _this.lowerRadiusLimit = null;
  37107. _this.upperRadiusLimit = null;
  37108. _this.inertialPanningX = 0;
  37109. _this.inertialPanningY = 0;
  37110. _this.pinchToPanMaxDistance = 20;
  37111. _this.panningDistanceLimit = null;
  37112. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  37113. _this.panningInertia = 0.9;
  37114. //-- end properties for backward compatibility for inputs
  37115. _this.zoomOnFactor = 1;
  37116. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  37117. _this.allowUpsideDown = true;
  37118. _this._viewMatrix = new BABYLON.Matrix();
  37119. // Panning
  37120. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  37121. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  37122. _this.checkCollisions = false;
  37123. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37124. _this._previousPosition = BABYLON.Vector3.Zero();
  37125. _this._collisionVelocity = BABYLON.Vector3.Zero();
  37126. _this._newPosition = BABYLON.Vector3.Zero();
  37127. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37128. if (collidedMesh === void 0) { collidedMesh = null; }
  37129. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  37130. newPosition.multiplyInPlace(_this._collider.radius);
  37131. }
  37132. if (!collidedMesh) {
  37133. _this._previousPosition.copyFrom(_this.position);
  37134. }
  37135. else {
  37136. _this.setPosition(newPosition);
  37137. if (_this.onCollide) {
  37138. _this.onCollide(collidedMesh);
  37139. }
  37140. }
  37141. // Recompute because of constraints
  37142. var cosa = Math.cos(_this.alpha);
  37143. var sina = Math.sin(_this.alpha);
  37144. var cosb = Math.cos(_this.beta);
  37145. var sinb = Math.sin(_this.beta);
  37146. if (sinb === 0) {
  37147. sinb = 0.0001;
  37148. }
  37149. var target = _this._getTargetPosition();
  37150. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  37151. _this.position.copyFrom(_this._newPosition);
  37152. var up = _this.upVector;
  37153. if (_this.allowUpsideDown && _this.beta < 0) {
  37154. up = up.clone();
  37155. up = up.negate();
  37156. }
  37157. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  37158. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  37159. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  37160. _this._collisionTriggered = false;
  37161. };
  37162. _this._target = BABYLON.Vector3.Zero();
  37163. if (target) {
  37164. _this.setTarget(target);
  37165. }
  37166. _this.alpha = alpha;
  37167. _this.beta = beta;
  37168. _this.radius = radius;
  37169. _this.getViewMatrix();
  37170. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  37171. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  37172. return _this;
  37173. }
  37174. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  37175. get: function () {
  37176. return this._target;
  37177. },
  37178. set: function (value) {
  37179. this.setTarget(value);
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  37185. //-- begin properties for backward compatibility for inputs
  37186. get: function () {
  37187. var pointers = this.inputs.attached["pointers"];
  37188. if (pointers)
  37189. return pointers.angularSensibilityX;
  37190. },
  37191. set: function (value) {
  37192. var pointers = this.inputs.attached["pointers"];
  37193. if (pointers) {
  37194. pointers.angularSensibilityX = value;
  37195. }
  37196. },
  37197. enumerable: true,
  37198. configurable: true
  37199. });
  37200. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  37201. get: function () {
  37202. var pointers = this.inputs.attached["pointers"];
  37203. if (pointers)
  37204. return pointers.angularSensibilityY;
  37205. },
  37206. set: function (value) {
  37207. var pointers = this.inputs.attached["pointers"];
  37208. if (pointers) {
  37209. pointers.angularSensibilityY = value;
  37210. }
  37211. },
  37212. enumerable: true,
  37213. configurable: true
  37214. });
  37215. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  37216. get: function () {
  37217. var pointers = this.inputs.attached["pointers"];
  37218. if (pointers)
  37219. return pointers.pinchPrecision;
  37220. },
  37221. set: function (value) {
  37222. var pointers = this.inputs.attached["pointers"];
  37223. if (pointers) {
  37224. pointers.pinchPrecision = value;
  37225. }
  37226. },
  37227. enumerable: true,
  37228. configurable: true
  37229. });
  37230. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  37231. get: function () {
  37232. var pointers = this.inputs.attached["pointers"];
  37233. if (pointers)
  37234. return pointers.pinchDeltaPercentage;
  37235. },
  37236. set: function (value) {
  37237. var pointers = this.inputs.attached["pointers"];
  37238. if (pointers) {
  37239. pointers.pinchDeltaPercentage = value;
  37240. }
  37241. },
  37242. enumerable: true,
  37243. configurable: true
  37244. });
  37245. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  37246. get: function () {
  37247. var pointers = this.inputs.attached["pointers"];
  37248. if (pointers)
  37249. return pointers.panningSensibility;
  37250. },
  37251. set: function (value) {
  37252. var pointers = this.inputs.attached["pointers"];
  37253. if (pointers) {
  37254. pointers.panningSensibility = value;
  37255. }
  37256. },
  37257. enumerable: true,
  37258. configurable: true
  37259. });
  37260. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  37261. get: function () {
  37262. var keyboard = this.inputs.attached["keyboard"];
  37263. if (keyboard)
  37264. return keyboard.keysUp;
  37265. },
  37266. set: function (value) {
  37267. var keyboard = this.inputs.attached["keyboard"];
  37268. if (keyboard)
  37269. keyboard.keysUp = value;
  37270. },
  37271. enumerable: true,
  37272. configurable: true
  37273. });
  37274. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  37275. get: function () {
  37276. var keyboard = this.inputs.attached["keyboard"];
  37277. if (keyboard)
  37278. return keyboard.keysDown;
  37279. },
  37280. set: function (value) {
  37281. var keyboard = this.inputs.attached["keyboard"];
  37282. if (keyboard)
  37283. keyboard.keysDown = value;
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  37289. get: function () {
  37290. var keyboard = this.inputs.attached["keyboard"];
  37291. if (keyboard)
  37292. return keyboard.keysLeft;
  37293. },
  37294. set: function (value) {
  37295. var keyboard = this.inputs.attached["keyboard"];
  37296. if (keyboard)
  37297. keyboard.keysLeft = value;
  37298. },
  37299. enumerable: true,
  37300. configurable: true
  37301. });
  37302. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  37303. get: function () {
  37304. var keyboard = this.inputs.attached["keyboard"];
  37305. if (keyboard)
  37306. return keyboard.keysRight;
  37307. },
  37308. set: function (value) {
  37309. var keyboard = this.inputs.attached["keyboard"];
  37310. if (keyboard)
  37311. keyboard.keysRight = value;
  37312. },
  37313. enumerable: true,
  37314. configurable: true
  37315. });
  37316. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  37317. get: function () {
  37318. var mousewheel = this.inputs.attached["mousewheel"];
  37319. if (mousewheel)
  37320. return mousewheel.wheelPrecision;
  37321. },
  37322. set: function (value) {
  37323. var mousewheel = this.inputs.attached["mousewheel"];
  37324. if (mousewheel)
  37325. mousewheel.wheelPrecision = value;
  37326. },
  37327. enumerable: true,
  37328. configurable: true
  37329. });
  37330. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  37331. get: function () {
  37332. var mousewheel = this.inputs.attached["mousewheel"];
  37333. if (mousewheel)
  37334. return mousewheel.wheelDeltaPercentage;
  37335. },
  37336. set: function (value) {
  37337. var mousewheel = this.inputs.attached["mousewheel"];
  37338. if (mousewheel)
  37339. mousewheel.wheelDeltaPercentage = value;
  37340. },
  37341. enumerable: true,
  37342. configurable: true
  37343. });
  37344. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  37345. get: function () {
  37346. return this._bouncingBehavior;
  37347. },
  37348. enumerable: true,
  37349. configurable: true
  37350. });
  37351. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  37352. get: function () {
  37353. return this._bouncingBehavior != null;
  37354. },
  37355. set: function (value) {
  37356. if (value === this.useBouncingBehavior) {
  37357. return;
  37358. }
  37359. if (value) {
  37360. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  37361. this.addBehavior(this._bouncingBehavior);
  37362. }
  37363. else {
  37364. this.removeBehavior(this._bouncingBehavior);
  37365. this._bouncingBehavior = null;
  37366. }
  37367. },
  37368. enumerable: true,
  37369. configurable: true
  37370. });
  37371. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  37372. get: function () {
  37373. return this._framingBehavior;
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  37379. get: function () {
  37380. return this._framingBehavior != null;
  37381. },
  37382. set: function (value) {
  37383. if (value === this.useFramingBehavior) {
  37384. return;
  37385. }
  37386. if (value) {
  37387. this._framingBehavior = new BABYLON.FramingBehavior();
  37388. this.addBehavior(this._framingBehavior);
  37389. }
  37390. else {
  37391. this.removeBehavior(this._framingBehavior);
  37392. this._framingBehavior = null;
  37393. }
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  37399. get: function () {
  37400. return this._autoRotationBehavior;
  37401. },
  37402. enumerable: true,
  37403. configurable: true
  37404. });
  37405. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  37406. get: function () {
  37407. return this._autoRotationBehavior != null;
  37408. },
  37409. set: function (value) {
  37410. if (value === this.useAutoRotationBehavior) {
  37411. return;
  37412. }
  37413. if (value) {
  37414. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  37415. this.addBehavior(this._autoRotationBehavior);
  37416. }
  37417. else {
  37418. this.removeBehavior(this._autoRotationBehavior);
  37419. this._autoRotationBehavior = null;
  37420. }
  37421. },
  37422. enumerable: true,
  37423. configurable: true
  37424. });
  37425. // Cache
  37426. ArcRotateCamera.prototype._initCache = function () {
  37427. _super.prototype._initCache.call(this);
  37428. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37429. this._cache.alpha = undefined;
  37430. this._cache.beta = undefined;
  37431. this._cache.radius = undefined;
  37432. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  37433. };
  37434. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  37435. if (!ignoreParentClass) {
  37436. _super.prototype._updateCache.call(this);
  37437. }
  37438. this._cache._target.copyFrom(this._getTargetPosition());
  37439. this._cache.alpha = this.alpha;
  37440. this._cache.beta = this.beta;
  37441. this._cache.radius = this.radius;
  37442. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  37443. };
  37444. ArcRotateCamera.prototype._getTargetPosition = function () {
  37445. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  37446. var pos = this._targetHost.getAbsolutePosition();
  37447. if (this._targetBoundingCenter) {
  37448. pos.addToRef(this._targetBoundingCenter, this._target);
  37449. }
  37450. else {
  37451. this._target.copyFrom(pos);
  37452. }
  37453. }
  37454. var lockedTargetPosition = this._getLockedTargetPosition();
  37455. if (lockedTargetPosition) {
  37456. return lockedTargetPosition;
  37457. }
  37458. return this._target;
  37459. };
  37460. ArcRotateCamera.prototype.storeState = function () {
  37461. this._storedAlpha = this.alpha;
  37462. this._storedBeta = this.beta;
  37463. this._storedRadius = this.radius;
  37464. this._storedTarget = this._getTargetPosition().clone();
  37465. return _super.prototype.storeState.call(this);
  37466. };
  37467. /**
  37468. * Restored camera state. You must call storeState() first
  37469. */
  37470. ArcRotateCamera.prototype._restoreStateValues = function () {
  37471. if (!_super.prototype._restoreStateValues.call(this)) {
  37472. return false;
  37473. }
  37474. this.alpha = this._storedAlpha;
  37475. this.beta = this._storedBeta;
  37476. this.radius = this._storedRadius;
  37477. this.setTarget(this._storedTarget.clone());
  37478. this.inertialAlphaOffset = 0;
  37479. this.inertialBetaOffset = 0;
  37480. this.inertialRadiusOffset = 0;
  37481. this.inertialPanningX = 0;
  37482. this.inertialPanningY = 0;
  37483. return true;
  37484. };
  37485. // Synchronized
  37486. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  37487. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  37488. return false;
  37489. return this._cache._target.equals(this._getTargetPosition())
  37490. && this._cache.alpha === this.alpha
  37491. && this._cache.beta === this.beta
  37492. && this._cache.radius === this.radius
  37493. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  37494. };
  37495. // Methods
  37496. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  37497. var _this = this;
  37498. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  37499. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  37500. this._useCtrlForPanning = useCtrlForPanning;
  37501. this._panningMouseButton = panningMouseButton;
  37502. this.inputs.attachElement(element, noPreventDefault);
  37503. this._reset = function () {
  37504. _this.inertialAlphaOffset = 0;
  37505. _this.inertialBetaOffset = 0;
  37506. _this.inertialRadiusOffset = 0;
  37507. _this.inertialPanningX = 0;
  37508. _this.inertialPanningY = 0;
  37509. };
  37510. };
  37511. ArcRotateCamera.prototype.detachControl = function (element) {
  37512. this.inputs.detachElement(element);
  37513. if (this._reset) {
  37514. this._reset();
  37515. }
  37516. };
  37517. ArcRotateCamera.prototype._checkInputs = function () {
  37518. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  37519. if (this._collisionTriggered) {
  37520. return;
  37521. }
  37522. this.inputs.checkInputs();
  37523. // Inertia
  37524. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  37525. if (this.getScene().useRightHandedSystem) {
  37526. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37527. }
  37528. else {
  37529. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37530. }
  37531. this.beta += this.inertialBetaOffset;
  37532. this.radius -= this.inertialRadiusOffset;
  37533. this.inertialAlphaOffset *= this.inertia;
  37534. this.inertialBetaOffset *= this.inertia;
  37535. this.inertialRadiusOffset *= this.inertia;
  37536. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  37537. this.inertialAlphaOffset = 0;
  37538. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  37539. this.inertialBetaOffset = 0;
  37540. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  37541. this.inertialRadiusOffset = 0;
  37542. }
  37543. // Panning inertia
  37544. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  37545. if (!this._localDirection) {
  37546. this._localDirection = BABYLON.Vector3.Zero();
  37547. this._transformedDirection = BABYLON.Vector3.Zero();
  37548. }
  37549. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  37550. this._localDirection.multiplyInPlace(this.panningAxis);
  37551. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  37552. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  37553. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  37554. if (!this.panningAxis.y) {
  37555. this._transformedDirection.y = 0;
  37556. }
  37557. if (!this._targetHost) {
  37558. if (this.panningDistanceLimit) {
  37559. this._transformedDirection.addInPlace(this._target);
  37560. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  37561. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  37562. this._target.copyFrom(this._transformedDirection);
  37563. }
  37564. }
  37565. else {
  37566. this._target.addInPlace(this._transformedDirection);
  37567. }
  37568. }
  37569. this.inertialPanningX *= this.panningInertia;
  37570. this.inertialPanningY *= this.panningInertia;
  37571. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  37572. this.inertialPanningX = 0;
  37573. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  37574. this.inertialPanningY = 0;
  37575. }
  37576. // Limits
  37577. this._checkLimits();
  37578. _super.prototype._checkInputs.call(this);
  37579. };
  37580. ArcRotateCamera.prototype._checkLimits = function () {
  37581. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  37582. if (this.allowUpsideDown && this.beta > Math.PI) {
  37583. this.beta = this.beta - (2 * Math.PI);
  37584. }
  37585. }
  37586. else {
  37587. if (this.beta < this.lowerBetaLimit) {
  37588. this.beta = this.lowerBetaLimit;
  37589. }
  37590. }
  37591. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  37592. if (this.allowUpsideDown && this.beta < -Math.PI) {
  37593. this.beta = this.beta + (2 * Math.PI);
  37594. }
  37595. }
  37596. else {
  37597. if (this.beta > this.upperBetaLimit) {
  37598. this.beta = this.upperBetaLimit;
  37599. }
  37600. }
  37601. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  37602. this.alpha = this.lowerAlphaLimit;
  37603. }
  37604. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  37605. this.alpha = this.upperAlphaLimit;
  37606. }
  37607. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  37608. this.radius = this.lowerRadiusLimit;
  37609. }
  37610. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  37611. this.radius = this.upperRadiusLimit;
  37612. }
  37613. };
  37614. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  37615. var radiusv3 = this.position.subtract(this._getTargetPosition());
  37616. this.radius = radiusv3.length();
  37617. if (this.radius === 0) {
  37618. this.radius = 0.0001; // Just to avoid division by zero
  37619. }
  37620. // Alpha
  37621. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  37622. if (radiusv3.z < 0) {
  37623. this.alpha = 2 * Math.PI - this.alpha;
  37624. }
  37625. // Beta
  37626. this.beta = Math.acos(radiusv3.y / this.radius);
  37627. this._checkLimits();
  37628. };
  37629. ArcRotateCamera.prototype.setPosition = function (position) {
  37630. if (this.position.equals(position)) {
  37631. return;
  37632. }
  37633. this.position.copyFrom(position);
  37634. this.rebuildAnglesAndRadius();
  37635. };
  37636. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  37637. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  37638. if (allowSamePosition === void 0) { allowSamePosition = false; }
  37639. if (target.getBoundingInfo) {
  37640. if (toBoundingCenter) {
  37641. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  37642. }
  37643. else {
  37644. this._targetBoundingCenter = null;
  37645. }
  37646. this._targetHost = target;
  37647. this._target = this._getTargetPosition();
  37648. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  37649. }
  37650. else {
  37651. var newTarget = target;
  37652. var currentTarget = this._getTargetPosition();
  37653. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  37654. return;
  37655. }
  37656. this._targetHost = null;
  37657. this._target = newTarget;
  37658. this._targetBoundingCenter = null;
  37659. this.onMeshTargetChangedObservable.notifyObservers(null);
  37660. }
  37661. this.rebuildAnglesAndRadius();
  37662. };
  37663. ArcRotateCamera.prototype._getViewMatrix = function () {
  37664. // Compute
  37665. var cosa = Math.cos(this.alpha);
  37666. var sina = Math.sin(this.alpha);
  37667. var cosb = Math.cos(this.beta);
  37668. var sinb = Math.sin(this.beta);
  37669. if (sinb === 0) {
  37670. sinb = 0.0001;
  37671. }
  37672. var target = this._getTargetPosition();
  37673. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  37674. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  37675. if (!this._collider) {
  37676. this._collider = new BABYLON.Collider();
  37677. }
  37678. this._collider.radius = this.collisionRadius;
  37679. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  37680. this._collisionTriggered = true;
  37681. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37682. }
  37683. else {
  37684. this.position.copyFrom(this._newPosition);
  37685. var up = this.upVector;
  37686. if (this.allowUpsideDown && sinb < 0) {
  37687. up = up.clone();
  37688. up = up.negate();
  37689. }
  37690. if (this.getScene().useRightHandedSystem) {
  37691. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  37692. }
  37693. else {
  37694. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  37695. }
  37696. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  37697. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  37698. }
  37699. this._currentTarget = target;
  37700. return this._viewMatrix;
  37701. };
  37702. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  37703. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37704. meshes = meshes || this.getScene().meshes;
  37705. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  37706. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  37707. this.radius = distance * this.zoomOnFactor;
  37708. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  37709. };
  37710. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  37711. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37712. var meshesOrMinMaxVector;
  37713. var distance;
  37714. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  37715. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  37716. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  37717. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  37718. }
  37719. else {
  37720. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  37721. meshesOrMinMaxVector = minMaxVectorAndDistance;
  37722. distance = minMaxVectorAndDistance.distance;
  37723. }
  37724. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  37725. if (!doNotUpdateMaxZ) {
  37726. this.maxZ = distance * 2;
  37727. }
  37728. };
  37729. /**
  37730. * @override
  37731. * Override Camera.createRigCamera
  37732. */
  37733. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37734. var alphaShift;
  37735. switch (this.cameraRigMode) {
  37736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37737. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37738. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37739. case BABYLON.Camera.RIG_MODE_VR:
  37740. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  37741. break;
  37742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37743. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  37744. break;
  37745. }
  37746. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  37747. rigCam._cameraRigParams = {};
  37748. return rigCam;
  37749. };
  37750. /**
  37751. * @override
  37752. * Override Camera._updateRigCameras
  37753. */
  37754. ArcRotateCamera.prototype._updateRigCameras = function () {
  37755. var camLeft = this._rigCameras[0];
  37756. var camRight = this._rigCameras[1];
  37757. camLeft.beta = camRight.beta = this.beta;
  37758. camLeft.radius = camRight.radius = this.radius;
  37759. switch (this.cameraRigMode) {
  37760. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37762. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37763. case BABYLON.Camera.RIG_MODE_VR:
  37764. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37765. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37766. break;
  37767. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37768. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37769. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37770. break;
  37771. }
  37772. _super.prototype._updateRigCameras.call(this);
  37773. };
  37774. ArcRotateCamera.prototype.dispose = function () {
  37775. this.inputs.clear();
  37776. _super.prototype.dispose.call(this);
  37777. };
  37778. ArcRotateCamera.prototype.getClassName = function () {
  37779. return "ArcRotateCamera";
  37780. };
  37781. __decorate([
  37782. BABYLON.serialize()
  37783. ], ArcRotateCamera.prototype, "alpha", void 0);
  37784. __decorate([
  37785. BABYLON.serialize()
  37786. ], ArcRotateCamera.prototype, "beta", void 0);
  37787. __decorate([
  37788. BABYLON.serialize()
  37789. ], ArcRotateCamera.prototype, "radius", void 0);
  37790. __decorate([
  37791. BABYLON.serializeAsVector3("target")
  37792. ], ArcRotateCamera.prototype, "_target", void 0);
  37793. __decorate([
  37794. BABYLON.serialize()
  37795. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  37796. __decorate([
  37797. BABYLON.serialize()
  37798. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  37799. __decorate([
  37800. BABYLON.serialize()
  37801. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  37802. __decorate([
  37803. BABYLON.serialize()
  37804. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  37805. __decorate([
  37806. BABYLON.serialize()
  37807. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  37808. __decorate([
  37809. BABYLON.serialize()
  37810. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  37811. __decorate([
  37812. BABYLON.serialize()
  37813. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  37814. __decorate([
  37815. BABYLON.serialize()
  37816. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  37817. __decorate([
  37818. BABYLON.serialize()
  37819. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  37820. __decorate([
  37821. BABYLON.serialize()
  37822. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  37823. __decorate([
  37824. BABYLON.serialize()
  37825. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  37826. __decorate([
  37827. BABYLON.serialize()
  37828. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  37829. __decorate([
  37830. BABYLON.serialize()
  37831. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  37832. __decorate([
  37833. BABYLON.serializeAsVector3()
  37834. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  37835. __decorate([
  37836. BABYLON.serialize()
  37837. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  37838. __decorate([
  37839. BABYLON.serialize()
  37840. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  37841. __decorate([
  37842. BABYLON.serialize()
  37843. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  37844. return ArcRotateCamera;
  37845. }(BABYLON.TargetCamera));
  37846. BABYLON.ArcRotateCamera = ArcRotateCamera;
  37847. })(BABYLON || (BABYLON = {}));
  37848. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  37849. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  37850. var BABYLON;
  37851. (function (BABYLON) {
  37852. var ArcRotateCameraInputsManager = (function (_super) {
  37853. __extends(ArcRotateCameraInputsManager, _super);
  37854. function ArcRotateCameraInputsManager(camera) {
  37855. return _super.call(this, camera) || this;
  37856. }
  37857. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  37858. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  37859. return this;
  37860. };
  37861. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  37862. this.add(new BABYLON.ArcRotateCameraPointersInput());
  37863. return this;
  37864. };
  37865. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  37866. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  37867. return this;
  37868. };
  37869. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  37870. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  37871. return this;
  37872. };
  37873. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  37874. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  37875. return this;
  37876. };
  37877. return ArcRotateCameraInputsManager;
  37878. }(BABYLON.CameraInputsManager));
  37879. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  37880. })(BABYLON || (BABYLON = {}));
  37881. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  37882. var BABYLON;
  37883. (function (BABYLON) {
  37884. var HemisphericLight = (function (_super) {
  37885. __extends(HemisphericLight, _super);
  37886. /**
  37887. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  37888. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  37889. * The HemisphericLight can't cast shadows.
  37890. * Documentation : http://doc.babylonjs.com/tutorials/lights
  37891. */
  37892. function HemisphericLight(name, direction, scene) {
  37893. var _this = _super.call(this, name, scene) || this;
  37894. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  37895. _this.direction = direction || BABYLON.Vector3.Up();
  37896. return _this;
  37897. }
  37898. HemisphericLight.prototype._buildUniformLayout = function () {
  37899. this._uniformBuffer.addUniform("vLightData", 4);
  37900. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  37901. this._uniformBuffer.addUniform("vLightSpecular", 3);
  37902. this._uniformBuffer.addUniform("vLightGround", 3);
  37903. this._uniformBuffer.addUniform("shadowsInfo", 3);
  37904. this._uniformBuffer.addUniform("depthValues", 2);
  37905. this._uniformBuffer.create();
  37906. };
  37907. /**
  37908. * Returns the string "HemisphericLight".
  37909. */
  37910. HemisphericLight.prototype.getClassName = function () {
  37911. return "HemisphericLight";
  37912. };
  37913. /**
  37914. * Sets the HemisphericLight direction towards the passed target (Vector3).
  37915. * Returns the updated direction.
  37916. */
  37917. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  37918. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  37919. return this.direction;
  37920. };
  37921. HemisphericLight.prototype.getShadowGenerator = function () {
  37922. return null;
  37923. };
  37924. /**
  37925. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  37926. * Returns the HemisphericLight.
  37927. */
  37928. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  37929. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  37930. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  37931. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  37932. return this;
  37933. };
  37934. HemisphericLight.prototype._getWorldMatrix = function () {
  37935. if (!this._worldMatrix) {
  37936. this._worldMatrix = BABYLON.Matrix.Identity();
  37937. }
  37938. return this._worldMatrix;
  37939. };
  37940. /**
  37941. * Returns the integer 3.
  37942. */
  37943. HemisphericLight.prototype.getTypeID = function () {
  37944. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  37945. };
  37946. __decorate([
  37947. BABYLON.serializeAsColor3()
  37948. ], HemisphericLight.prototype, "groundColor", void 0);
  37949. __decorate([
  37950. BABYLON.serializeAsVector3()
  37951. ], HemisphericLight.prototype, "direction", void 0);
  37952. return HemisphericLight;
  37953. }(BABYLON.Light));
  37954. BABYLON.HemisphericLight = HemisphericLight;
  37955. })(BABYLON || (BABYLON = {}));
  37956. //# sourceMappingURL=babylon.hemisphericLight.js.map
  37957. var BABYLON;
  37958. (function (BABYLON) {
  37959. var ShadowLight = (function (_super) {
  37960. __extends(ShadowLight, _super);
  37961. function ShadowLight() {
  37962. var _this = _super !== null && _super.apply(this, arguments) || this;
  37963. _this._needProjectionMatrixCompute = true;
  37964. return _this;
  37965. }
  37966. Object.defineProperty(ShadowLight.prototype, "direction", {
  37967. get: function () {
  37968. return this._direction;
  37969. },
  37970. set: function (value) {
  37971. this._direction = value;
  37972. },
  37973. enumerable: true,
  37974. configurable: true
  37975. });
  37976. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  37977. get: function () {
  37978. return this._shadowMinZ;
  37979. },
  37980. set: function (value) {
  37981. this._shadowMinZ = value;
  37982. this.forceProjectionMatrixCompute();
  37983. },
  37984. enumerable: true,
  37985. configurable: true
  37986. });
  37987. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  37988. get: function () {
  37989. return this._shadowMaxZ;
  37990. },
  37991. set: function (value) {
  37992. this._shadowMaxZ = value;
  37993. this.forceProjectionMatrixCompute();
  37994. },
  37995. enumerable: true,
  37996. configurable: true
  37997. });
  37998. /**
  37999. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  38000. */
  38001. ShadowLight.prototype.computeTransformedInformation = function () {
  38002. if (this.parent && this.parent.getWorldMatrix) {
  38003. if (!this.transformedPosition) {
  38004. this.transformedPosition = BABYLON.Vector3.Zero();
  38005. }
  38006. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  38007. // In case the direction is present.
  38008. if (this.direction) {
  38009. if (!this.transformedDirection) {
  38010. this.transformedDirection = BABYLON.Vector3.Zero();
  38011. }
  38012. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  38013. }
  38014. return true;
  38015. }
  38016. return false;
  38017. };
  38018. /**
  38019. * Return the depth scale used for the shadow map.
  38020. */
  38021. ShadowLight.prototype.getDepthScale = function () {
  38022. return 50.0;
  38023. };
  38024. /**
  38025. * Returns the light direction (Vector3) for any passed face index.
  38026. */
  38027. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  38028. return this.transformedDirection ? this.transformedDirection : this.direction;
  38029. };
  38030. /**
  38031. * Returns the DirectionalLight absolute position in the World.
  38032. */
  38033. ShadowLight.prototype.getAbsolutePosition = function () {
  38034. return this.transformedPosition ? this.transformedPosition : this.position;
  38035. };
  38036. /**
  38037. * Sets the DirectionalLight direction toward the passed target (Vector3).
  38038. * Returns the updated DirectionalLight direction (Vector3).
  38039. */
  38040. ShadowLight.prototype.setDirectionToTarget = function (target) {
  38041. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  38042. return this.direction;
  38043. };
  38044. /**
  38045. * Returns the light rotation (Vector3).
  38046. */
  38047. ShadowLight.prototype.getRotation = function () {
  38048. this.direction.normalize();
  38049. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  38050. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  38051. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  38052. };
  38053. /**
  38054. * Boolean : false by default.
  38055. */
  38056. ShadowLight.prototype.needCube = function () {
  38057. return false;
  38058. };
  38059. /**
  38060. * Specifies wether or not the projection matrix should be recomputed this frame.
  38061. */
  38062. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  38063. return this._needProjectionMatrixCompute;
  38064. };
  38065. /**
  38066. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  38067. */
  38068. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  38069. this._needProjectionMatrixCompute = true;
  38070. };
  38071. /**
  38072. * Get the world matrix of the sahdow lights.
  38073. */
  38074. ShadowLight.prototype._getWorldMatrix = function () {
  38075. if (!this._worldMatrix) {
  38076. this._worldMatrix = BABYLON.Matrix.Identity();
  38077. }
  38078. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  38079. return this._worldMatrix;
  38080. };
  38081. /**
  38082. * Gets the minZ used for shadow according to both the scene and the light.
  38083. * @param activeCamera
  38084. */
  38085. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  38086. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  38087. };
  38088. /**
  38089. * Gets the maxZ used for shadow according to both the scene and the light.
  38090. * @param activeCamera
  38091. */
  38092. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  38093. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  38094. };
  38095. /**
  38096. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  38097. * Returns the light.
  38098. */
  38099. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38100. if (this.customProjectionMatrixBuilder) {
  38101. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  38102. }
  38103. else {
  38104. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38105. }
  38106. return this;
  38107. };
  38108. __decorate([
  38109. BABYLON.serializeAsVector3()
  38110. ], ShadowLight.prototype, "position", void 0);
  38111. __decorate([
  38112. BABYLON.serializeAsVector3()
  38113. ], ShadowLight.prototype, "direction", null);
  38114. __decorate([
  38115. BABYLON.serialize()
  38116. ], ShadowLight.prototype, "shadowMinZ", null);
  38117. __decorate([
  38118. BABYLON.serialize()
  38119. ], ShadowLight.prototype, "shadowMaxZ", null);
  38120. return ShadowLight;
  38121. }(BABYLON.Light));
  38122. BABYLON.ShadowLight = ShadowLight;
  38123. })(BABYLON || (BABYLON = {}));
  38124. //# sourceMappingURL=babylon.shadowLight.js.map
  38125. var BABYLON;
  38126. (function (BABYLON) {
  38127. var PointLight = (function (_super) {
  38128. __extends(PointLight, _super);
  38129. /**
  38130. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  38131. * A PointLight emits the light in every direction.
  38132. * It can cast shadows.
  38133. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  38134. * ```javascript
  38135. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  38136. * ```
  38137. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38138. */
  38139. function PointLight(name, position, scene) {
  38140. var _this = _super.call(this, name, scene) || this;
  38141. _this._shadowAngle = Math.PI / 2;
  38142. _this.position = position;
  38143. return _this;
  38144. }
  38145. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  38146. /**
  38147. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38148. * This specifies what angle the shadow will use to be created.
  38149. *
  38150. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38151. */
  38152. get: function () {
  38153. return this._shadowAngle;
  38154. },
  38155. /**
  38156. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38157. * This specifies what angle the shadow will use to be created.
  38158. *
  38159. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38160. */
  38161. set: function (value) {
  38162. this._shadowAngle = value;
  38163. this.forceProjectionMatrixCompute();
  38164. },
  38165. enumerable: true,
  38166. configurable: true
  38167. });
  38168. Object.defineProperty(PointLight.prototype, "direction", {
  38169. get: function () {
  38170. return this._direction;
  38171. },
  38172. /**
  38173. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38174. */
  38175. set: function (value) {
  38176. var previousNeedCube = this.needCube();
  38177. this._direction = value;
  38178. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  38179. this._shadowGenerator.recreateShadowMap();
  38180. }
  38181. },
  38182. enumerable: true,
  38183. configurable: true
  38184. });
  38185. /**
  38186. * Returns the string "PointLight"
  38187. */
  38188. PointLight.prototype.getClassName = function () {
  38189. return "PointLight";
  38190. };
  38191. /**
  38192. * Returns the integer 0.
  38193. */
  38194. PointLight.prototype.getTypeID = function () {
  38195. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  38196. };
  38197. /**
  38198. * Specifies wether or not the shadowmap should be a cube texture.
  38199. */
  38200. PointLight.prototype.needCube = function () {
  38201. return !this.direction;
  38202. };
  38203. /**
  38204. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  38205. */
  38206. PointLight.prototype.getShadowDirection = function (faceIndex) {
  38207. if (this.direction) {
  38208. return _super.prototype.getShadowDirection.call(this, faceIndex);
  38209. }
  38210. else {
  38211. switch (faceIndex) {
  38212. case 0:
  38213. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  38214. case 1:
  38215. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  38216. case 2:
  38217. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  38218. case 3:
  38219. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  38220. case 4:
  38221. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  38222. case 5:
  38223. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  38224. }
  38225. }
  38226. return BABYLON.Vector3.Zero();
  38227. };
  38228. /**
  38229. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  38230. * - fov = PI / 2
  38231. * - aspect ratio : 1.0
  38232. * - z-near and far equal to the active camera minZ and maxZ.
  38233. * Returns the PointLight.
  38234. */
  38235. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38236. var activeCamera = this.getScene().activeCamera;
  38237. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38238. };
  38239. PointLight.prototype._buildUniformLayout = function () {
  38240. this._uniformBuffer.addUniform("vLightData", 4);
  38241. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38242. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38243. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38244. this._uniformBuffer.addUniform("depthValues", 2);
  38245. this._uniformBuffer.create();
  38246. };
  38247. /**
  38248. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  38249. * Returns the PointLight.
  38250. */
  38251. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  38252. if (this.computeTransformedInformation()) {
  38253. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  38254. return this;
  38255. }
  38256. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  38257. return this;
  38258. };
  38259. __decorate([
  38260. BABYLON.serialize()
  38261. ], PointLight.prototype, "shadowAngle", null);
  38262. return PointLight;
  38263. }(BABYLON.ShadowLight));
  38264. BABYLON.PointLight = PointLight;
  38265. })(BABYLON || (BABYLON = {}));
  38266. //# sourceMappingURL=babylon.pointLight.js.map
  38267. /// <reference path="babylon.light.ts" />
  38268. var BABYLON;
  38269. (function (BABYLON) {
  38270. var DirectionalLight = (function (_super) {
  38271. __extends(DirectionalLight, _super);
  38272. /**
  38273. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  38274. * The directional light is emitted from everywhere in the given direction.
  38275. * It can cast shawdows.
  38276. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38277. */
  38278. function DirectionalLight(name, direction, scene) {
  38279. var _this = _super.call(this, name, scene) || this;
  38280. _this._shadowFrustumSize = 0;
  38281. _this._shadowOrthoScale = 0.5;
  38282. _this.autoUpdateExtends = true;
  38283. // Cache
  38284. _this._orthoLeft = Number.MAX_VALUE;
  38285. _this._orthoRight = Number.MIN_VALUE;
  38286. _this._orthoTop = Number.MIN_VALUE;
  38287. _this._orthoBottom = Number.MAX_VALUE;
  38288. _this.position = direction.scale(-1.0);
  38289. _this.direction = direction;
  38290. return _this;
  38291. }
  38292. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  38293. /**
  38294. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  38295. */
  38296. get: function () {
  38297. return this._shadowFrustumSize;
  38298. },
  38299. /**
  38300. * Specifies a fix frustum size for the shadow generation.
  38301. */
  38302. set: function (value) {
  38303. this._shadowFrustumSize = value;
  38304. this.forceProjectionMatrixCompute();
  38305. },
  38306. enumerable: true,
  38307. configurable: true
  38308. });
  38309. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  38310. get: function () {
  38311. return this._shadowOrthoScale;
  38312. },
  38313. set: function (value) {
  38314. this._shadowOrthoScale = value;
  38315. this.forceProjectionMatrixCompute();
  38316. },
  38317. enumerable: true,
  38318. configurable: true
  38319. });
  38320. /**
  38321. * Returns the string "DirectionalLight".
  38322. */
  38323. DirectionalLight.prototype.getClassName = function () {
  38324. return "DirectionalLight";
  38325. };
  38326. /**
  38327. * Returns the integer 1.
  38328. */
  38329. DirectionalLight.prototype.getTypeID = function () {
  38330. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  38331. };
  38332. /**
  38333. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  38334. * Returns the DirectionalLight Shadow projection matrix.
  38335. */
  38336. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38337. if (this.shadowFrustumSize > 0) {
  38338. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  38339. }
  38340. else {
  38341. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38342. }
  38343. };
  38344. /**
  38345. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  38346. * Returns the DirectionalLight Shadow projection matrix.
  38347. */
  38348. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  38349. var activeCamera = this.getScene().activeCamera;
  38350. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  38351. };
  38352. /**
  38353. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  38354. * Returns the DirectionalLight Shadow projection matrix.
  38355. */
  38356. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38357. var activeCamera = this.getScene().activeCamera;
  38358. // Check extends
  38359. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  38360. var tempVector3 = BABYLON.Vector3.Zero();
  38361. this._orthoLeft = Number.MAX_VALUE;
  38362. this._orthoRight = Number.MIN_VALUE;
  38363. this._orthoTop = Number.MIN_VALUE;
  38364. this._orthoBottom = Number.MAX_VALUE;
  38365. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  38366. var mesh = renderList[meshIndex];
  38367. if (!mesh) {
  38368. continue;
  38369. }
  38370. var boundingInfo = mesh.getBoundingInfo();
  38371. if (!boundingInfo) {
  38372. continue;
  38373. }
  38374. var boundingBox = boundingInfo.boundingBox;
  38375. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  38376. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  38377. if (tempVector3.x < this._orthoLeft)
  38378. this._orthoLeft = tempVector3.x;
  38379. if (tempVector3.y < this._orthoBottom)
  38380. this._orthoBottom = tempVector3.y;
  38381. if (tempVector3.x > this._orthoRight)
  38382. this._orthoRight = tempVector3.x;
  38383. if (tempVector3.y > this._orthoTop)
  38384. this._orthoTop = tempVector3.y;
  38385. }
  38386. }
  38387. }
  38388. var xOffset = this._orthoRight - this._orthoLeft;
  38389. var yOffset = this._orthoTop - this._orthoBottom;
  38390. 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);
  38391. };
  38392. DirectionalLight.prototype._buildUniformLayout = function () {
  38393. this._uniformBuffer.addUniform("vLightData", 4);
  38394. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38395. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38396. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38397. this._uniformBuffer.addUniform("depthValues", 2);
  38398. this._uniformBuffer.create();
  38399. };
  38400. /**
  38401. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  38402. * Returns the DirectionalLight.
  38403. */
  38404. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  38405. if (this.computeTransformedInformation()) {
  38406. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  38407. return this;
  38408. }
  38409. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  38410. return this;
  38411. };
  38412. /**
  38413. * Gets the minZ used for shadow according to both the scene and the light.
  38414. *
  38415. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38416. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38417. * @param activeCamera
  38418. */
  38419. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  38420. return 1;
  38421. };
  38422. /**
  38423. * Gets the maxZ used for shadow according to both the scene and the light.
  38424. *
  38425. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38426. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38427. * @param activeCamera
  38428. */
  38429. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  38430. return 1;
  38431. };
  38432. __decorate([
  38433. BABYLON.serialize()
  38434. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  38435. __decorate([
  38436. BABYLON.serialize()
  38437. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  38438. __decorate([
  38439. BABYLON.serialize()
  38440. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  38441. return DirectionalLight;
  38442. }(BABYLON.ShadowLight));
  38443. BABYLON.DirectionalLight = DirectionalLight;
  38444. })(BABYLON || (BABYLON = {}));
  38445. //# sourceMappingURL=babylon.directionalLight.js.map
  38446. var BABYLON;
  38447. (function (BABYLON) {
  38448. var SpotLight = (function (_super) {
  38449. __extends(SpotLight, _super);
  38450. /**
  38451. * Creates a SpotLight object in the scene with the passed parameters :
  38452. * - `position` (Vector3) is the initial SpotLight position,
  38453. * - `direction` (Vector3) is the initial SpotLight direction,
  38454. * - `angle` (float, in radians) is the spot light cone angle,
  38455. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  38456. * A spot light is a simply light oriented cone.
  38457. * It can cast shadows.
  38458. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38459. */
  38460. function SpotLight(name, position, direction, angle, exponent, scene) {
  38461. var _this = _super.call(this, name, scene) || this;
  38462. _this.position = position;
  38463. _this.direction = direction;
  38464. _this.angle = angle;
  38465. _this.exponent = exponent;
  38466. return _this;
  38467. }
  38468. Object.defineProperty(SpotLight.prototype, "angle", {
  38469. get: function () {
  38470. return this._angle;
  38471. },
  38472. set: function (value) {
  38473. this._angle = value;
  38474. this.forceProjectionMatrixCompute();
  38475. },
  38476. enumerable: true,
  38477. configurable: true
  38478. });
  38479. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  38480. get: function () {
  38481. return this._shadowAngleScale;
  38482. },
  38483. /**
  38484. * Allows scaling the angle of the light for shadow generation only.
  38485. */
  38486. set: function (value) {
  38487. this._shadowAngleScale = value;
  38488. this.forceProjectionMatrixCompute();
  38489. },
  38490. enumerable: true,
  38491. configurable: true
  38492. });
  38493. /**
  38494. * Returns the string "SpotLight".
  38495. */
  38496. SpotLight.prototype.getClassName = function () {
  38497. return "SpotLight";
  38498. };
  38499. /**
  38500. * Returns the integer 2.
  38501. */
  38502. SpotLight.prototype.getTypeID = function () {
  38503. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  38504. };
  38505. /**
  38506. * 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.
  38507. * Returns the SpotLight.
  38508. */
  38509. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38510. var activeCamera = this.getScene().activeCamera;
  38511. this._shadowAngleScale = this._shadowAngleScale || 1;
  38512. var angle = this._shadowAngleScale * this._angle;
  38513. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38514. };
  38515. SpotLight.prototype._buildUniformLayout = function () {
  38516. this._uniformBuffer.addUniform("vLightData", 4);
  38517. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38518. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38519. this._uniformBuffer.addUniform("vLightDirection", 3);
  38520. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38521. this._uniformBuffer.addUniform("depthValues", 2);
  38522. this._uniformBuffer.create();
  38523. };
  38524. /**
  38525. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  38526. * Return the SpotLight.
  38527. */
  38528. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  38529. var normalizeDirection;
  38530. if (this.computeTransformedInformation()) {
  38531. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  38532. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  38533. }
  38534. else {
  38535. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  38536. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38537. }
  38538. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  38539. return this;
  38540. };
  38541. __decorate([
  38542. BABYLON.serialize()
  38543. ], SpotLight.prototype, "angle", null);
  38544. __decorate([
  38545. BABYLON.serialize()
  38546. /**
  38547. * Allows scaling the angle of the light for shadow generation only.
  38548. */
  38549. ], SpotLight.prototype, "shadowAngleScale", null);
  38550. __decorate([
  38551. BABYLON.serialize()
  38552. ], SpotLight.prototype, "exponent", void 0);
  38553. return SpotLight;
  38554. }(BABYLON.ShadowLight));
  38555. BABYLON.SpotLight = SpotLight;
  38556. })(BABYLON || (BABYLON = {}));
  38557. //# sourceMappingURL=babylon.spotLight.js.map
  38558. var BABYLON;
  38559. (function (BABYLON) {
  38560. var AnimationRange = (function () {
  38561. function AnimationRange(name, from, to) {
  38562. this.name = name;
  38563. this.from = from;
  38564. this.to = to;
  38565. }
  38566. AnimationRange.prototype.clone = function () {
  38567. return new AnimationRange(this.name, this.from, this.to);
  38568. };
  38569. return AnimationRange;
  38570. }());
  38571. BABYLON.AnimationRange = AnimationRange;
  38572. /**
  38573. * Composed of a frame, and an action function
  38574. */
  38575. var AnimationEvent = (function () {
  38576. function AnimationEvent(frame, action, onlyOnce) {
  38577. this.frame = frame;
  38578. this.action = action;
  38579. this.onlyOnce = onlyOnce;
  38580. this.isDone = false;
  38581. }
  38582. return AnimationEvent;
  38583. }());
  38584. BABYLON.AnimationEvent = AnimationEvent;
  38585. var PathCursor = (function () {
  38586. function PathCursor(path) {
  38587. this.path = path;
  38588. this._onchange = new Array();
  38589. this.value = 0;
  38590. this.animations = new Array();
  38591. }
  38592. PathCursor.prototype.getPoint = function () {
  38593. var point = this.path.getPointAtLengthPosition(this.value);
  38594. return new BABYLON.Vector3(point.x, 0, point.y);
  38595. };
  38596. PathCursor.prototype.moveAhead = function (step) {
  38597. if (step === void 0) { step = 0.002; }
  38598. this.move(step);
  38599. return this;
  38600. };
  38601. PathCursor.prototype.moveBack = function (step) {
  38602. if (step === void 0) { step = 0.002; }
  38603. this.move(-step);
  38604. return this;
  38605. };
  38606. PathCursor.prototype.move = function (step) {
  38607. if (Math.abs(step) > 1) {
  38608. throw "step size should be less than 1.";
  38609. }
  38610. this.value += step;
  38611. this.ensureLimits();
  38612. this.raiseOnChange();
  38613. return this;
  38614. };
  38615. PathCursor.prototype.ensureLimits = function () {
  38616. while (this.value > 1) {
  38617. this.value -= 1;
  38618. }
  38619. while (this.value < 0) {
  38620. this.value += 1;
  38621. }
  38622. return this;
  38623. };
  38624. // used by animation engine
  38625. PathCursor.prototype.markAsDirty = function (propertyName) {
  38626. this.ensureLimits();
  38627. this.raiseOnChange();
  38628. return this;
  38629. };
  38630. PathCursor.prototype.raiseOnChange = function () {
  38631. var _this = this;
  38632. this._onchange.forEach(function (f) { return f(_this); });
  38633. return this;
  38634. };
  38635. PathCursor.prototype.onchange = function (f) {
  38636. this._onchange.push(f);
  38637. return this;
  38638. };
  38639. return PathCursor;
  38640. }());
  38641. BABYLON.PathCursor = PathCursor;
  38642. var Animation = (function () {
  38643. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  38644. this.name = name;
  38645. this.targetProperty = targetProperty;
  38646. this.framePerSecond = framePerSecond;
  38647. this.dataType = dataType;
  38648. this.loopMode = loopMode;
  38649. this.enableBlending = enableBlending;
  38650. this._runtimeAnimations = new Array();
  38651. // The set of event that will be linked to this animation
  38652. this._events = new Array();
  38653. this.blendingSpeed = 0.01;
  38654. this._ranges = {};
  38655. this.targetPropertyPath = targetProperty.split(".");
  38656. this.dataType = dataType;
  38657. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  38658. }
  38659. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  38660. var dataType = undefined;
  38661. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  38662. dataType = Animation.ANIMATIONTYPE_FLOAT;
  38663. }
  38664. else if (from instanceof BABYLON.Quaternion) {
  38665. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  38666. }
  38667. else if (from instanceof BABYLON.Vector3) {
  38668. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  38669. }
  38670. else if (from instanceof BABYLON.Vector2) {
  38671. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  38672. }
  38673. else if (from instanceof BABYLON.Color3) {
  38674. dataType = Animation.ANIMATIONTYPE_COLOR3;
  38675. }
  38676. else if (from instanceof BABYLON.Size) {
  38677. dataType = Animation.ANIMATIONTYPE_SIZE;
  38678. }
  38679. if (dataType == undefined) {
  38680. return null;
  38681. }
  38682. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  38683. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  38684. animation.setKeys(keys);
  38685. if (easingFunction !== undefined) {
  38686. animation.setEasingFunction(easingFunction);
  38687. }
  38688. return animation;
  38689. };
  38690. /**
  38691. * Sets up an animation.
  38692. * @param property the property to animate
  38693. * @param animationType the animation type to apply
  38694. * @param easingFunction the easing function used in the animation
  38695. * @returns The created animation
  38696. */
  38697. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  38698. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38699. animation.setEasingFunction(easingFunction);
  38700. return animation;
  38701. };
  38702. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38703. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38704. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38705. };
  38706. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38707. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38708. node.animations.push(animation);
  38709. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38710. };
  38711. /**
  38712. * Transition property of the Camera to the target Value.
  38713. * @param property The property to transition
  38714. * @param targetValue The target Value of the property
  38715. * @param host The object where the property to animate belongs
  38716. * @param scene Scene used to run the animation
  38717. * @param frameRate Framerate (in frame/s) to use
  38718. * @param transition The transition type we want to use
  38719. * @param duration The duration of the animation, in milliseconds
  38720. * @param onAnimationEnd Call back trigger at the end of the animation.
  38721. */
  38722. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  38723. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  38724. if (duration <= 0) {
  38725. host[property] = targetValue;
  38726. if (onAnimationEnd) {
  38727. onAnimationEnd();
  38728. }
  38729. return;
  38730. }
  38731. var endFrame = frameRate * (duration / 1000);
  38732. transition.setKeys([{
  38733. frame: 0,
  38734. value: host[property].clone ? host[property].clone() : host[property]
  38735. },
  38736. {
  38737. frame: endFrame,
  38738. value: targetValue
  38739. }]);
  38740. if (!host.animations) {
  38741. host.animations = [];
  38742. }
  38743. host.animations.push(transition);
  38744. var animation = scene.beginAnimation(host, 0, endFrame, false);
  38745. animation.onAnimationEnd = onAnimationEnd;
  38746. return animation;
  38747. };
  38748. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  38749. /**
  38750. * Return the array of runtime animations currently using this animation
  38751. */
  38752. get: function () {
  38753. return this._runtimeAnimations;
  38754. },
  38755. enumerable: true,
  38756. configurable: true
  38757. });
  38758. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  38759. get: function () {
  38760. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  38761. var runtimeAnimation = _a[_i];
  38762. if (!runtimeAnimation.isStopped) {
  38763. return true;
  38764. }
  38765. }
  38766. return false;
  38767. },
  38768. enumerable: true,
  38769. configurable: true
  38770. });
  38771. // Methods
  38772. /**
  38773. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  38774. */
  38775. Animation.prototype.toString = function (fullDetails) {
  38776. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  38777. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  38778. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  38779. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  38780. if (fullDetails) {
  38781. ret += ", Ranges: {";
  38782. var first = true;
  38783. for (var name in this._ranges) {
  38784. if (first) {
  38785. ret += ", ";
  38786. first = false;
  38787. }
  38788. ret += name;
  38789. }
  38790. ret += "}";
  38791. }
  38792. return ret;
  38793. };
  38794. /**
  38795. * Add an event to this animation.
  38796. */
  38797. Animation.prototype.addEvent = function (event) {
  38798. this._events.push(event);
  38799. };
  38800. /**
  38801. * Remove all events found at the given frame
  38802. * @param frame
  38803. */
  38804. Animation.prototype.removeEvents = function (frame) {
  38805. for (var index = 0; index < this._events.length; index++) {
  38806. if (this._events[index].frame === frame) {
  38807. this._events.splice(index, 1);
  38808. index--;
  38809. }
  38810. }
  38811. };
  38812. Animation.prototype.getEvents = function () {
  38813. return this._events;
  38814. };
  38815. Animation.prototype.createRange = function (name, from, to) {
  38816. // check name not already in use; could happen for bones after serialized
  38817. if (!this._ranges[name]) {
  38818. this._ranges[name] = new AnimationRange(name, from, to);
  38819. }
  38820. };
  38821. Animation.prototype.deleteRange = function (name, deleteFrames) {
  38822. if (deleteFrames === void 0) { deleteFrames = true; }
  38823. if (this._ranges[name]) {
  38824. if (deleteFrames) {
  38825. var from = this._ranges[name].from;
  38826. var to = this._ranges[name].to;
  38827. // this loop MUST go high to low for multiple splices to work
  38828. for (var key = this._keys.length - 1; key >= 0; key--) {
  38829. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  38830. this._keys.splice(key, 1);
  38831. }
  38832. }
  38833. }
  38834. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  38835. }
  38836. };
  38837. Animation.prototype.getRange = function (name) {
  38838. return this._ranges[name];
  38839. };
  38840. Animation.prototype.getKeys = function () {
  38841. return this._keys;
  38842. };
  38843. Animation.prototype.getHighestFrame = function () {
  38844. var ret = 0;
  38845. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  38846. if (ret < this._keys[key].frame) {
  38847. ret = this._keys[key].frame;
  38848. }
  38849. }
  38850. return ret;
  38851. };
  38852. Animation.prototype.getEasingFunction = function () {
  38853. return this._easingFunction;
  38854. };
  38855. Animation.prototype.setEasingFunction = function (easingFunction) {
  38856. this._easingFunction = easingFunction;
  38857. };
  38858. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  38859. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  38860. };
  38861. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38862. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38863. };
  38864. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  38865. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  38866. };
  38867. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38868. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  38869. };
  38870. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  38871. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  38872. };
  38873. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38874. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38875. };
  38876. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  38877. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  38878. };
  38879. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38880. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38881. };
  38882. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  38883. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  38884. };
  38885. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  38886. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  38887. };
  38888. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  38889. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  38890. };
  38891. Animation.prototype.clone = function () {
  38892. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  38893. clone.enableBlending = this.enableBlending;
  38894. clone.blendingSpeed = this.blendingSpeed;
  38895. if (this._keys) {
  38896. clone.setKeys(this._keys);
  38897. }
  38898. if (this._ranges) {
  38899. clone._ranges = {};
  38900. for (var name in this._ranges) {
  38901. clone._ranges[name] = this._ranges[name].clone();
  38902. }
  38903. }
  38904. return clone;
  38905. };
  38906. Animation.prototype.setKeys = function (values) {
  38907. this._keys = values.slice(0);
  38908. };
  38909. Animation.prototype.serialize = function () {
  38910. var serializationObject = {};
  38911. serializationObject.name = this.name;
  38912. serializationObject.property = this.targetProperty;
  38913. serializationObject.framePerSecond = this.framePerSecond;
  38914. serializationObject.dataType = this.dataType;
  38915. serializationObject.loopBehavior = this.loopMode;
  38916. serializationObject.enableBlending = this.enableBlending;
  38917. serializationObject.blendingSpeed = this.blendingSpeed;
  38918. var dataType = this.dataType;
  38919. serializationObject.keys = [];
  38920. var keys = this.getKeys();
  38921. for (var index = 0; index < keys.length; index++) {
  38922. var animationKey = keys[index];
  38923. var key = {};
  38924. key.frame = animationKey.frame;
  38925. switch (dataType) {
  38926. case Animation.ANIMATIONTYPE_FLOAT:
  38927. key.values = [animationKey.value];
  38928. break;
  38929. case Animation.ANIMATIONTYPE_QUATERNION:
  38930. case Animation.ANIMATIONTYPE_MATRIX:
  38931. case Animation.ANIMATIONTYPE_VECTOR3:
  38932. case Animation.ANIMATIONTYPE_COLOR3:
  38933. key.values = animationKey.value.asArray();
  38934. break;
  38935. }
  38936. serializationObject.keys.push(key);
  38937. }
  38938. serializationObject.ranges = [];
  38939. for (var name in this._ranges) {
  38940. var range = {};
  38941. range.name = name;
  38942. range.from = this._ranges[name].from;
  38943. range.to = this._ranges[name].to;
  38944. serializationObject.ranges.push(range);
  38945. }
  38946. return serializationObject;
  38947. };
  38948. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  38949. get: function () {
  38950. return Animation._ANIMATIONTYPE_FLOAT;
  38951. },
  38952. enumerable: true,
  38953. configurable: true
  38954. });
  38955. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  38956. get: function () {
  38957. return Animation._ANIMATIONTYPE_VECTOR3;
  38958. },
  38959. enumerable: true,
  38960. configurable: true
  38961. });
  38962. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  38963. get: function () {
  38964. return Animation._ANIMATIONTYPE_VECTOR2;
  38965. },
  38966. enumerable: true,
  38967. configurable: true
  38968. });
  38969. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  38970. get: function () {
  38971. return Animation._ANIMATIONTYPE_SIZE;
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  38977. get: function () {
  38978. return Animation._ANIMATIONTYPE_QUATERNION;
  38979. },
  38980. enumerable: true,
  38981. configurable: true
  38982. });
  38983. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  38984. get: function () {
  38985. return Animation._ANIMATIONTYPE_MATRIX;
  38986. },
  38987. enumerable: true,
  38988. configurable: true
  38989. });
  38990. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  38991. get: function () {
  38992. return Animation._ANIMATIONTYPE_COLOR3;
  38993. },
  38994. enumerable: true,
  38995. configurable: true
  38996. });
  38997. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  38998. get: function () {
  38999. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  39000. },
  39001. enumerable: true,
  39002. configurable: true
  39003. });
  39004. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  39005. get: function () {
  39006. return Animation._ANIMATIONLOOPMODE_CYCLE;
  39007. },
  39008. enumerable: true,
  39009. configurable: true
  39010. });
  39011. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  39012. get: function () {
  39013. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  39014. },
  39015. enumerable: true,
  39016. configurable: true
  39017. });
  39018. Animation.Parse = function (parsedAnimation) {
  39019. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  39020. var dataType = parsedAnimation.dataType;
  39021. var keys = [];
  39022. var data;
  39023. var index;
  39024. if (parsedAnimation.enableBlending) {
  39025. animation.enableBlending = parsedAnimation.enableBlending;
  39026. }
  39027. if (parsedAnimation.blendingSpeed) {
  39028. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  39029. }
  39030. for (index = 0; index < parsedAnimation.keys.length; index++) {
  39031. var key = parsedAnimation.keys[index];
  39032. switch (dataType) {
  39033. case Animation.ANIMATIONTYPE_FLOAT:
  39034. data = key.values[0];
  39035. break;
  39036. case Animation.ANIMATIONTYPE_QUATERNION:
  39037. data = BABYLON.Quaternion.FromArray(key.values);
  39038. break;
  39039. case Animation.ANIMATIONTYPE_MATRIX:
  39040. data = BABYLON.Matrix.FromArray(key.values);
  39041. break;
  39042. case Animation.ANIMATIONTYPE_COLOR3:
  39043. data = BABYLON.Color3.FromArray(key.values);
  39044. break;
  39045. case Animation.ANIMATIONTYPE_VECTOR3:
  39046. default:
  39047. data = BABYLON.Vector3.FromArray(key.values);
  39048. break;
  39049. }
  39050. keys.push({
  39051. frame: key.frame,
  39052. value: data
  39053. });
  39054. }
  39055. animation.setKeys(keys);
  39056. if (parsedAnimation.ranges) {
  39057. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  39058. data = parsedAnimation.ranges[index];
  39059. animation.createRange(data.name, data.from, data.to);
  39060. }
  39061. }
  39062. return animation;
  39063. };
  39064. Animation.AppendSerializedAnimations = function (source, destination) {
  39065. if (source.animations) {
  39066. destination.animations = [];
  39067. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  39068. var animation = source.animations[animationIndex];
  39069. destination.animations.push(animation.serialize());
  39070. }
  39071. }
  39072. };
  39073. Animation.AllowMatricesInterpolation = false;
  39074. // Statics
  39075. Animation._ANIMATIONTYPE_FLOAT = 0;
  39076. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  39077. Animation._ANIMATIONTYPE_QUATERNION = 2;
  39078. Animation._ANIMATIONTYPE_MATRIX = 3;
  39079. Animation._ANIMATIONTYPE_COLOR3 = 4;
  39080. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  39081. Animation._ANIMATIONTYPE_SIZE = 6;
  39082. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  39083. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  39084. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  39085. return Animation;
  39086. }());
  39087. BABYLON.Animation = Animation;
  39088. })(BABYLON || (BABYLON = {}));
  39089. //# sourceMappingURL=babylon.animation.js.map
  39090. var BABYLON;
  39091. (function (BABYLON) {
  39092. var RuntimeAnimation = (function () {
  39093. function RuntimeAnimation(target, animation) {
  39094. this._offsetsCache = {};
  39095. this._highLimitsCache = {};
  39096. this._stopped = false;
  39097. this._blendingFactor = 0;
  39098. this._ratioOffset = 0;
  39099. this._animation = animation;
  39100. this._target = target;
  39101. animation._runtimeAnimations.push(this);
  39102. }
  39103. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  39104. get: function () {
  39105. return this._animation;
  39106. },
  39107. enumerable: true,
  39108. configurable: true
  39109. });
  39110. RuntimeAnimation.prototype.reset = function () {
  39111. this._offsetsCache = {};
  39112. this._highLimitsCache = {};
  39113. this.currentFrame = 0;
  39114. this._blendingFactor = 0;
  39115. this._originalBlendValue = null;
  39116. };
  39117. RuntimeAnimation.prototype.isStopped = function () {
  39118. return this._stopped;
  39119. };
  39120. RuntimeAnimation.prototype.dispose = function () {
  39121. var index = this._animation.runtimeAnimations.indexOf(this);
  39122. if (index > -1) {
  39123. this._animation.runtimeAnimations.splice(index, 1);
  39124. }
  39125. };
  39126. RuntimeAnimation.prototype._getKeyValue = function (value) {
  39127. if (typeof value === "function") {
  39128. return value();
  39129. }
  39130. return value;
  39131. };
  39132. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  39133. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  39134. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  39135. }
  39136. this.currentFrame = currentFrame;
  39137. var keys = this._animation.getKeys();
  39138. // Try to get a hash to find the right key
  39139. 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));
  39140. if (keys[startKeyIndex].frame >= currentFrame) {
  39141. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  39142. startKeyIndex--;
  39143. }
  39144. }
  39145. for (var key = startKeyIndex; key < keys.length; key++) {
  39146. var endKey = keys[key + 1];
  39147. if (endKey.frame >= currentFrame) {
  39148. var startKey = keys[key];
  39149. var startValue = this._getKeyValue(startKey.value);
  39150. var endValue = this._getKeyValue(endKey.value);
  39151. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  39152. var frameDelta = endKey.frame - startKey.frame;
  39153. // gradient : percent of currentFrame between the frame inf and the frame sup
  39154. var gradient = (currentFrame - startKey.frame) / frameDelta;
  39155. // check for easingFunction and correction of gradient
  39156. var easingFunction = this._animation.getEasingFunction();
  39157. if (easingFunction != null) {
  39158. gradient = easingFunction.ease(gradient);
  39159. }
  39160. switch (this._animation.dataType) {
  39161. // Float
  39162. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39163. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  39164. switch (loopMode) {
  39165. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39166. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39167. return floatValue;
  39168. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39169. return offsetValue * repeatCount + floatValue;
  39170. }
  39171. break;
  39172. // Quaternion
  39173. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39174. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  39175. switch (loopMode) {
  39176. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39177. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39178. return quatValue;
  39179. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39180. return quatValue.add(offsetValue.scale(repeatCount));
  39181. }
  39182. return quatValue;
  39183. // Vector3
  39184. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39185. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  39186. switch (loopMode) {
  39187. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39188. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39189. return vec3Value;
  39190. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39191. return vec3Value.add(offsetValue.scale(repeatCount));
  39192. }
  39193. // Vector2
  39194. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39195. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  39196. switch (loopMode) {
  39197. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39198. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39199. return vec2Value;
  39200. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39201. return vec2Value.add(offsetValue.scale(repeatCount));
  39202. }
  39203. // Size
  39204. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39205. switch (loopMode) {
  39206. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39207. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39208. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  39209. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39210. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39211. }
  39212. // Color3
  39213. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39214. switch (loopMode) {
  39215. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39216. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39217. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  39218. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39219. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39220. }
  39221. // Matrix
  39222. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  39223. switch (loopMode) {
  39224. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39225. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39226. if (BABYLON.Animation.AllowMatricesInterpolation) {
  39227. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  39228. }
  39229. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39230. return startValue;
  39231. }
  39232. default:
  39233. break;
  39234. }
  39235. break;
  39236. }
  39237. }
  39238. return this._getKeyValue(keys[keys.length - 1].value);
  39239. };
  39240. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  39241. if (blend === void 0) { blend = false; }
  39242. // Set value
  39243. var path;
  39244. var destination;
  39245. var targetPropertyPath = this._animation.targetPropertyPath;
  39246. if (targetPropertyPath.length > 1) {
  39247. var property = this._target[targetPropertyPath[0]];
  39248. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  39249. property = property[targetPropertyPath[index]];
  39250. }
  39251. path = targetPropertyPath[targetPropertyPath.length - 1];
  39252. destination = property;
  39253. }
  39254. else {
  39255. path = targetPropertyPath[0];
  39256. destination = this._target;
  39257. }
  39258. // Blending
  39259. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  39260. if (!this._originalBlendValue) {
  39261. if (destination[path].clone) {
  39262. this._originalBlendValue = destination[path].clone();
  39263. }
  39264. else {
  39265. this._originalBlendValue = destination[path];
  39266. }
  39267. }
  39268. if (this._originalBlendValue.prototype) {
  39269. if (this._originalBlendValue.prototype.Lerp) {
  39270. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  39271. }
  39272. else {
  39273. destination[path] = currentValue;
  39274. }
  39275. }
  39276. else if (this._originalBlendValue.m) {
  39277. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  39278. }
  39279. else {
  39280. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  39281. }
  39282. this._blendingFactor += this._animation.blendingSpeed;
  39283. }
  39284. else {
  39285. destination[path] = currentValue;
  39286. }
  39287. if (this._target.markAsDirty) {
  39288. this._target.markAsDirty(this._animation.targetProperty);
  39289. }
  39290. };
  39291. RuntimeAnimation.prototype.goToFrame = function (frame) {
  39292. var keys = this._animation.getKeys();
  39293. if (frame < keys[0].frame) {
  39294. frame = keys[0].frame;
  39295. }
  39296. else if (frame > keys[keys.length - 1].frame) {
  39297. frame = keys[keys.length - 1].frame;
  39298. }
  39299. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  39300. this.setValue(currentValue);
  39301. };
  39302. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  39303. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  39304. this._ratioOffset = this._previousRatio - newRatio;
  39305. };
  39306. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  39307. if (blend === void 0) { blend = false; }
  39308. var targetPropertyPath = this._animation.targetPropertyPath;
  39309. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  39310. this._stopped = true;
  39311. return false;
  39312. }
  39313. var returnValue = true;
  39314. var keys = this._animation.getKeys();
  39315. // Adding a start key at frame 0 if missing
  39316. if (keys[0].frame !== 0) {
  39317. var newKey = { frame: 0, value: keys[0].value };
  39318. keys.splice(0, 0, newKey);
  39319. }
  39320. // Check limits
  39321. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  39322. from = keys[0].frame;
  39323. }
  39324. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  39325. to = keys[keys.length - 1].frame;
  39326. }
  39327. //to and from cannot be the same key
  39328. if (from === to) {
  39329. if (from > keys[0].frame) {
  39330. from--;
  39331. }
  39332. else if (to < keys[keys.length - 1].frame) {
  39333. to++;
  39334. }
  39335. }
  39336. // Compute ratio
  39337. var range = to - from;
  39338. var offsetValue;
  39339. // ratio represents the frame delta between from and to
  39340. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  39341. var highLimitValue = 0;
  39342. this._previousDelay = delay;
  39343. this._previousRatio = ratio;
  39344. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  39345. returnValue = false;
  39346. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  39347. }
  39348. else {
  39349. // Get max value if required
  39350. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  39351. var keyOffset = to.toString() + from.toString();
  39352. if (!this._offsetsCache[keyOffset]) {
  39353. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39354. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39355. switch (this._animation.dataType) {
  39356. // Float
  39357. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39358. this._offsetsCache[keyOffset] = toValue - fromValue;
  39359. break;
  39360. // Quaternion
  39361. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39363. break;
  39364. // Vector3
  39365. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39366. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39367. // Vector2
  39368. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39369. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39370. // Size
  39371. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39372. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39373. // Color3
  39374. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39375. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39376. default:
  39377. break;
  39378. }
  39379. this._highLimitsCache[keyOffset] = toValue;
  39380. }
  39381. highLimitValue = this._highLimitsCache[keyOffset];
  39382. offsetValue = this._offsetsCache[keyOffset];
  39383. }
  39384. }
  39385. if (offsetValue === undefined) {
  39386. switch (this._animation.dataType) {
  39387. // Float
  39388. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39389. offsetValue = 0;
  39390. break;
  39391. // Quaternion
  39392. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39393. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  39394. break;
  39395. // Vector3
  39396. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39397. offsetValue = BABYLON.Vector3.Zero();
  39398. break;
  39399. // Vector2
  39400. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39401. offsetValue = BABYLON.Vector2.Zero();
  39402. break;
  39403. // Size
  39404. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39405. offsetValue = BABYLON.Size.Zero();
  39406. break;
  39407. // Color3
  39408. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39409. offsetValue = BABYLON.Color3.Black();
  39410. }
  39411. }
  39412. // Compute value
  39413. var repeatCount = (ratio / range) >> 0;
  39414. var currentFrame = returnValue ? from + ratio % range : to;
  39415. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  39416. // Set value
  39417. this.setValue(currentValue);
  39418. // Check events
  39419. var events = this._animation.getEvents();
  39420. for (var index = 0; index < events.length; index++) {
  39421. // Make sure current frame has passed event frame and that event frame is within the current range
  39422. // Also, handle both forward and reverse animations
  39423. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  39424. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  39425. var event = events[index];
  39426. if (!event.isDone) {
  39427. // If event should be done only once, remove it.
  39428. if (event.onlyOnce) {
  39429. events.splice(index, 1);
  39430. index--;
  39431. }
  39432. event.isDone = true;
  39433. event.action();
  39434. } // Don't do anything if the event has already be done.
  39435. }
  39436. else if (events[index].isDone && !events[index].onlyOnce) {
  39437. // reset event, the animation is looping
  39438. events[index].isDone = false;
  39439. }
  39440. }
  39441. if (!returnValue) {
  39442. this._stopped = true;
  39443. }
  39444. return returnValue;
  39445. };
  39446. return RuntimeAnimation;
  39447. }());
  39448. BABYLON.RuntimeAnimation = RuntimeAnimation;
  39449. })(BABYLON || (BABYLON = {}));
  39450. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  39451. var BABYLON;
  39452. (function (BABYLON) {
  39453. var Animatable = (function () {
  39454. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  39455. if (fromFrame === void 0) { fromFrame = 0; }
  39456. if (toFrame === void 0) { toFrame = 100; }
  39457. if (loopAnimation === void 0) { loopAnimation = false; }
  39458. if (speedRatio === void 0) { speedRatio = 1.0; }
  39459. this.target = target;
  39460. this.fromFrame = fromFrame;
  39461. this.toFrame = toFrame;
  39462. this.loopAnimation = loopAnimation;
  39463. this.onAnimationEnd = onAnimationEnd;
  39464. this._localDelayOffset = null;
  39465. this._pausedDelay = null;
  39466. this._runtimeAnimations = new Array();
  39467. this._paused = false;
  39468. this._speedRatio = 1;
  39469. this.animationStarted = false;
  39470. if (animations) {
  39471. this.appendAnimations(target, animations);
  39472. }
  39473. this._speedRatio = speedRatio;
  39474. this._scene = scene;
  39475. scene._activeAnimatables.push(this);
  39476. }
  39477. Object.defineProperty(Animatable.prototype, "speedRatio", {
  39478. get: function () {
  39479. return this._speedRatio;
  39480. },
  39481. set: function (value) {
  39482. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  39483. var animation = this._runtimeAnimations[index];
  39484. animation._prepareForSpeedRatioChange(value);
  39485. }
  39486. this._speedRatio = value;
  39487. },
  39488. enumerable: true,
  39489. configurable: true
  39490. });
  39491. // Methods
  39492. Animatable.prototype.getAnimations = function () {
  39493. return this._runtimeAnimations;
  39494. };
  39495. Animatable.prototype.appendAnimations = function (target, animations) {
  39496. for (var index = 0; index < animations.length; index++) {
  39497. var animation = animations[index];
  39498. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  39499. }
  39500. };
  39501. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  39502. var runtimeAnimations = this._runtimeAnimations;
  39503. for (var index = 0; index < runtimeAnimations.length; index++) {
  39504. if (runtimeAnimations[index].animation.targetProperty === property) {
  39505. return runtimeAnimations[index].animation;
  39506. }
  39507. }
  39508. return null;
  39509. };
  39510. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  39511. var runtimeAnimations = this._runtimeAnimations;
  39512. for (var index = 0; index < runtimeAnimations.length; index++) {
  39513. if (runtimeAnimations[index].animation.targetProperty === property) {
  39514. return runtimeAnimations[index];
  39515. }
  39516. }
  39517. return null;
  39518. };
  39519. Animatable.prototype.reset = function () {
  39520. var runtimeAnimations = this._runtimeAnimations;
  39521. for (var index = 0; index < runtimeAnimations.length; index++) {
  39522. runtimeAnimations[index].reset();
  39523. }
  39524. this._localDelayOffset = null;
  39525. this._pausedDelay = null;
  39526. };
  39527. Animatable.prototype.enableBlending = function (blendingSpeed) {
  39528. var runtimeAnimations = this._runtimeAnimations;
  39529. for (var index = 0; index < runtimeAnimations.length; index++) {
  39530. runtimeAnimations[index].animation.enableBlending = true;
  39531. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  39532. }
  39533. };
  39534. Animatable.prototype.disableBlending = function () {
  39535. var runtimeAnimations = this._runtimeAnimations;
  39536. for (var index = 0; index < runtimeAnimations.length; index++) {
  39537. runtimeAnimations[index].animation.enableBlending = false;
  39538. }
  39539. };
  39540. Animatable.prototype.goToFrame = function (frame) {
  39541. var runtimeAnimations = this._runtimeAnimations;
  39542. if (runtimeAnimations[0]) {
  39543. var fps = runtimeAnimations[0].animation.framePerSecond;
  39544. var currentFrame = runtimeAnimations[0].currentFrame;
  39545. var adjustTime = frame - currentFrame;
  39546. var delay = adjustTime * 1000 / fps;
  39547. this._localDelayOffset -= delay;
  39548. }
  39549. for (var index = 0; index < runtimeAnimations.length; index++) {
  39550. runtimeAnimations[index].goToFrame(frame);
  39551. }
  39552. };
  39553. Animatable.prototype.pause = function () {
  39554. if (this._paused) {
  39555. return;
  39556. }
  39557. this._paused = true;
  39558. };
  39559. Animatable.prototype.restart = function () {
  39560. this._paused = false;
  39561. };
  39562. Animatable.prototype.stop = function (animationName) {
  39563. if (animationName) {
  39564. var idx = this._scene._activeAnimatables.indexOf(this);
  39565. if (idx > -1) {
  39566. var runtimeAnimations = this._runtimeAnimations;
  39567. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  39568. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  39569. continue;
  39570. }
  39571. runtimeAnimations[index].dispose();
  39572. runtimeAnimations.splice(index, 1);
  39573. }
  39574. if (runtimeAnimations.length == 0) {
  39575. this._scene._activeAnimatables.splice(idx, 1);
  39576. if (this.onAnimationEnd) {
  39577. this.onAnimationEnd();
  39578. }
  39579. }
  39580. }
  39581. }
  39582. else {
  39583. var index = this._scene._activeAnimatables.indexOf(this);
  39584. if (index > -1) {
  39585. this._scene._activeAnimatables.splice(index, 1);
  39586. var runtimeAnimations = this._runtimeAnimations;
  39587. for (var index = 0; index < runtimeAnimations.length; index++) {
  39588. runtimeAnimations[index].dispose();
  39589. }
  39590. if (this.onAnimationEnd) {
  39591. this.onAnimationEnd();
  39592. }
  39593. }
  39594. }
  39595. };
  39596. Animatable.prototype._animate = function (delay) {
  39597. if (this._paused) {
  39598. this.animationStarted = false;
  39599. if (this._pausedDelay === null) {
  39600. this._pausedDelay = delay;
  39601. }
  39602. return true;
  39603. }
  39604. if (this._localDelayOffset === null) {
  39605. this._localDelayOffset = delay;
  39606. }
  39607. else if (this._pausedDelay !== null) {
  39608. this._localDelayOffset += delay - this._pausedDelay;
  39609. this._pausedDelay = null;
  39610. }
  39611. // Animating
  39612. var running = false;
  39613. var runtimeAnimations = this._runtimeAnimations;
  39614. var index;
  39615. for (index = 0; index < runtimeAnimations.length; index++) {
  39616. var animation = runtimeAnimations[index];
  39617. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  39618. running = running || isRunning;
  39619. }
  39620. this.animationStarted = running;
  39621. if (!running) {
  39622. // Remove from active animatables
  39623. index = this._scene._activeAnimatables.indexOf(this);
  39624. this._scene._activeAnimatables.splice(index, 1);
  39625. // Dispose all runtime animations
  39626. for (index = 0; index < runtimeAnimations.length; index++) {
  39627. runtimeAnimations[index].dispose();
  39628. }
  39629. }
  39630. if (!running && this.onAnimationEnd) {
  39631. this.onAnimationEnd();
  39632. this.onAnimationEnd = null;
  39633. }
  39634. return running;
  39635. };
  39636. return Animatable;
  39637. }());
  39638. BABYLON.Animatable = Animatable;
  39639. })(BABYLON || (BABYLON = {}));
  39640. //# sourceMappingURL=babylon.animatable.js.map
  39641. var BABYLON;
  39642. (function (BABYLON) {
  39643. var EasingFunction = (function () {
  39644. function EasingFunction() {
  39645. // Properties
  39646. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  39647. }
  39648. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  39649. get: function () {
  39650. return EasingFunction._EASINGMODE_EASEIN;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  39656. get: function () {
  39657. return EasingFunction._EASINGMODE_EASEOUT;
  39658. },
  39659. enumerable: true,
  39660. configurable: true
  39661. });
  39662. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  39663. get: function () {
  39664. return EasingFunction._EASINGMODE_EASEINOUT;
  39665. },
  39666. enumerable: true,
  39667. configurable: true
  39668. });
  39669. EasingFunction.prototype.setEasingMode = function (easingMode) {
  39670. var n = Math.min(Math.max(easingMode, 0), 2);
  39671. this._easingMode = n;
  39672. };
  39673. EasingFunction.prototype.getEasingMode = function () {
  39674. return this._easingMode;
  39675. };
  39676. EasingFunction.prototype.easeInCore = function (gradient) {
  39677. throw new Error('You must implement this method');
  39678. };
  39679. EasingFunction.prototype.ease = function (gradient) {
  39680. switch (this._easingMode) {
  39681. case EasingFunction.EASINGMODE_EASEIN:
  39682. return this.easeInCore(gradient);
  39683. case EasingFunction.EASINGMODE_EASEOUT:
  39684. return (1 - this.easeInCore(1 - gradient));
  39685. }
  39686. if (gradient >= 0.5) {
  39687. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  39688. }
  39689. return (this.easeInCore(gradient * 2) * 0.5);
  39690. };
  39691. //Statics
  39692. EasingFunction._EASINGMODE_EASEIN = 0;
  39693. EasingFunction._EASINGMODE_EASEOUT = 1;
  39694. EasingFunction._EASINGMODE_EASEINOUT = 2;
  39695. return EasingFunction;
  39696. }());
  39697. BABYLON.EasingFunction = EasingFunction;
  39698. var CircleEase = (function (_super) {
  39699. __extends(CircleEase, _super);
  39700. function CircleEase() {
  39701. return _super !== null && _super.apply(this, arguments) || this;
  39702. }
  39703. CircleEase.prototype.easeInCore = function (gradient) {
  39704. gradient = Math.max(0, Math.min(1, gradient));
  39705. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  39706. };
  39707. return CircleEase;
  39708. }(EasingFunction));
  39709. BABYLON.CircleEase = CircleEase;
  39710. var BackEase = (function (_super) {
  39711. __extends(BackEase, _super);
  39712. function BackEase(amplitude) {
  39713. if (amplitude === void 0) { amplitude = 1; }
  39714. var _this = _super.call(this) || this;
  39715. _this.amplitude = amplitude;
  39716. return _this;
  39717. }
  39718. BackEase.prototype.easeInCore = function (gradient) {
  39719. var num = Math.max(0, this.amplitude);
  39720. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  39721. };
  39722. return BackEase;
  39723. }(EasingFunction));
  39724. BABYLON.BackEase = BackEase;
  39725. var BounceEase = (function (_super) {
  39726. __extends(BounceEase, _super);
  39727. function BounceEase(bounces, bounciness) {
  39728. if (bounces === void 0) { bounces = 3; }
  39729. if (bounciness === void 0) { bounciness = 2; }
  39730. var _this = _super.call(this) || this;
  39731. _this.bounces = bounces;
  39732. _this.bounciness = bounciness;
  39733. return _this;
  39734. }
  39735. BounceEase.prototype.easeInCore = function (gradient) {
  39736. var y = Math.max(0.0, this.bounces);
  39737. var bounciness = this.bounciness;
  39738. if (bounciness <= 1.0) {
  39739. bounciness = 1.001;
  39740. }
  39741. var num9 = Math.pow(bounciness, y);
  39742. var num5 = 1.0 - bounciness;
  39743. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  39744. var num15 = gradient * num4;
  39745. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  39746. var num3 = Math.floor(num65);
  39747. var num13 = num3 + 1.0;
  39748. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  39749. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  39750. var num7 = (num8 + num12) * 0.5;
  39751. var num6 = gradient - num7;
  39752. var num2 = num7 - num8;
  39753. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  39754. };
  39755. return BounceEase;
  39756. }(EasingFunction));
  39757. BABYLON.BounceEase = BounceEase;
  39758. var CubicEase = (function (_super) {
  39759. __extends(CubicEase, _super);
  39760. function CubicEase() {
  39761. return _super !== null && _super.apply(this, arguments) || this;
  39762. }
  39763. CubicEase.prototype.easeInCore = function (gradient) {
  39764. return (gradient * gradient * gradient);
  39765. };
  39766. return CubicEase;
  39767. }(EasingFunction));
  39768. BABYLON.CubicEase = CubicEase;
  39769. var ElasticEase = (function (_super) {
  39770. __extends(ElasticEase, _super);
  39771. function ElasticEase(oscillations, springiness) {
  39772. if (oscillations === void 0) { oscillations = 3; }
  39773. if (springiness === void 0) { springiness = 3; }
  39774. var _this = _super.call(this) || this;
  39775. _this.oscillations = oscillations;
  39776. _this.springiness = springiness;
  39777. return _this;
  39778. }
  39779. ElasticEase.prototype.easeInCore = function (gradient) {
  39780. var num2;
  39781. var num3 = Math.max(0.0, this.oscillations);
  39782. var num = Math.max(0.0, this.springiness);
  39783. if (num == 0) {
  39784. num2 = gradient;
  39785. }
  39786. else {
  39787. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  39788. }
  39789. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  39790. };
  39791. return ElasticEase;
  39792. }(EasingFunction));
  39793. BABYLON.ElasticEase = ElasticEase;
  39794. var ExponentialEase = (function (_super) {
  39795. __extends(ExponentialEase, _super);
  39796. function ExponentialEase(exponent) {
  39797. if (exponent === void 0) { exponent = 2; }
  39798. var _this = _super.call(this) || this;
  39799. _this.exponent = exponent;
  39800. return _this;
  39801. }
  39802. ExponentialEase.prototype.easeInCore = function (gradient) {
  39803. if (this.exponent <= 0) {
  39804. return gradient;
  39805. }
  39806. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  39807. };
  39808. return ExponentialEase;
  39809. }(EasingFunction));
  39810. BABYLON.ExponentialEase = ExponentialEase;
  39811. var PowerEase = (function (_super) {
  39812. __extends(PowerEase, _super);
  39813. function PowerEase(power) {
  39814. if (power === void 0) { power = 2; }
  39815. var _this = _super.call(this) || this;
  39816. _this.power = power;
  39817. return _this;
  39818. }
  39819. PowerEase.prototype.easeInCore = function (gradient) {
  39820. var y = Math.max(0.0, this.power);
  39821. return Math.pow(gradient, y);
  39822. };
  39823. return PowerEase;
  39824. }(EasingFunction));
  39825. BABYLON.PowerEase = PowerEase;
  39826. var QuadraticEase = (function (_super) {
  39827. __extends(QuadraticEase, _super);
  39828. function QuadraticEase() {
  39829. return _super !== null && _super.apply(this, arguments) || this;
  39830. }
  39831. QuadraticEase.prototype.easeInCore = function (gradient) {
  39832. return (gradient * gradient);
  39833. };
  39834. return QuadraticEase;
  39835. }(EasingFunction));
  39836. BABYLON.QuadraticEase = QuadraticEase;
  39837. var QuarticEase = (function (_super) {
  39838. __extends(QuarticEase, _super);
  39839. function QuarticEase() {
  39840. return _super !== null && _super.apply(this, arguments) || this;
  39841. }
  39842. QuarticEase.prototype.easeInCore = function (gradient) {
  39843. return (gradient * gradient * gradient * gradient);
  39844. };
  39845. return QuarticEase;
  39846. }(EasingFunction));
  39847. BABYLON.QuarticEase = QuarticEase;
  39848. var QuinticEase = (function (_super) {
  39849. __extends(QuinticEase, _super);
  39850. function QuinticEase() {
  39851. return _super !== null && _super.apply(this, arguments) || this;
  39852. }
  39853. QuinticEase.prototype.easeInCore = function (gradient) {
  39854. return (gradient * gradient * gradient * gradient * gradient);
  39855. };
  39856. return QuinticEase;
  39857. }(EasingFunction));
  39858. BABYLON.QuinticEase = QuinticEase;
  39859. var SineEase = (function (_super) {
  39860. __extends(SineEase, _super);
  39861. function SineEase() {
  39862. return _super !== null && _super.apply(this, arguments) || this;
  39863. }
  39864. SineEase.prototype.easeInCore = function (gradient) {
  39865. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  39866. };
  39867. return SineEase;
  39868. }(EasingFunction));
  39869. BABYLON.SineEase = SineEase;
  39870. var BezierCurveEase = (function (_super) {
  39871. __extends(BezierCurveEase, _super);
  39872. function BezierCurveEase(x1, y1, x2, y2) {
  39873. if (x1 === void 0) { x1 = 0; }
  39874. if (y1 === void 0) { y1 = 0; }
  39875. if (x2 === void 0) { x2 = 1; }
  39876. if (y2 === void 0) { y2 = 1; }
  39877. var _this = _super.call(this) || this;
  39878. _this.x1 = x1;
  39879. _this.y1 = y1;
  39880. _this.x2 = x2;
  39881. _this.y2 = y2;
  39882. return _this;
  39883. }
  39884. BezierCurveEase.prototype.easeInCore = function (gradient) {
  39885. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  39886. };
  39887. return BezierCurveEase;
  39888. }(EasingFunction));
  39889. BABYLON.BezierCurveEase = BezierCurveEase;
  39890. })(BABYLON || (BABYLON = {}));
  39891. //# sourceMappingURL=babylon.easing.js.map
  39892. var BABYLON;
  39893. (function (BABYLON) {
  39894. var Condition = (function () {
  39895. function Condition(actionManager) {
  39896. this._actionManager = actionManager;
  39897. }
  39898. Condition.prototype.isValid = function () {
  39899. return true;
  39900. };
  39901. Condition.prototype._getProperty = function (propertyPath) {
  39902. return this._actionManager._getProperty(propertyPath);
  39903. };
  39904. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39905. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39906. };
  39907. Condition.prototype.serialize = function () {
  39908. };
  39909. Condition.prototype._serialize = function (serializedCondition) {
  39910. return {
  39911. type: 2,
  39912. children: [],
  39913. name: serializedCondition.name,
  39914. properties: serializedCondition.properties
  39915. };
  39916. };
  39917. return Condition;
  39918. }());
  39919. BABYLON.Condition = Condition;
  39920. var ValueCondition = (function (_super) {
  39921. __extends(ValueCondition, _super);
  39922. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39923. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39924. var _this = _super.call(this, actionManager) || this;
  39925. _this.propertyPath = propertyPath;
  39926. _this.value = value;
  39927. _this.operator = operator;
  39928. _this._target = target;
  39929. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39930. _this._property = _this._getProperty(_this.propertyPath);
  39931. return _this;
  39932. }
  39933. Object.defineProperty(ValueCondition, "IsEqual", {
  39934. get: function () {
  39935. return ValueCondition._IsEqual;
  39936. },
  39937. enumerable: true,
  39938. configurable: true
  39939. });
  39940. Object.defineProperty(ValueCondition, "IsDifferent", {
  39941. get: function () {
  39942. return ValueCondition._IsDifferent;
  39943. },
  39944. enumerable: true,
  39945. configurable: true
  39946. });
  39947. Object.defineProperty(ValueCondition, "IsGreater", {
  39948. get: function () {
  39949. return ValueCondition._IsGreater;
  39950. },
  39951. enumerable: true,
  39952. configurable: true
  39953. });
  39954. Object.defineProperty(ValueCondition, "IsLesser", {
  39955. get: function () {
  39956. return ValueCondition._IsLesser;
  39957. },
  39958. enumerable: true,
  39959. configurable: true
  39960. });
  39961. // Methods
  39962. ValueCondition.prototype.isValid = function () {
  39963. switch (this.operator) {
  39964. case ValueCondition.IsGreater:
  39965. return this._effectiveTarget[this._property] > this.value;
  39966. case ValueCondition.IsLesser:
  39967. return this._effectiveTarget[this._property] < this.value;
  39968. case ValueCondition.IsEqual:
  39969. case ValueCondition.IsDifferent:
  39970. var check;
  39971. if (this.value.equals) {
  39972. check = this.value.equals(this._effectiveTarget[this._property]);
  39973. }
  39974. else {
  39975. check = this.value === this._effectiveTarget[this._property];
  39976. }
  39977. return this.operator === ValueCondition.IsEqual ? check : !check;
  39978. }
  39979. return false;
  39980. };
  39981. ValueCondition.prototype.serialize = function () {
  39982. return this._serialize({
  39983. name: "ValueCondition",
  39984. properties: [
  39985. BABYLON.Action._GetTargetProperty(this._target),
  39986. { name: "propertyPath", value: this.propertyPath },
  39987. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39988. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39989. ]
  39990. });
  39991. };
  39992. ValueCondition.GetOperatorName = function (operator) {
  39993. switch (operator) {
  39994. case ValueCondition._IsEqual: return "IsEqual";
  39995. case ValueCondition._IsDifferent: return "IsDifferent";
  39996. case ValueCondition._IsGreater: return "IsGreater";
  39997. case ValueCondition._IsLesser: return "IsLesser";
  39998. default: return "";
  39999. }
  40000. };
  40001. // Statics
  40002. ValueCondition._IsEqual = 0;
  40003. ValueCondition._IsDifferent = 1;
  40004. ValueCondition._IsGreater = 2;
  40005. ValueCondition._IsLesser = 3;
  40006. return ValueCondition;
  40007. }(Condition));
  40008. BABYLON.ValueCondition = ValueCondition;
  40009. var PredicateCondition = (function (_super) {
  40010. __extends(PredicateCondition, _super);
  40011. function PredicateCondition(actionManager, predicate) {
  40012. var _this = _super.call(this, actionManager) || this;
  40013. _this.predicate = predicate;
  40014. return _this;
  40015. }
  40016. PredicateCondition.prototype.isValid = function () {
  40017. return this.predicate();
  40018. };
  40019. return PredicateCondition;
  40020. }(Condition));
  40021. BABYLON.PredicateCondition = PredicateCondition;
  40022. var StateCondition = (function (_super) {
  40023. __extends(StateCondition, _super);
  40024. function StateCondition(actionManager, target, value) {
  40025. var _this = _super.call(this, actionManager) || this;
  40026. _this.value = value;
  40027. _this._target = target;
  40028. return _this;
  40029. }
  40030. // Methods
  40031. StateCondition.prototype.isValid = function () {
  40032. return this._target.state === this.value;
  40033. };
  40034. StateCondition.prototype.serialize = function () {
  40035. return this._serialize({
  40036. name: "StateCondition",
  40037. properties: [
  40038. BABYLON.Action._GetTargetProperty(this._target),
  40039. { name: "value", value: this.value }
  40040. ]
  40041. });
  40042. };
  40043. return StateCondition;
  40044. }(Condition));
  40045. BABYLON.StateCondition = StateCondition;
  40046. })(BABYLON || (BABYLON = {}));
  40047. //# sourceMappingURL=babylon.condition.js.map
  40048. var BABYLON;
  40049. (function (BABYLON) {
  40050. var Action = (function () {
  40051. function Action(triggerOptions, condition) {
  40052. this.triggerOptions = triggerOptions;
  40053. this.onBeforeExecuteObservable = new BABYLON.Observable();
  40054. if (triggerOptions.parameter) {
  40055. this.trigger = triggerOptions.trigger;
  40056. this._triggerParameter = triggerOptions.parameter;
  40057. }
  40058. else {
  40059. this.trigger = triggerOptions;
  40060. }
  40061. this._nextActiveAction = this;
  40062. this._condition = condition;
  40063. }
  40064. // Methods
  40065. Action.prototype._prepare = function () {
  40066. };
  40067. Action.prototype.getTriggerParameter = function () {
  40068. return this._triggerParameter;
  40069. };
  40070. Action.prototype._executeCurrent = function (evt) {
  40071. if (this._nextActiveAction._condition) {
  40072. var condition = this._nextActiveAction._condition;
  40073. var currentRenderId = this._actionManager.getScene().getRenderId();
  40074. // We cache the current evaluation for the current frame
  40075. if (condition._evaluationId === currentRenderId) {
  40076. if (!condition._currentResult) {
  40077. return;
  40078. }
  40079. }
  40080. else {
  40081. condition._evaluationId = currentRenderId;
  40082. if (!condition.isValid()) {
  40083. condition._currentResult = false;
  40084. return;
  40085. }
  40086. condition._currentResult = true;
  40087. }
  40088. }
  40089. this.onBeforeExecuteObservable.notifyObservers(this);
  40090. this._nextActiveAction.execute(evt);
  40091. this.skipToNextActiveAction();
  40092. };
  40093. Action.prototype.execute = function (evt) {
  40094. };
  40095. Action.prototype.skipToNextActiveAction = function () {
  40096. if (this._nextActiveAction._child) {
  40097. if (!this._nextActiveAction._child._actionManager) {
  40098. this._nextActiveAction._child._actionManager = this._actionManager;
  40099. }
  40100. this._nextActiveAction = this._nextActiveAction._child;
  40101. }
  40102. else {
  40103. this._nextActiveAction = this;
  40104. }
  40105. };
  40106. Action.prototype.then = function (action) {
  40107. this._child = action;
  40108. action._actionManager = this._actionManager;
  40109. action._prepare();
  40110. return action;
  40111. };
  40112. Action.prototype._getProperty = function (propertyPath) {
  40113. return this._actionManager._getProperty(propertyPath);
  40114. };
  40115. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  40116. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40117. };
  40118. Action.prototype.serialize = function (parent) {
  40119. };
  40120. // Called by BABYLON.Action objects in serialize(...). Internal use
  40121. Action.prototype._serialize = function (serializedAction, parent) {
  40122. var serializationObject = {
  40123. type: 1,
  40124. children: [],
  40125. name: serializedAction.name,
  40126. properties: serializedAction.properties || []
  40127. };
  40128. // Serialize child
  40129. if (this._child) {
  40130. this._child.serialize(serializationObject);
  40131. }
  40132. // Check if "this" has a condition
  40133. if (this._condition) {
  40134. var serializedCondition = this._condition.serialize();
  40135. serializedCondition.children.push(serializationObject);
  40136. if (parent) {
  40137. parent.children.push(serializedCondition);
  40138. }
  40139. return serializedCondition;
  40140. }
  40141. if (parent) {
  40142. parent.children.push(serializationObject);
  40143. }
  40144. return serializationObject;
  40145. };
  40146. Action._SerializeValueAsString = function (value) {
  40147. if (typeof value === "number") {
  40148. return value.toString();
  40149. }
  40150. if (typeof value === "boolean") {
  40151. return value ? "true" : "false";
  40152. }
  40153. if (value instanceof BABYLON.Vector2) {
  40154. return value.x + ", " + value.y;
  40155. }
  40156. if (value instanceof BABYLON.Vector3) {
  40157. return value.x + ", " + value.y + ", " + value.z;
  40158. }
  40159. if (value instanceof BABYLON.Color3) {
  40160. return value.r + ", " + value.g + ", " + value.b;
  40161. }
  40162. if (value instanceof BABYLON.Color4) {
  40163. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  40164. }
  40165. return value; // string
  40166. };
  40167. Action._GetTargetProperty = function (target) {
  40168. return {
  40169. name: "target",
  40170. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  40171. : target instanceof BABYLON.Light ? "LightProperties"
  40172. : target instanceof BABYLON.Camera ? "CameraProperties"
  40173. : "SceneProperties",
  40174. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  40175. };
  40176. };
  40177. return Action;
  40178. }());
  40179. BABYLON.Action = Action;
  40180. })(BABYLON || (BABYLON = {}));
  40181. //# sourceMappingURL=babylon.action.js.map
  40182. var BABYLON;
  40183. (function (BABYLON) {
  40184. /**
  40185. * ActionEvent is the event beint sent when an action is triggered.
  40186. */
  40187. var ActionEvent = (function () {
  40188. /**
  40189. * @param source The mesh or sprite that triggered the action.
  40190. * @param pointerX The X mouse cursor position at the time of the event
  40191. * @param pointerY The Y mouse cursor position at the time of the event
  40192. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  40193. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  40194. */
  40195. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  40196. this.source = source;
  40197. this.pointerX = pointerX;
  40198. this.pointerY = pointerY;
  40199. this.meshUnderPointer = meshUnderPointer;
  40200. this.sourceEvent = sourceEvent;
  40201. this.additionalData = additionalData;
  40202. }
  40203. /**
  40204. * Helper function to auto-create an ActionEvent from a source mesh.
  40205. * @param source The source mesh that triggered the event
  40206. * @param evt {Event} The original (browser) event
  40207. */
  40208. ActionEvent.CreateNew = function (source, evt, additionalData) {
  40209. var scene = source.getScene();
  40210. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40211. };
  40212. /**
  40213. * Helper function to auto-create an ActionEvent from a source mesh.
  40214. * @param source The source sprite that triggered the event
  40215. * @param scene Scene associated with the sprite
  40216. * @param evt {Event} The original (browser) event
  40217. */
  40218. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  40219. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40220. };
  40221. /**
  40222. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  40223. * @param scene the scene where the event occurred
  40224. * @param evt {Event} The original (browser) event
  40225. */
  40226. ActionEvent.CreateNewFromScene = function (scene, evt) {
  40227. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40228. };
  40229. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  40230. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  40231. };
  40232. return ActionEvent;
  40233. }());
  40234. BABYLON.ActionEvent = ActionEvent;
  40235. /**
  40236. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  40237. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  40238. */
  40239. var ActionManager = (function () {
  40240. function ActionManager(scene) {
  40241. // Members
  40242. this.actions = new Array();
  40243. this.hoverCursor = '';
  40244. this._scene = scene;
  40245. scene._actionManagers.push(this);
  40246. }
  40247. Object.defineProperty(ActionManager, "NothingTrigger", {
  40248. get: function () {
  40249. return ActionManager._NothingTrigger;
  40250. },
  40251. enumerable: true,
  40252. configurable: true
  40253. });
  40254. Object.defineProperty(ActionManager, "OnPickTrigger", {
  40255. get: function () {
  40256. return ActionManager._OnPickTrigger;
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  40262. get: function () {
  40263. return ActionManager._OnLeftPickTrigger;
  40264. },
  40265. enumerable: true,
  40266. configurable: true
  40267. });
  40268. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  40269. get: function () {
  40270. return ActionManager._OnRightPickTrigger;
  40271. },
  40272. enumerable: true,
  40273. configurable: true
  40274. });
  40275. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  40276. get: function () {
  40277. return ActionManager._OnCenterPickTrigger;
  40278. },
  40279. enumerable: true,
  40280. configurable: true
  40281. });
  40282. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  40283. get: function () {
  40284. return ActionManager._OnPickDownTrigger;
  40285. },
  40286. enumerable: true,
  40287. configurable: true
  40288. });
  40289. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  40290. get: function () {
  40291. return ActionManager._OnDoublePickTrigger;
  40292. },
  40293. enumerable: true,
  40294. configurable: true
  40295. });
  40296. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  40297. get: function () {
  40298. return ActionManager._OnPickUpTrigger;
  40299. },
  40300. enumerable: true,
  40301. configurable: true
  40302. });
  40303. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  40304. /// This trigger will only be raised if you also declared a OnPickDown
  40305. get: function () {
  40306. return ActionManager._OnPickOutTrigger;
  40307. },
  40308. enumerable: true,
  40309. configurable: true
  40310. });
  40311. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  40312. get: function () {
  40313. return ActionManager._OnLongPressTrigger;
  40314. },
  40315. enumerable: true,
  40316. configurable: true
  40317. });
  40318. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40319. get: function () {
  40320. return ActionManager._OnPointerOverTrigger;
  40321. },
  40322. enumerable: true,
  40323. configurable: true
  40324. });
  40325. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  40326. get: function () {
  40327. return ActionManager._OnPointerOutTrigger;
  40328. },
  40329. enumerable: true,
  40330. configurable: true
  40331. });
  40332. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  40333. get: function () {
  40334. return ActionManager._OnEveryFrameTrigger;
  40335. },
  40336. enumerable: true,
  40337. configurable: true
  40338. });
  40339. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  40340. get: function () {
  40341. return ActionManager._OnIntersectionEnterTrigger;
  40342. },
  40343. enumerable: true,
  40344. configurable: true
  40345. });
  40346. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  40347. get: function () {
  40348. return ActionManager._OnIntersectionExitTrigger;
  40349. },
  40350. enumerable: true,
  40351. configurable: true
  40352. });
  40353. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  40354. get: function () {
  40355. return ActionManager._OnKeyDownTrigger;
  40356. },
  40357. enumerable: true,
  40358. configurable: true
  40359. });
  40360. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  40361. get: function () {
  40362. return ActionManager._OnKeyUpTrigger;
  40363. },
  40364. enumerable: true,
  40365. configurable: true
  40366. });
  40367. // Methods
  40368. ActionManager.prototype.dispose = function () {
  40369. var index = this._scene._actionManagers.indexOf(this);
  40370. for (var i = 0; i < this.actions.length; i++) {
  40371. var action = this.actions[i];
  40372. ActionManager.Triggers[action.trigger]--;
  40373. if (ActionManager.Triggers[action.trigger] === 0) {
  40374. delete ActionManager.Triggers[action.trigger];
  40375. }
  40376. }
  40377. if (index > -1) {
  40378. this._scene._actionManagers.splice(index, 1);
  40379. }
  40380. };
  40381. ActionManager.prototype.getScene = function () {
  40382. return this._scene;
  40383. };
  40384. /**
  40385. * Does this action manager handles actions of any of the given triggers
  40386. * @param {number[]} triggers - the triggers to be tested
  40387. * @return {boolean} whether one (or more) of the triggers is handeled
  40388. */
  40389. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  40390. for (var index = 0; index < this.actions.length; index++) {
  40391. var action = this.actions[index];
  40392. if (triggers.indexOf(action.trigger) > -1) {
  40393. return true;
  40394. }
  40395. }
  40396. return false;
  40397. };
  40398. /**
  40399. * Does this action manager handles actions of a given trigger
  40400. * @param {number} trigger - the trigger to be tested
  40401. * @return {boolean} whether the trigger is handeled
  40402. */
  40403. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  40404. for (var index = 0; index < this.actions.length; index++) {
  40405. var action = this.actions[index];
  40406. if (action.trigger === trigger) {
  40407. return true;
  40408. }
  40409. }
  40410. return false;
  40411. };
  40412. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40413. /**
  40414. * Does this action manager has pointer triggers
  40415. * @return {boolean} whether or not it has pointer triggers
  40416. */
  40417. get: function () {
  40418. for (var index = 0; index < this.actions.length; index++) {
  40419. var action = this.actions[index];
  40420. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40421. return true;
  40422. }
  40423. }
  40424. return false;
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40430. /**
  40431. * Does this action manager has pick triggers
  40432. * @return {boolean} whether or not it has pick triggers
  40433. */
  40434. get: function () {
  40435. for (var index = 0; index < this.actions.length; index++) {
  40436. var action = this.actions[index];
  40437. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40438. return true;
  40439. }
  40440. }
  40441. return false;
  40442. },
  40443. enumerable: true,
  40444. configurable: true
  40445. });
  40446. Object.defineProperty(ActionManager, "HasTriggers", {
  40447. /**
  40448. * Does exist one action manager with at least one trigger
  40449. * @return {boolean} whether or not it exists one action manager with one trigger
  40450. **/
  40451. get: function () {
  40452. for (var t in ActionManager.Triggers) {
  40453. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40454. return true;
  40455. }
  40456. }
  40457. return false;
  40458. },
  40459. enumerable: true,
  40460. configurable: true
  40461. });
  40462. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40463. /**
  40464. * Does exist one action manager with at least one pick trigger
  40465. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40466. **/
  40467. get: function () {
  40468. for (var t in ActionManager.Triggers) {
  40469. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40470. var t_int = parseInt(t);
  40471. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40472. return true;
  40473. }
  40474. }
  40475. }
  40476. return false;
  40477. },
  40478. enumerable: true,
  40479. configurable: true
  40480. });
  40481. /**
  40482. * Does exist one action manager that handles actions of a given trigger
  40483. * @param {number} trigger - the trigger to be tested
  40484. * @return {boolean} whether the trigger is handeled by at least one action manager
  40485. **/
  40486. ActionManager.HasSpecificTrigger = function (trigger) {
  40487. for (var t in ActionManager.Triggers) {
  40488. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40489. var t_int = parseInt(t);
  40490. if (t_int === trigger) {
  40491. return true;
  40492. }
  40493. }
  40494. }
  40495. return false;
  40496. };
  40497. /**
  40498. * Registers an action to this action manager
  40499. * @param {BABYLON.Action} action - the action to be registered
  40500. * @return {BABYLON.Action} the action amended (prepared) after registration
  40501. */
  40502. ActionManager.prototype.registerAction = function (action) {
  40503. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40504. if (this.getScene().actionManager !== this) {
  40505. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40506. return null;
  40507. }
  40508. }
  40509. this.actions.push(action);
  40510. if (ActionManager.Triggers[action.trigger]) {
  40511. ActionManager.Triggers[action.trigger]++;
  40512. }
  40513. else {
  40514. ActionManager.Triggers[action.trigger] = 1;
  40515. }
  40516. action._actionManager = this;
  40517. action._prepare();
  40518. return action;
  40519. };
  40520. /**
  40521. * Process a specific trigger
  40522. * @param {number} trigger - the trigger to process
  40523. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40524. */
  40525. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40526. for (var index = 0; index < this.actions.length; index++) {
  40527. var action = this.actions[index];
  40528. if (action.trigger === trigger) {
  40529. if (trigger === ActionManager.OnKeyUpTrigger
  40530. || trigger === ActionManager.OnKeyDownTrigger) {
  40531. var parameter = action.getTriggerParameter();
  40532. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40533. if (!parameter.toLowerCase) {
  40534. continue;
  40535. }
  40536. var lowerCase = parameter.toLowerCase();
  40537. if (lowerCase !== evt.sourceEvent.key) {
  40538. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40539. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40540. if (actualkey !== lowerCase) {
  40541. continue;
  40542. }
  40543. }
  40544. }
  40545. }
  40546. action._executeCurrent(evt);
  40547. }
  40548. }
  40549. };
  40550. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40551. var properties = propertyPath.split(".");
  40552. for (var index = 0; index < properties.length - 1; index++) {
  40553. target = target[properties[index]];
  40554. }
  40555. return target;
  40556. };
  40557. ActionManager.prototype._getProperty = function (propertyPath) {
  40558. var properties = propertyPath.split(".");
  40559. return properties[properties.length - 1];
  40560. };
  40561. ActionManager.prototype.serialize = function (name) {
  40562. var root = {
  40563. children: new Array(),
  40564. name: name,
  40565. type: 3,
  40566. properties: new Array() // Empty for root but required
  40567. };
  40568. for (var i = 0; i < this.actions.length; i++) {
  40569. var triggerObject = {
  40570. type: 0,
  40571. children: new Array(),
  40572. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40573. properties: new Array()
  40574. };
  40575. var triggerOptions = this.actions[i].triggerOptions;
  40576. if (triggerOptions && typeof triggerOptions !== "number") {
  40577. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40578. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40579. }
  40580. else {
  40581. var parameter = {};
  40582. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40583. if (triggerOptions.parameter.mesh) {
  40584. parameter._meshId = triggerOptions.parameter.mesh.id;
  40585. }
  40586. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40587. }
  40588. }
  40589. // Serialize child action, recursively
  40590. this.actions[i].serialize(triggerObject);
  40591. // Add serialized trigger
  40592. root.children.push(triggerObject);
  40593. }
  40594. return root;
  40595. };
  40596. ActionManager.Parse = function (parsedActions, object, scene) {
  40597. var actionManager = new BABYLON.ActionManager(scene);
  40598. if (object === null)
  40599. scene.actionManager = actionManager;
  40600. else
  40601. object.actionManager = actionManager;
  40602. // instanciate a new object
  40603. var instanciate = function (name, params) {
  40604. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  40605. newInstance.constructor.apply(newInstance, params);
  40606. return newInstance;
  40607. };
  40608. var parseParameter = function (name, value, target, propertyPath) {
  40609. if (propertyPath === null) {
  40610. // String, boolean or float
  40611. var floatValue = parseFloat(value);
  40612. if (value === "true" || value === "false")
  40613. return value === "true";
  40614. else
  40615. return isNaN(floatValue) ? value : floatValue;
  40616. }
  40617. var effectiveTarget = propertyPath.split(".");
  40618. var values = value.split(",");
  40619. // Get effective Target
  40620. for (var i = 0; i < effectiveTarget.length; i++) {
  40621. target = target[effectiveTarget[i]];
  40622. }
  40623. // Return appropriate value with its type
  40624. if (typeof (target) === "boolean")
  40625. return values[0] === "true";
  40626. if (typeof (target) === "string")
  40627. return values[0];
  40628. // Parameters with multiple values such as Vector3 etc.
  40629. var split = new Array();
  40630. for (var i = 0; i < values.length; i++)
  40631. split.push(parseFloat(values[i]));
  40632. if (target instanceof BABYLON.Vector3)
  40633. return BABYLON.Vector3.FromArray(split);
  40634. if (target instanceof BABYLON.Vector4)
  40635. return BABYLON.Vector4.FromArray(split);
  40636. if (target instanceof BABYLON.Color3)
  40637. return BABYLON.Color3.FromArray(split);
  40638. if (target instanceof BABYLON.Color4)
  40639. return BABYLON.Color4.FromArray(split);
  40640. return parseFloat(values[0]);
  40641. };
  40642. // traverse graph per trigger
  40643. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40644. if (combineArray === void 0) { combineArray = null; }
  40645. if (parsedAction.detached)
  40646. return;
  40647. var parameters = new Array();
  40648. var target = null;
  40649. var propertyPath = null;
  40650. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40651. // Parameters
  40652. if (parsedAction.type === 2)
  40653. parameters.push(actionManager);
  40654. else
  40655. parameters.push(trigger);
  40656. if (combine) {
  40657. var actions = new Array();
  40658. for (var j = 0; j < parsedAction.combine.length; j++) {
  40659. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40660. }
  40661. parameters.push(actions);
  40662. }
  40663. else {
  40664. for (var i = 0; i < parsedAction.properties.length; i++) {
  40665. var value = parsedAction.properties[i].value;
  40666. var name = parsedAction.properties[i].name;
  40667. var targetType = parsedAction.properties[i].targetType;
  40668. if (name === "target")
  40669. if (targetType !== null && targetType === "SceneProperties")
  40670. value = target = scene;
  40671. else
  40672. value = target = scene.getNodeByName(value);
  40673. else if (name === "parent")
  40674. value = scene.getNodeByName(value);
  40675. else if (name === "sound")
  40676. value = scene.getSoundByName(value);
  40677. else if (name !== "propertyPath") {
  40678. if (parsedAction.type === 2 && name === "operator")
  40679. value = BABYLON.ValueCondition[value];
  40680. else
  40681. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40682. }
  40683. else {
  40684. propertyPath = value;
  40685. }
  40686. parameters.push(value);
  40687. }
  40688. }
  40689. if (combineArray === null) {
  40690. parameters.push(condition);
  40691. }
  40692. else {
  40693. parameters.push(null);
  40694. }
  40695. // If interpolate value action
  40696. if (parsedAction.name === "InterpolateValueAction") {
  40697. var param = parameters[parameters.length - 2];
  40698. parameters[parameters.length - 1] = param;
  40699. parameters[parameters.length - 2] = condition;
  40700. }
  40701. // Action or condition(s) and not CombineAction
  40702. var newAction = instanciate(parsedAction.name, parameters);
  40703. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40704. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40705. if (action)
  40706. action.then(nothing);
  40707. else
  40708. actionManager.registerAction(nothing);
  40709. action = nothing;
  40710. }
  40711. if (combineArray === null) {
  40712. if (newAction instanceof BABYLON.Condition) {
  40713. condition = newAction;
  40714. newAction = action;
  40715. }
  40716. else {
  40717. condition = null;
  40718. if (action)
  40719. action.then(newAction);
  40720. else
  40721. actionManager.registerAction(newAction);
  40722. }
  40723. }
  40724. else {
  40725. combineArray.push(newAction);
  40726. }
  40727. for (var i = 0; i < parsedAction.children.length; i++)
  40728. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40729. };
  40730. // triggers
  40731. for (var i = 0; i < parsedActions.children.length; i++) {
  40732. var triggerParams;
  40733. var trigger = parsedActions.children[i];
  40734. if (trigger.properties.length > 0) {
  40735. var param = trigger.properties[0].value;
  40736. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40737. if (value._meshId) {
  40738. value.mesh = scene.getMeshByID(value._meshId);
  40739. }
  40740. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  40741. }
  40742. else
  40743. triggerParams = ActionManager[trigger.name];
  40744. for (var j = 0; j < trigger.children.length; j++) {
  40745. if (!trigger.detached)
  40746. traverse(trigger.children[j], triggerParams, null, null);
  40747. }
  40748. }
  40749. };
  40750. ActionManager.GetTriggerName = function (trigger) {
  40751. switch (trigger) {
  40752. case 0: return "NothingTrigger";
  40753. case 1: return "OnPickTrigger";
  40754. case 2: return "OnLeftPickTrigger";
  40755. case 3: return "OnRightPickTrigger";
  40756. case 4: return "OnCenterPickTrigger";
  40757. case 5: return "OnPickDownTrigger";
  40758. case 6: return "OnPickUpTrigger";
  40759. case 7: return "OnLongPressTrigger";
  40760. case 8: return "OnPointerOverTrigger";
  40761. case 9: return "OnPointerOutTrigger";
  40762. case 10: return "OnEveryFrameTrigger";
  40763. case 11: return "OnIntersectionEnterTrigger";
  40764. case 12: return "OnIntersectionExitTrigger";
  40765. case 13: return "OnKeyDownTrigger";
  40766. case 14: return "OnKeyUpTrigger";
  40767. case 15: return "OnPickOutTrigger";
  40768. default: return "";
  40769. }
  40770. };
  40771. // Statics
  40772. ActionManager._NothingTrigger = 0;
  40773. ActionManager._OnPickTrigger = 1;
  40774. ActionManager._OnLeftPickTrigger = 2;
  40775. ActionManager._OnRightPickTrigger = 3;
  40776. ActionManager._OnCenterPickTrigger = 4;
  40777. ActionManager._OnPickDownTrigger = 5;
  40778. ActionManager._OnDoublePickTrigger = 6;
  40779. ActionManager._OnPickUpTrigger = 7;
  40780. ActionManager._OnLongPressTrigger = 8;
  40781. ActionManager._OnPointerOverTrigger = 9;
  40782. ActionManager._OnPointerOutTrigger = 10;
  40783. ActionManager._OnEveryFrameTrigger = 11;
  40784. ActionManager._OnIntersectionEnterTrigger = 12;
  40785. ActionManager._OnIntersectionExitTrigger = 13;
  40786. ActionManager._OnKeyDownTrigger = 14;
  40787. ActionManager._OnKeyUpTrigger = 15;
  40788. ActionManager._OnPickOutTrigger = 16;
  40789. ActionManager.Triggers = {};
  40790. return ActionManager;
  40791. }());
  40792. BABYLON.ActionManager = ActionManager;
  40793. })(BABYLON || (BABYLON = {}));
  40794. //# sourceMappingURL=babylon.actionManager.js.map
  40795. var BABYLON;
  40796. (function (BABYLON) {
  40797. var InterpolateValueAction = (function (_super) {
  40798. __extends(InterpolateValueAction, _super);
  40799. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40800. if (duration === void 0) { duration = 1000; }
  40801. var _this = _super.call(this, triggerOptions, condition) || this;
  40802. _this.propertyPath = propertyPath;
  40803. _this.value = value;
  40804. _this.duration = duration;
  40805. _this.stopOtherAnimations = stopOtherAnimations;
  40806. _this.onInterpolationDone = onInterpolationDone;
  40807. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  40808. _this._target = _this._effectiveTarget = target;
  40809. return _this;
  40810. }
  40811. InterpolateValueAction.prototype._prepare = function () {
  40812. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40813. this._property = this._getProperty(this.propertyPath);
  40814. };
  40815. InterpolateValueAction.prototype.execute = function () {
  40816. var _this = this;
  40817. var scene = this._actionManager.getScene();
  40818. var keys = [
  40819. {
  40820. frame: 0,
  40821. value: this._effectiveTarget[this._property]
  40822. }, {
  40823. frame: 100,
  40824. value: this.value
  40825. }
  40826. ];
  40827. var dataType;
  40828. if (typeof this.value === "number") {
  40829. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40830. }
  40831. else if (this.value instanceof BABYLON.Color3) {
  40832. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40833. }
  40834. else if (this.value instanceof BABYLON.Vector3) {
  40835. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40836. }
  40837. else if (this.value instanceof BABYLON.Matrix) {
  40838. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40839. }
  40840. else if (this.value instanceof BABYLON.Quaternion) {
  40841. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40842. }
  40843. else {
  40844. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40845. return;
  40846. }
  40847. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40848. animation.setKeys(keys);
  40849. if (this.stopOtherAnimations) {
  40850. scene.stopAnimation(this._effectiveTarget);
  40851. }
  40852. var wrapper = function () {
  40853. _this.onInterpolationDoneObservable.notifyObservers(_this);
  40854. if (_this.onInterpolationDone) {
  40855. _this.onInterpolationDone();
  40856. }
  40857. };
  40858. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  40859. };
  40860. InterpolateValueAction.prototype.serialize = function (parent) {
  40861. return _super.prototype._serialize.call(this, {
  40862. name: "InterpolateValueAction",
  40863. properties: [
  40864. BABYLON.Action._GetTargetProperty(this._target),
  40865. { name: "propertyPath", value: this.propertyPath },
  40866. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40867. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40868. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40869. ]
  40870. }, parent);
  40871. };
  40872. return InterpolateValueAction;
  40873. }(BABYLON.Action));
  40874. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40875. })(BABYLON || (BABYLON = {}));
  40876. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40877. var BABYLON;
  40878. (function (BABYLON) {
  40879. var SwitchBooleanAction = (function (_super) {
  40880. __extends(SwitchBooleanAction, _super);
  40881. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40882. var _this = _super.call(this, triggerOptions, condition) || this;
  40883. _this.propertyPath = propertyPath;
  40884. _this._target = _this._effectiveTarget = target;
  40885. return _this;
  40886. }
  40887. SwitchBooleanAction.prototype._prepare = function () {
  40888. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40889. this._property = this._getProperty(this.propertyPath);
  40890. };
  40891. SwitchBooleanAction.prototype.execute = function () {
  40892. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40893. };
  40894. SwitchBooleanAction.prototype.serialize = function (parent) {
  40895. return _super.prototype._serialize.call(this, {
  40896. name: "SwitchBooleanAction",
  40897. properties: [
  40898. BABYLON.Action._GetTargetProperty(this._target),
  40899. { name: "propertyPath", value: this.propertyPath }
  40900. ]
  40901. }, parent);
  40902. };
  40903. return SwitchBooleanAction;
  40904. }(BABYLON.Action));
  40905. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40906. var SetStateAction = (function (_super) {
  40907. __extends(SetStateAction, _super);
  40908. function SetStateAction(triggerOptions, target, value, condition) {
  40909. var _this = _super.call(this, triggerOptions, condition) || this;
  40910. _this.value = value;
  40911. _this._target = target;
  40912. return _this;
  40913. }
  40914. SetStateAction.prototype.execute = function () {
  40915. this._target.state = this.value;
  40916. };
  40917. SetStateAction.prototype.serialize = function (parent) {
  40918. return _super.prototype._serialize.call(this, {
  40919. name: "SetStateAction",
  40920. properties: [
  40921. BABYLON.Action._GetTargetProperty(this._target),
  40922. { name: "value", value: this.value }
  40923. ]
  40924. }, parent);
  40925. };
  40926. return SetStateAction;
  40927. }(BABYLON.Action));
  40928. BABYLON.SetStateAction = SetStateAction;
  40929. var SetValueAction = (function (_super) {
  40930. __extends(SetValueAction, _super);
  40931. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40932. var _this = _super.call(this, triggerOptions, condition) || this;
  40933. _this.propertyPath = propertyPath;
  40934. _this.value = value;
  40935. _this._target = _this._effectiveTarget = target;
  40936. return _this;
  40937. }
  40938. SetValueAction.prototype._prepare = function () {
  40939. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40940. this._property = this._getProperty(this.propertyPath);
  40941. };
  40942. SetValueAction.prototype.execute = function () {
  40943. this._effectiveTarget[this._property] = this.value;
  40944. if (this._target.markAsDirty) {
  40945. this._target.markAsDirty(this._property);
  40946. }
  40947. };
  40948. SetValueAction.prototype.serialize = function (parent) {
  40949. return _super.prototype._serialize.call(this, {
  40950. name: "SetValueAction",
  40951. properties: [
  40952. BABYLON.Action._GetTargetProperty(this._target),
  40953. { name: "propertyPath", value: this.propertyPath },
  40954. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40955. ]
  40956. }, parent);
  40957. };
  40958. return SetValueAction;
  40959. }(BABYLON.Action));
  40960. BABYLON.SetValueAction = SetValueAction;
  40961. var IncrementValueAction = (function (_super) {
  40962. __extends(IncrementValueAction, _super);
  40963. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40964. var _this = _super.call(this, triggerOptions, condition) || this;
  40965. _this.propertyPath = propertyPath;
  40966. _this.value = value;
  40967. _this._target = _this._effectiveTarget = target;
  40968. return _this;
  40969. }
  40970. IncrementValueAction.prototype._prepare = function () {
  40971. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40972. this._property = this._getProperty(this.propertyPath);
  40973. if (typeof this._effectiveTarget[this._property] !== "number") {
  40974. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40975. }
  40976. };
  40977. IncrementValueAction.prototype.execute = function () {
  40978. this._effectiveTarget[this._property] += this.value;
  40979. if (this._target.markAsDirty) {
  40980. this._target.markAsDirty(this._property);
  40981. }
  40982. };
  40983. IncrementValueAction.prototype.serialize = function (parent) {
  40984. return _super.prototype._serialize.call(this, {
  40985. name: "IncrementValueAction",
  40986. properties: [
  40987. BABYLON.Action._GetTargetProperty(this._target),
  40988. { name: "propertyPath", value: this.propertyPath },
  40989. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40990. ]
  40991. }, parent);
  40992. };
  40993. return IncrementValueAction;
  40994. }(BABYLON.Action));
  40995. BABYLON.IncrementValueAction = IncrementValueAction;
  40996. var PlayAnimationAction = (function (_super) {
  40997. __extends(PlayAnimationAction, _super);
  40998. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40999. var _this = _super.call(this, triggerOptions, condition) || this;
  41000. _this.from = from;
  41001. _this.to = to;
  41002. _this.loop = loop;
  41003. _this._target = target;
  41004. return _this;
  41005. }
  41006. PlayAnimationAction.prototype._prepare = function () {
  41007. };
  41008. PlayAnimationAction.prototype.execute = function () {
  41009. var scene = this._actionManager.getScene();
  41010. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  41011. };
  41012. PlayAnimationAction.prototype.serialize = function (parent) {
  41013. return _super.prototype._serialize.call(this, {
  41014. name: "PlayAnimationAction",
  41015. properties: [
  41016. BABYLON.Action._GetTargetProperty(this._target),
  41017. { name: "from", value: String(this.from) },
  41018. { name: "to", value: String(this.to) },
  41019. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  41020. ]
  41021. }, parent);
  41022. };
  41023. return PlayAnimationAction;
  41024. }(BABYLON.Action));
  41025. BABYLON.PlayAnimationAction = PlayAnimationAction;
  41026. var StopAnimationAction = (function (_super) {
  41027. __extends(StopAnimationAction, _super);
  41028. function StopAnimationAction(triggerOptions, target, condition) {
  41029. var _this = _super.call(this, triggerOptions, condition) || this;
  41030. _this._target = target;
  41031. return _this;
  41032. }
  41033. StopAnimationAction.prototype._prepare = function () {
  41034. };
  41035. StopAnimationAction.prototype.execute = function () {
  41036. var scene = this._actionManager.getScene();
  41037. scene.stopAnimation(this._target);
  41038. };
  41039. StopAnimationAction.prototype.serialize = function (parent) {
  41040. return _super.prototype._serialize.call(this, {
  41041. name: "StopAnimationAction",
  41042. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41043. }, parent);
  41044. };
  41045. return StopAnimationAction;
  41046. }(BABYLON.Action));
  41047. BABYLON.StopAnimationAction = StopAnimationAction;
  41048. var DoNothingAction = (function (_super) {
  41049. __extends(DoNothingAction, _super);
  41050. function DoNothingAction(triggerOptions, condition) {
  41051. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41052. return _super.call(this, triggerOptions, condition) || this;
  41053. }
  41054. DoNothingAction.prototype.execute = function () {
  41055. };
  41056. DoNothingAction.prototype.serialize = function (parent) {
  41057. return _super.prototype._serialize.call(this, {
  41058. name: "DoNothingAction",
  41059. properties: []
  41060. }, parent);
  41061. };
  41062. return DoNothingAction;
  41063. }(BABYLON.Action));
  41064. BABYLON.DoNothingAction = DoNothingAction;
  41065. var CombineAction = (function (_super) {
  41066. __extends(CombineAction, _super);
  41067. function CombineAction(triggerOptions, children, condition) {
  41068. var _this = _super.call(this, triggerOptions, condition) || this;
  41069. _this.children = children;
  41070. return _this;
  41071. }
  41072. CombineAction.prototype._prepare = function () {
  41073. for (var index = 0; index < this.children.length; index++) {
  41074. this.children[index]._actionManager = this._actionManager;
  41075. this.children[index]._prepare();
  41076. }
  41077. };
  41078. CombineAction.prototype.execute = function (evt) {
  41079. for (var index = 0; index < this.children.length; index++) {
  41080. this.children[index].execute(evt);
  41081. }
  41082. };
  41083. CombineAction.prototype.serialize = function (parent) {
  41084. var serializationObject = _super.prototype._serialize.call(this, {
  41085. name: "CombineAction",
  41086. properties: [],
  41087. combine: []
  41088. }, parent);
  41089. for (var i = 0; i < this.children.length; i++) {
  41090. serializationObject.combine.push(this.children[i].serialize(null));
  41091. }
  41092. return serializationObject;
  41093. };
  41094. return CombineAction;
  41095. }(BABYLON.Action));
  41096. BABYLON.CombineAction = CombineAction;
  41097. var ExecuteCodeAction = (function (_super) {
  41098. __extends(ExecuteCodeAction, _super);
  41099. function ExecuteCodeAction(triggerOptions, func, condition) {
  41100. var _this = _super.call(this, triggerOptions, condition) || this;
  41101. _this.func = func;
  41102. return _this;
  41103. }
  41104. ExecuteCodeAction.prototype.execute = function (evt) {
  41105. this.func(evt);
  41106. };
  41107. return ExecuteCodeAction;
  41108. }(BABYLON.Action));
  41109. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  41110. var SetParentAction = (function (_super) {
  41111. __extends(SetParentAction, _super);
  41112. function SetParentAction(triggerOptions, target, parent, condition) {
  41113. var _this = _super.call(this, triggerOptions, condition) || this;
  41114. _this._target = target;
  41115. _this._parent = parent;
  41116. return _this;
  41117. }
  41118. SetParentAction.prototype._prepare = function () {
  41119. };
  41120. SetParentAction.prototype.execute = function () {
  41121. if (this._target.parent === this._parent) {
  41122. return;
  41123. }
  41124. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  41125. invertParentWorldMatrix.invert();
  41126. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  41127. this._target.parent = this._parent;
  41128. };
  41129. SetParentAction.prototype.serialize = function (parent) {
  41130. return _super.prototype._serialize.call(this, {
  41131. name: "SetParentAction",
  41132. properties: [
  41133. BABYLON.Action._GetTargetProperty(this._target),
  41134. BABYLON.Action._GetTargetProperty(this._parent),
  41135. ]
  41136. }, parent);
  41137. };
  41138. return SetParentAction;
  41139. }(BABYLON.Action));
  41140. BABYLON.SetParentAction = SetParentAction;
  41141. var PlaySoundAction = (function (_super) {
  41142. __extends(PlaySoundAction, _super);
  41143. function PlaySoundAction(triggerOptions, sound, condition) {
  41144. var _this = _super.call(this, triggerOptions, condition) || this;
  41145. _this._sound = sound;
  41146. return _this;
  41147. }
  41148. PlaySoundAction.prototype._prepare = function () {
  41149. };
  41150. PlaySoundAction.prototype.execute = function () {
  41151. if (this._sound !== undefined)
  41152. this._sound.play();
  41153. };
  41154. PlaySoundAction.prototype.serialize = function (parent) {
  41155. return _super.prototype._serialize.call(this, {
  41156. name: "PlaySoundAction",
  41157. properties: [{ name: "sound", value: this._sound.name }]
  41158. }, parent);
  41159. };
  41160. return PlaySoundAction;
  41161. }(BABYLON.Action));
  41162. BABYLON.PlaySoundAction = PlaySoundAction;
  41163. var StopSoundAction = (function (_super) {
  41164. __extends(StopSoundAction, _super);
  41165. function StopSoundAction(triggerOptions, sound, condition) {
  41166. var _this = _super.call(this, triggerOptions, condition) || this;
  41167. _this._sound = sound;
  41168. return _this;
  41169. }
  41170. StopSoundAction.prototype._prepare = function () {
  41171. };
  41172. StopSoundAction.prototype.execute = function () {
  41173. if (this._sound !== undefined)
  41174. this._sound.stop();
  41175. };
  41176. StopSoundAction.prototype.serialize = function (parent) {
  41177. return _super.prototype._serialize.call(this, {
  41178. name: "StopSoundAction",
  41179. properties: [{ name: "sound", value: this._sound.name }]
  41180. }, parent);
  41181. };
  41182. return StopSoundAction;
  41183. }(BABYLON.Action));
  41184. BABYLON.StopSoundAction = StopSoundAction;
  41185. })(BABYLON || (BABYLON = {}));
  41186. //# sourceMappingURL=babylon.directActions.js.map
  41187. var BABYLON;
  41188. (function (BABYLON) {
  41189. var SpriteManager = (function () {
  41190. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  41191. if (epsilon === void 0) { epsilon = 0.01; }
  41192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41193. this.name = name;
  41194. this.sprites = new Array();
  41195. this.renderingGroupId = 0;
  41196. this.layerMask = 0x0FFFFFFF;
  41197. this.fogEnabled = true;
  41198. this.isPickable = false;
  41199. /**
  41200. * An event triggered when the manager is disposed.
  41201. * @type {BABYLON.Observable}
  41202. */
  41203. this.onDisposeObservable = new BABYLON.Observable();
  41204. this._vertexBuffers = {};
  41205. this._capacity = capacity;
  41206. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  41207. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41208. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41209. if (cellSize.width && cellSize.height) {
  41210. this.cellWidth = cellSize.width;
  41211. this.cellHeight = cellSize.height;
  41212. }
  41213. else if (cellSize !== undefined) {
  41214. this.cellWidth = cellSize;
  41215. this.cellHeight = cellSize;
  41216. }
  41217. else {
  41218. return;
  41219. }
  41220. this._epsilon = epsilon;
  41221. this._scene = scene;
  41222. this._scene.spriteManagers.push(this);
  41223. var indices = [];
  41224. var index = 0;
  41225. for (var count = 0; count < capacity; count++) {
  41226. indices.push(index);
  41227. indices.push(index + 1);
  41228. indices.push(index + 2);
  41229. indices.push(index);
  41230. indices.push(index + 2);
  41231. indices.push(index + 3);
  41232. index += 4;
  41233. }
  41234. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  41235. // VBO
  41236. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  41237. this._vertexData = new Float32Array(capacity * 16 * 4);
  41238. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  41239. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  41240. var options = this._buffer.createVertexBuffer("options", 4, 4);
  41241. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  41242. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  41243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41244. this._vertexBuffers["options"] = options;
  41245. this._vertexBuffers["cellInfo"] = cellInfo;
  41246. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41247. // Effects
  41248. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  41249. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  41250. }
  41251. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  41252. set: function (callback) {
  41253. if (this._onDisposeObserver) {
  41254. this.onDisposeObservable.remove(this._onDisposeObserver);
  41255. }
  41256. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41257. },
  41258. enumerable: true,
  41259. configurable: true
  41260. });
  41261. Object.defineProperty(SpriteManager.prototype, "texture", {
  41262. get: function () {
  41263. return this._spriteTexture;
  41264. },
  41265. set: function (value) {
  41266. this._spriteTexture = value;
  41267. },
  41268. enumerable: true,
  41269. configurable: true
  41270. });
  41271. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  41272. var arrayOffset = index * 16;
  41273. if (offsetX === 0)
  41274. offsetX = this._epsilon;
  41275. else if (offsetX === 1)
  41276. offsetX = 1 - this._epsilon;
  41277. if (offsetY === 0)
  41278. offsetY = this._epsilon;
  41279. else if (offsetY === 1)
  41280. offsetY = 1 - this._epsilon;
  41281. this._vertexData[arrayOffset] = sprite.position.x;
  41282. this._vertexData[arrayOffset + 1] = sprite.position.y;
  41283. this._vertexData[arrayOffset + 2] = sprite.position.z;
  41284. this._vertexData[arrayOffset + 3] = sprite.angle;
  41285. this._vertexData[arrayOffset + 4] = sprite.width;
  41286. this._vertexData[arrayOffset + 5] = sprite.height;
  41287. this._vertexData[arrayOffset + 6] = offsetX;
  41288. this._vertexData[arrayOffset + 7] = offsetY;
  41289. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  41290. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  41291. var offset = (sprite.cellIndex / rowSize) >> 0;
  41292. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  41293. this._vertexData[arrayOffset + 11] = offset;
  41294. // Color
  41295. this._vertexData[arrayOffset + 12] = sprite.color.r;
  41296. this._vertexData[arrayOffset + 13] = sprite.color.g;
  41297. this._vertexData[arrayOffset + 14] = sprite.color.b;
  41298. this._vertexData[arrayOffset + 15] = sprite.color.a;
  41299. };
  41300. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  41301. var count = Math.min(this._capacity, this.sprites.length);
  41302. var min = BABYLON.Vector3.Zero();
  41303. var max = BABYLON.Vector3.Zero();
  41304. var distance = Number.MAX_VALUE;
  41305. var currentSprite;
  41306. var cameraSpacePosition = BABYLON.Vector3.Zero();
  41307. var cameraView = camera.getViewMatrix();
  41308. for (var index = 0; index < count; index++) {
  41309. var sprite = this.sprites[index];
  41310. if (!sprite) {
  41311. continue;
  41312. }
  41313. if (predicate) {
  41314. if (!predicate(sprite)) {
  41315. continue;
  41316. }
  41317. }
  41318. else if (!sprite.isPickable) {
  41319. continue;
  41320. }
  41321. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  41322. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  41323. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  41324. if (ray.intersectsBoxMinMax(min, max)) {
  41325. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  41326. if (distance > currentDistance) {
  41327. distance = currentDistance;
  41328. currentSprite = sprite;
  41329. if (fastCheck) {
  41330. break;
  41331. }
  41332. }
  41333. }
  41334. }
  41335. if (currentSprite) {
  41336. var result = new BABYLON.PickingInfo();
  41337. result.hit = true;
  41338. result.pickedSprite = currentSprite;
  41339. result.distance = distance;
  41340. return result;
  41341. }
  41342. return null;
  41343. };
  41344. SpriteManager.prototype.render = function () {
  41345. // Check
  41346. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  41347. return;
  41348. var engine = this._scene.getEngine();
  41349. var baseSize = this._spriteTexture.getBaseSize();
  41350. // Sprites
  41351. var deltaTime = engine.getDeltaTime();
  41352. var max = Math.min(this._capacity, this.sprites.length);
  41353. var rowSize = baseSize.width / this.cellWidth;
  41354. var offset = 0;
  41355. for (var index = 0; index < max; index++) {
  41356. var sprite = this.sprites[index];
  41357. if (!sprite) {
  41358. continue;
  41359. }
  41360. sprite._animate(deltaTime);
  41361. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  41362. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  41363. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  41364. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  41365. }
  41366. this._buffer.update(this._vertexData);
  41367. // Render
  41368. var effect = this._effectBase;
  41369. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41370. effect = this._effectFog;
  41371. }
  41372. engine.enableEffect(effect);
  41373. var viewMatrix = this._scene.getViewMatrix();
  41374. effect.setTexture("diffuseSampler", this._spriteTexture);
  41375. effect.setMatrix("view", viewMatrix);
  41376. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41377. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  41378. // Fog
  41379. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41380. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  41381. effect.setColor3("vFogColor", this._scene.fogColor);
  41382. }
  41383. // VBOs
  41384. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41385. // Draw order
  41386. engine.setDepthFunctionToLessOrEqual();
  41387. effect.setBool("alphaTest", true);
  41388. engine.setColorWrite(false);
  41389. engine.draw(true, 0, max * 6);
  41390. engine.setColorWrite(true);
  41391. effect.setBool("alphaTest", false);
  41392. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41393. engine.draw(true, 0, max * 6);
  41394. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41395. };
  41396. SpriteManager.prototype.dispose = function () {
  41397. if (this._buffer) {
  41398. this._buffer.dispose();
  41399. this._buffer = null;
  41400. }
  41401. if (this._indexBuffer) {
  41402. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41403. this._indexBuffer = null;
  41404. }
  41405. if (this._spriteTexture) {
  41406. this._spriteTexture.dispose();
  41407. this._spriteTexture = null;
  41408. }
  41409. // Remove from scene
  41410. var index = this._scene.spriteManagers.indexOf(this);
  41411. this._scene.spriteManagers.splice(index, 1);
  41412. // Callback
  41413. this.onDisposeObservable.notifyObservers(this);
  41414. this.onDisposeObservable.clear();
  41415. };
  41416. return SpriteManager;
  41417. }());
  41418. BABYLON.SpriteManager = SpriteManager;
  41419. })(BABYLON || (BABYLON = {}));
  41420. //# sourceMappingURL=babylon.spriteManager.js.map
  41421. var BABYLON;
  41422. (function (BABYLON) {
  41423. var Sprite = (function () {
  41424. function Sprite(name, manager) {
  41425. this.name = name;
  41426. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41427. this.width = 1.0;
  41428. this.height = 1.0;
  41429. this.angle = 0;
  41430. this.cellIndex = 0;
  41431. this.invertU = 0;
  41432. this.invertV = 0;
  41433. this.animations = new Array();
  41434. this.isPickable = false;
  41435. this._animationStarted = false;
  41436. this._loopAnimation = false;
  41437. this._fromIndex = 0;
  41438. this._toIndex = 0;
  41439. this._delay = 0;
  41440. this._direction = 1;
  41441. this._frameCount = 0;
  41442. this._time = 0;
  41443. this._manager = manager;
  41444. this._manager.sprites.push(this);
  41445. this.position = BABYLON.Vector3.Zero();
  41446. }
  41447. Object.defineProperty(Sprite.prototype, "size", {
  41448. get: function () {
  41449. return this.width;
  41450. },
  41451. set: function (value) {
  41452. this.width = value;
  41453. this.height = value;
  41454. },
  41455. enumerable: true,
  41456. configurable: true
  41457. });
  41458. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  41459. this._fromIndex = from;
  41460. this._toIndex = to;
  41461. this._loopAnimation = loop;
  41462. this._delay = delay;
  41463. this._animationStarted = true;
  41464. this._direction = from < to ? 1 : -1;
  41465. this.cellIndex = from;
  41466. this._time = 0;
  41467. this._onAnimationEnd = onAnimationEnd;
  41468. };
  41469. Sprite.prototype.stopAnimation = function () {
  41470. this._animationStarted = false;
  41471. };
  41472. Sprite.prototype._animate = function (deltaTime) {
  41473. if (!this._animationStarted)
  41474. return;
  41475. this._time += deltaTime;
  41476. if (this._time > this._delay) {
  41477. this._time = this._time % this._delay;
  41478. this.cellIndex += this._direction;
  41479. if (this.cellIndex > this._toIndex) {
  41480. if (this._loopAnimation) {
  41481. this.cellIndex = this._fromIndex;
  41482. }
  41483. else {
  41484. this.cellIndex = this._toIndex;
  41485. this._animationStarted = false;
  41486. if (this._onAnimationEnd) {
  41487. this._onAnimationEnd();
  41488. }
  41489. if (this.disposeWhenFinishedAnimating) {
  41490. this.dispose();
  41491. }
  41492. }
  41493. }
  41494. }
  41495. };
  41496. Sprite.prototype.dispose = function () {
  41497. for (var i = 0; i < this._manager.sprites.length; i++) {
  41498. if (this._manager.sprites[i] == this) {
  41499. this._manager.sprites.splice(i, 1);
  41500. }
  41501. }
  41502. };
  41503. return Sprite;
  41504. }());
  41505. BABYLON.Sprite = Sprite;
  41506. })(BABYLON || (BABYLON = {}));
  41507. //# sourceMappingURL=babylon.sprite.js.map
  41508. var BABYLON;
  41509. (function (BABYLON) {
  41510. var IntersectionInfo = (function () {
  41511. function IntersectionInfo(bu, bv, distance) {
  41512. this.bu = bu;
  41513. this.bv = bv;
  41514. this.distance = distance;
  41515. this.faceId = 0;
  41516. this.subMeshId = 0;
  41517. }
  41518. return IntersectionInfo;
  41519. }());
  41520. BABYLON.IntersectionInfo = IntersectionInfo;
  41521. var PickingInfo = (function () {
  41522. function PickingInfo() {
  41523. this.hit = false;
  41524. this.distance = 0;
  41525. this.pickedPoint = null;
  41526. this.pickedMesh = null;
  41527. this.bu = 0;
  41528. this.bv = 0;
  41529. this.faceId = -1;
  41530. this.subMeshId = 0;
  41531. this.pickedSprite = null;
  41532. }
  41533. // Methods
  41534. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  41535. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  41536. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  41537. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41538. return null;
  41539. }
  41540. var indices = this.pickedMesh.getIndices();
  41541. var result;
  41542. if (useVerticesNormals) {
  41543. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41544. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  41545. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  41546. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  41547. normal0 = normal0.scale(this.bu);
  41548. normal1 = normal1.scale(this.bv);
  41549. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  41550. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  41551. }
  41552. else {
  41553. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41554. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  41555. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  41556. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  41557. var p1p2 = vertex1.subtract(vertex2);
  41558. var p3p2 = vertex3.subtract(vertex2);
  41559. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  41560. }
  41561. if (useWorldCoordinates) {
  41562. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  41563. }
  41564. return BABYLON.Vector3.Normalize(result);
  41565. };
  41566. PickingInfo.prototype.getTextureCoordinates = function () {
  41567. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41568. return null;
  41569. }
  41570. var indices = this.pickedMesh.getIndices();
  41571. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41572. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  41573. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  41574. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  41575. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  41576. uv1 = uv1.scale(this.bu);
  41577. uv2 = uv2.scale(this.bv);
  41578. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  41579. };
  41580. return PickingInfo;
  41581. }());
  41582. BABYLON.PickingInfo = PickingInfo;
  41583. })(BABYLON || (BABYLON = {}));
  41584. //# sourceMappingURL=babylon.pickingInfo.js.map
  41585. var BABYLON;
  41586. (function (BABYLON) {
  41587. var Ray = (function () {
  41588. function Ray(origin, direction, length) {
  41589. if (length === void 0) { length = Number.MAX_VALUE; }
  41590. this.origin = origin;
  41591. this.direction = direction;
  41592. this.length = length;
  41593. }
  41594. // Methods
  41595. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  41596. var d = 0.0;
  41597. var maxValue = Number.MAX_VALUE;
  41598. var inv;
  41599. var min;
  41600. var max;
  41601. var temp;
  41602. if (Math.abs(this.direction.x) < 0.0000001) {
  41603. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  41604. return false;
  41605. }
  41606. }
  41607. else {
  41608. inv = 1.0 / this.direction.x;
  41609. min = (minimum.x - this.origin.x) * inv;
  41610. max = (maximum.x - this.origin.x) * inv;
  41611. if (max === -Infinity) {
  41612. max = Infinity;
  41613. }
  41614. if (min > max) {
  41615. temp = min;
  41616. min = max;
  41617. max = temp;
  41618. }
  41619. d = Math.max(min, d);
  41620. maxValue = Math.min(max, maxValue);
  41621. if (d > maxValue) {
  41622. return false;
  41623. }
  41624. }
  41625. if (Math.abs(this.direction.y) < 0.0000001) {
  41626. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  41627. return false;
  41628. }
  41629. }
  41630. else {
  41631. inv = 1.0 / this.direction.y;
  41632. min = (minimum.y - this.origin.y) * inv;
  41633. max = (maximum.y - this.origin.y) * inv;
  41634. if (max === -Infinity) {
  41635. max = Infinity;
  41636. }
  41637. if (min > max) {
  41638. temp = min;
  41639. min = max;
  41640. max = temp;
  41641. }
  41642. d = Math.max(min, d);
  41643. maxValue = Math.min(max, maxValue);
  41644. if (d > maxValue) {
  41645. return false;
  41646. }
  41647. }
  41648. if (Math.abs(this.direction.z) < 0.0000001) {
  41649. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  41650. return false;
  41651. }
  41652. }
  41653. else {
  41654. inv = 1.0 / this.direction.z;
  41655. min = (minimum.z - this.origin.z) * inv;
  41656. max = (maximum.z - this.origin.z) * inv;
  41657. if (max === -Infinity) {
  41658. max = Infinity;
  41659. }
  41660. if (min > max) {
  41661. temp = min;
  41662. min = max;
  41663. max = temp;
  41664. }
  41665. d = Math.max(min, d);
  41666. maxValue = Math.min(max, maxValue);
  41667. if (d > maxValue) {
  41668. return false;
  41669. }
  41670. }
  41671. return true;
  41672. };
  41673. Ray.prototype.intersectsBox = function (box) {
  41674. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  41675. };
  41676. Ray.prototype.intersectsSphere = function (sphere) {
  41677. var x = sphere.center.x - this.origin.x;
  41678. var y = sphere.center.y - this.origin.y;
  41679. var z = sphere.center.z - this.origin.z;
  41680. var pyth = (x * x) + (y * y) + (z * z);
  41681. var rr = sphere.radius * sphere.radius;
  41682. if (pyth <= rr) {
  41683. return true;
  41684. }
  41685. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  41686. if (dot < 0.0) {
  41687. return false;
  41688. }
  41689. var temp = pyth - (dot * dot);
  41690. return temp <= rr;
  41691. };
  41692. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  41693. if (!this._edge1) {
  41694. this._edge1 = BABYLON.Vector3.Zero();
  41695. this._edge2 = BABYLON.Vector3.Zero();
  41696. this._pvec = BABYLON.Vector3.Zero();
  41697. this._tvec = BABYLON.Vector3.Zero();
  41698. this._qvec = BABYLON.Vector3.Zero();
  41699. }
  41700. vertex1.subtractToRef(vertex0, this._edge1);
  41701. vertex2.subtractToRef(vertex0, this._edge2);
  41702. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  41703. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  41704. if (det === 0) {
  41705. return null;
  41706. }
  41707. var invdet = 1 / det;
  41708. this.origin.subtractToRef(vertex0, this._tvec);
  41709. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  41710. if (bu < 0 || bu > 1.0) {
  41711. return null;
  41712. }
  41713. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  41714. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  41715. if (bv < 0 || bu + bv > 1.0) {
  41716. return null;
  41717. }
  41718. //check if the distance is longer than the predefined length.
  41719. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  41720. if (distance > this.length) {
  41721. return null;
  41722. }
  41723. return new BABYLON.IntersectionInfo(bu, bv, distance);
  41724. };
  41725. Ray.prototype.intersectsPlane = function (plane) {
  41726. var distance;
  41727. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  41728. if (Math.abs(result1) < 9.99999997475243E-07) {
  41729. return null;
  41730. }
  41731. else {
  41732. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  41733. distance = (-plane.d - result2) / result1;
  41734. if (distance < 0.0) {
  41735. if (distance < -9.99999997475243E-07) {
  41736. return null;
  41737. }
  41738. else {
  41739. return 0;
  41740. }
  41741. }
  41742. return distance;
  41743. }
  41744. };
  41745. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  41746. var tm = BABYLON.Tmp.Matrix[0];
  41747. mesh.getWorldMatrix().invertToRef(tm);
  41748. if (this._tmpRay) {
  41749. Ray.TransformToRef(this, tm, this._tmpRay);
  41750. }
  41751. else {
  41752. this._tmpRay = Ray.Transform(this, tm);
  41753. }
  41754. return mesh.intersects(this._tmpRay, fastCheck);
  41755. };
  41756. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  41757. if (results) {
  41758. results.length = 0;
  41759. }
  41760. else {
  41761. results = [];
  41762. }
  41763. for (var i = 0; i < meshes.length; i++) {
  41764. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  41765. if (pickInfo.hit) {
  41766. results.push(pickInfo);
  41767. }
  41768. }
  41769. results.sort(this._comparePickingInfo);
  41770. return results;
  41771. };
  41772. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  41773. if (pickingInfoA.distance < pickingInfoB.distance) {
  41774. return -1;
  41775. }
  41776. else if (pickingInfoA.distance > pickingInfoB.distance) {
  41777. return 1;
  41778. }
  41779. else {
  41780. return 0;
  41781. }
  41782. };
  41783. /**
  41784. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  41785. * @param sega the first point of the segment to test the intersection against
  41786. * @param segb the second point of the segment to test the intersection against
  41787. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  41788. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  41789. */
  41790. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  41791. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  41792. var u = segb.subtract(sega);
  41793. var v = rsegb.subtract(this.origin);
  41794. var w = sega.subtract(this.origin);
  41795. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  41796. var b = BABYLON.Vector3.Dot(u, v);
  41797. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  41798. var d = BABYLON.Vector3.Dot(u, w);
  41799. var e = BABYLON.Vector3.Dot(v, w);
  41800. var D = a * c - b * b; // always >= 0
  41801. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  41802. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  41803. // compute the line parameters of the two closest points
  41804. if (D < Ray.smallnum) {
  41805. sN = 0.0; // force using point P0 on segment S1
  41806. sD = 1.0; // to prevent possible division by 0.0 later
  41807. tN = e;
  41808. tD = c;
  41809. }
  41810. else {
  41811. sN = (b * e - c * d);
  41812. tN = (a * e - b * d);
  41813. if (sN < 0.0) {
  41814. sN = 0.0;
  41815. tN = e;
  41816. tD = c;
  41817. }
  41818. else if (sN > sD) {
  41819. sN = sD;
  41820. tN = e + b;
  41821. tD = c;
  41822. }
  41823. }
  41824. if (tN < 0.0) {
  41825. tN = 0.0;
  41826. // recompute sc for this edge
  41827. if (-d < 0.0) {
  41828. sN = 0.0;
  41829. }
  41830. else if (-d > a)
  41831. sN = sD;
  41832. else {
  41833. sN = -d;
  41834. sD = a;
  41835. }
  41836. }
  41837. else if (tN > tD) {
  41838. tN = tD;
  41839. // recompute sc for this edge
  41840. if ((-d + b) < 0.0) {
  41841. sN = 0;
  41842. }
  41843. else if ((-d + b) > a) {
  41844. sN = sD;
  41845. }
  41846. else {
  41847. sN = (-d + b);
  41848. sD = a;
  41849. }
  41850. }
  41851. // finally do the division to get sc and tc
  41852. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  41853. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  41854. // get the difference of the two closest points
  41855. var qtc = v.multiplyByFloats(tc, tc, tc);
  41856. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  41857. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  41858. if (isIntersected) {
  41859. return qtc.length();
  41860. }
  41861. return -1;
  41862. };
  41863. // Statics
  41864. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  41865. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  41866. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  41867. var direction = end.subtract(start);
  41868. direction.normalize();
  41869. return new Ray(start, direction);
  41870. };
  41871. /**
  41872. * 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
  41873. * transformed to the given world matrix.
  41874. * @param origin The origin point
  41875. * @param end The end point
  41876. * @param world a matrix to transform the ray to. Default is the identity matrix.
  41877. */
  41878. Ray.CreateNewFromTo = function (origin, end, world) {
  41879. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  41880. var direction = end.subtract(origin);
  41881. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  41882. direction.normalize();
  41883. return Ray.Transform(new Ray(origin, direction, length), world);
  41884. };
  41885. Ray.Transform = function (ray, matrix) {
  41886. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  41887. Ray.TransformToRef(ray, matrix, result);
  41888. return result;
  41889. };
  41890. Ray.TransformToRef = function (ray, matrix, result) {
  41891. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  41892. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  41893. result.length = ray.length;
  41894. var dir = result.direction;
  41895. var len = dir.length();
  41896. if (!(len === 0 || len === 1)) {
  41897. var num = 1.0 / len;
  41898. dir.x *= num;
  41899. dir.y *= num;
  41900. dir.z *= num;
  41901. result.length *= len;
  41902. }
  41903. };
  41904. Ray.smallnum = 0.00000001;
  41905. Ray.rayl = 10e8;
  41906. return Ray;
  41907. }());
  41908. BABYLON.Ray = Ray;
  41909. })(BABYLON || (BABYLON = {}));
  41910. //# sourceMappingURL=babylon.ray.js.map
  41911. var BABYLON;
  41912. (function (BABYLON) {
  41913. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  41914. if (boxMin.x > sphereCenter.x + sphereRadius)
  41915. return false;
  41916. if (sphereCenter.x - sphereRadius > boxMax.x)
  41917. return false;
  41918. if (boxMin.y > sphereCenter.y + sphereRadius)
  41919. return false;
  41920. if (sphereCenter.y - sphereRadius > boxMax.y)
  41921. return false;
  41922. if (boxMin.z > sphereCenter.z + sphereRadius)
  41923. return false;
  41924. if (sphereCenter.z - sphereRadius > boxMax.z)
  41925. return false;
  41926. return true;
  41927. };
  41928. var getLowestRoot = (function () {
  41929. var result = { root: 0, found: false };
  41930. return function (a, b, c, maxR) {
  41931. result.root = 0;
  41932. result.found = false;
  41933. var determinant = b * b - 4.0 * a * c;
  41934. if (determinant < 0)
  41935. return result;
  41936. var sqrtD = Math.sqrt(determinant);
  41937. var r1 = (-b - sqrtD) / (2.0 * a);
  41938. var r2 = (-b + sqrtD) / (2.0 * a);
  41939. if (r1 > r2) {
  41940. var temp = r2;
  41941. r2 = r1;
  41942. r1 = temp;
  41943. }
  41944. if (r1 > 0 && r1 < maxR) {
  41945. result.root = r1;
  41946. result.found = true;
  41947. return result;
  41948. }
  41949. if (r2 > 0 && r2 < maxR) {
  41950. result.root = r2;
  41951. result.found = true;
  41952. return result;
  41953. }
  41954. return result;
  41955. };
  41956. })();
  41957. var Collider = (function () {
  41958. function Collider() {
  41959. this.radius = BABYLON.Vector3.One();
  41960. this.retry = 0;
  41961. this.basePointWorld = BABYLON.Vector3.Zero();
  41962. this.velocityWorld = BABYLON.Vector3.Zero();
  41963. this.normalizedVelocity = BABYLON.Vector3.Zero();
  41964. this._collisionPoint = BABYLON.Vector3.Zero();
  41965. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  41966. this._tempVector = BABYLON.Vector3.Zero();
  41967. this._tempVector2 = BABYLON.Vector3.Zero();
  41968. this._tempVector3 = BABYLON.Vector3.Zero();
  41969. this._tempVector4 = BABYLON.Vector3.Zero();
  41970. this._edge = BABYLON.Vector3.Zero();
  41971. this._baseToVertex = BABYLON.Vector3.Zero();
  41972. this._destinationPoint = BABYLON.Vector3.Zero();
  41973. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  41974. this._displacementVector = BABYLON.Vector3.Zero();
  41975. this._collisionMask = -1;
  41976. }
  41977. Object.defineProperty(Collider.prototype, "collisionMask", {
  41978. get: function () {
  41979. return this._collisionMask;
  41980. },
  41981. set: function (mask) {
  41982. this._collisionMask = !isNaN(mask) ? mask : -1;
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. // Methods
  41988. Collider.prototype._initialize = function (source, dir, e) {
  41989. this.velocity = dir;
  41990. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  41991. this.basePoint = source;
  41992. source.multiplyToRef(this.radius, this.basePointWorld);
  41993. dir.multiplyToRef(this.radius, this.velocityWorld);
  41994. this.velocityWorldLength = this.velocityWorld.length();
  41995. this.epsilon = e;
  41996. this.collisionFound = false;
  41997. };
  41998. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  41999. pa.subtractToRef(point, this._tempVector);
  42000. pb.subtractToRef(point, this._tempVector2);
  42001. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  42002. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42003. if (d < 0)
  42004. return false;
  42005. pc.subtractToRef(point, this._tempVector3);
  42006. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  42007. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42008. if (d < 0)
  42009. return false;
  42010. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  42011. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  42012. return d >= 0;
  42013. };
  42014. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  42015. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  42016. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  42017. if (distance > this.velocityWorldLength + max + sphereRadius) {
  42018. return false;
  42019. }
  42020. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  42021. return false;
  42022. return true;
  42023. };
  42024. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  42025. var t0;
  42026. var embeddedInPlane = false;
  42027. //defensive programming, actually not needed.
  42028. if (!trianglePlaneArray) {
  42029. trianglePlaneArray = [];
  42030. }
  42031. if (!trianglePlaneArray[faceIndex]) {
  42032. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  42033. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  42034. }
  42035. var trianglePlane = trianglePlaneArray[faceIndex];
  42036. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  42037. return;
  42038. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  42039. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  42040. if (normalDotVelocity == 0) {
  42041. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  42042. return;
  42043. embeddedInPlane = true;
  42044. t0 = 0;
  42045. }
  42046. else {
  42047. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42048. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42049. if (t0 > t1) {
  42050. var temp = t1;
  42051. t1 = t0;
  42052. t0 = temp;
  42053. }
  42054. if (t0 > 1.0 || t1 < 0.0)
  42055. return;
  42056. if (t0 < 0)
  42057. t0 = 0;
  42058. if (t0 > 1.0)
  42059. t0 = 1.0;
  42060. }
  42061. this._collisionPoint.copyFromFloats(0, 0, 0);
  42062. var found = false;
  42063. var t = 1.0;
  42064. if (!embeddedInPlane) {
  42065. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  42066. this.velocity.scaleToRef(t0, this._tempVector);
  42067. this._planeIntersectionPoint.addInPlace(this._tempVector);
  42068. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  42069. found = true;
  42070. t = t0;
  42071. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  42072. }
  42073. }
  42074. if (!found) {
  42075. var velocitySquaredLength = this.velocity.lengthSquared();
  42076. var a = velocitySquaredLength;
  42077. this.basePoint.subtractToRef(p1, this._tempVector);
  42078. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42079. var c = this._tempVector.lengthSquared() - 1.0;
  42080. var lowestRoot = getLowestRoot(a, b, c, t);
  42081. if (lowestRoot.found) {
  42082. t = lowestRoot.root;
  42083. found = true;
  42084. this._collisionPoint.copyFrom(p1);
  42085. }
  42086. this.basePoint.subtractToRef(p2, this._tempVector);
  42087. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42088. c = this._tempVector.lengthSquared() - 1.0;
  42089. lowestRoot = getLowestRoot(a, b, c, t);
  42090. if (lowestRoot.found) {
  42091. t = lowestRoot.root;
  42092. found = true;
  42093. this._collisionPoint.copyFrom(p2);
  42094. }
  42095. this.basePoint.subtractToRef(p3, this._tempVector);
  42096. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42097. c = this._tempVector.lengthSquared() - 1.0;
  42098. lowestRoot = getLowestRoot(a, b, c, t);
  42099. if (lowestRoot.found) {
  42100. t = lowestRoot.root;
  42101. found = true;
  42102. this._collisionPoint.copyFrom(p3);
  42103. }
  42104. p2.subtractToRef(p1, this._edge);
  42105. p1.subtractToRef(this.basePoint, this._baseToVertex);
  42106. var edgeSquaredLength = this._edge.lengthSquared();
  42107. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42108. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42109. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42110. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42111. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42112. lowestRoot = getLowestRoot(a, b, c, t);
  42113. if (lowestRoot.found) {
  42114. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42115. if (f >= 0.0 && f <= 1.0) {
  42116. t = lowestRoot.root;
  42117. found = true;
  42118. this._edge.scaleInPlace(f);
  42119. p1.addToRef(this._edge, this._collisionPoint);
  42120. }
  42121. }
  42122. p3.subtractToRef(p2, this._edge);
  42123. p2.subtractToRef(this.basePoint, this._baseToVertex);
  42124. edgeSquaredLength = this._edge.lengthSquared();
  42125. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42126. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42127. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42128. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42129. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42130. lowestRoot = getLowestRoot(a, b, c, t);
  42131. if (lowestRoot.found) {
  42132. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42133. if (f >= 0.0 && f <= 1.0) {
  42134. t = lowestRoot.root;
  42135. found = true;
  42136. this._edge.scaleInPlace(f);
  42137. p2.addToRef(this._edge, this._collisionPoint);
  42138. }
  42139. }
  42140. p1.subtractToRef(p3, this._edge);
  42141. p3.subtractToRef(this.basePoint, this._baseToVertex);
  42142. edgeSquaredLength = this._edge.lengthSquared();
  42143. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42144. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42145. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42146. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42147. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42148. lowestRoot = getLowestRoot(a, b, c, t);
  42149. if (lowestRoot.found) {
  42150. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42151. if (f >= 0.0 && f <= 1.0) {
  42152. t = lowestRoot.root;
  42153. found = true;
  42154. this._edge.scaleInPlace(f);
  42155. p3.addToRef(this._edge, this._collisionPoint);
  42156. }
  42157. }
  42158. }
  42159. if (found) {
  42160. var distToCollision = t * this.velocity.length();
  42161. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  42162. if (!this.intersectionPoint) {
  42163. this.intersectionPoint = this._collisionPoint.clone();
  42164. }
  42165. else {
  42166. this.intersectionPoint.copyFrom(this._collisionPoint);
  42167. }
  42168. this.nearestDistance = distToCollision;
  42169. this.collisionFound = true;
  42170. }
  42171. }
  42172. };
  42173. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  42174. for (var i = indexStart; i < indexEnd; i += 3) {
  42175. var p1 = pts[indices[i] - decal];
  42176. var p2 = pts[indices[i + 1] - decal];
  42177. var p3 = pts[indices[i + 2] - decal];
  42178. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  42179. }
  42180. };
  42181. Collider.prototype._getResponse = function (pos, vel) {
  42182. pos.addToRef(vel, this._destinationPoint);
  42183. vel.scaleInPlace((this.nearestDistance / vel.length()));
  42184. this.basePoint.addToRef(vel, pos);
  42185. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  42186. this._slidePlaneNormal.normalize();
  42187. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  42188. pos.addInPlace(this._displacementVector);
  42189. this.intersectionPoint.addInPlace(this._displacementVector);
  42190. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  42191. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  42192. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  42193. };
  42194. return Collider;
  42195. }());
  42196. BABYLON.Collider = Collider;
  42197. })(BABYLON || (BABYLON = {}));
  42198. //# sourceMappingURL=babylon.collider.js.map
  42199. var BABYLON;
  42200. (function (BABYLON) {
  42201. //WebWorker code will be inserted to this variable.
  42202. BABYLON.CollisionWorker = "";
  42203. var WorkerTaskType;
  42204. (function (WorkerTaskType) {
  42205. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  42206. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  42207. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  42208. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  42209. var WorkerReplyType;
  42210. (function (WorkerReplyType) {
  42211. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  42212. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  42213. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  42214. var CollisionCoordinatorWorker = (function () {
  42215. function CollisionCoordinatorWorker() {
  42216. var _this = this;
  42217. this._scaledPosition = BABYLON.Vector3.Zero();
  42218. this._scaledVelocity = BABYLON.Vector3.Zero();
  42219. this.onMeshUpdated = function (mesh) {
  42220. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  42221. };
  42222. this.onGeometryUpdated = function (geometry) {
  42223. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  42224. };
  42225. this._afterRender = function () {
  42226. if (!_this._init)
  42227. return;
  42228. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  42229. return;
  42230. }
  42231. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  42232. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  42233. if (_this._runningUpdated > 4) {
  42234. return;
  42235. }
  42236. ++_this._runningUpdated;
  42237. var payload = {
  42238. updatedMeshes: _this._addUpdateMeshesList,
  42239. updatedGeometries: _this._addUpdateGeometriesList,
  42240. removedGeometries: _this._toRemoveGeometryArray,
  42241. removedMeshes: _this._toRemoveMeshesArray
  42242. };
  42243. var message = {
  42244. payload: payload,
  42245. taskType: WorkerTaskType.UPDATE
  42246. };
  42247. var serializable = [];
  42248. for (var id in payload.updatedGeometries) {
  42249. if (payload.updatedGeometries.hasOwnProperty(id)) {
  42250. //prepare transferables
  42251. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  42252. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  42253. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  42254. }
  42255. }
  42256. _this._worker.postMessage(message, serializable);
  42257. _this._addUpdateMeshesList = {};
  42258. _this._addUpdateGeometriesList = {};
  42259. _this._toRemoveGeometryArray = [];
  42260. _this._toRemoveMeshesArray = [];
  42261. };
  42262. this._onMessageFromWorker = function (e) {
  42263. var returnData = e.data;
  42264. if (returnData.error != WorkerReplyType.SUCCESS) {
  42265. //TODO what errors can be returned from the worker?
  42266. BABYLON.Tools.Warn("error returned from worker!");
  42267. return;
  42268. }
  42269. switch (returnData.taskType) {
  42270. case WorkerTaskType.INIT:
  42271. _this._init = true;
  42272. //Update the worked with ALL of the scene's current state
  42273. _this._scene.meshes.forEach(function (mesh) {
  42274. _this.onMeshAdded(mesh);
  42275. });
  42276. _this._scene.getGeometries().forEach(function (geometry) {
  42277. _this.onGeometryAdded(geometry);
  42278. });
  42279. break;
  42280. case WorkerTaskType.UPDATE:
  42281. _this._runningUpdated--;
  42282. break;
  42283. case WorkerTaskType.COLLIDE:
  42284. _this._runningCollisionTask = false;
  42285. var returnPayload = returnData.payload;
  42286. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  42287. return;
  42288. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  42289. //cleanup
  42290. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  42291. break;
  42292. }
  42293. };
  42294. this._collisionsCallbackArray = [];
  42295. this._init = false;
  42296. this._runningUpdated = 0;
  42297. this._runningCollisionTask = false;
  42298. this._addUpdateMeshesList = {};
  42299. this._addUpdateGeometriesList = {};
  42300. this._toRemoveGeometryArray = [];
  42301. this._toRemoveMeshesArray = [];
  42302. }
  42303. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42304. if (!this._init)
  42305. return;
  42306. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  42307. return;
  42308. position.divideToRef(collider.radius, this._scaledPosition);
  42309. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42310. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  42311. var payload = {
  42312. collider: {
  42313. position: this._scaledPosition.asArray(),
  42314. velocity: this._scaledVelocity.asArray(),
  42315. radius: collider.radius.asArray()
  42316. },
  42317. collisionId: collisionIndex,
  42318. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  42319. maximumRetry: maximumRetry
  42320. };
  42321. var message = {
  42322. payload: payload,
  42323. taskType: WorkerTaskType.COLLIDE
  42324. };
  42325. this._worker.postMessage(message);
  42326. };
  42327. CollisionCoordinatorWorker.prototype.init = function (scene) {
  42328. this._scene = scene;
  42329. this._scene.registerAfterRender(this._afterRender);
  42330. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  42331. this._worker = new Worker(workerUrl);
  42332. this._worker.onmessage = this._onMessageFromWorker;
  42333. var message = {
  42334. payload: {},
  42335. taskType: WorkerTaskType.INIT
  42336. };
  42337. this._worker.postMessage(message);
  42338. };
  42339. CollisionCoordinatorWorker.prototype.destroy = function () {
  42340. this._scene.unregisterAfterRender(this._afterRender);
  42341. this._worker.terminate();
  42342. };
  42343. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  42344. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  42345. this.onMeshUpdated(mesh);
  42346. };
  42347. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  42348. this._toRemoveMeshesArray.push(mesh.uniqueId);
  42349. };
  42350. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  42351. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  42352. geometry.onGeometryUpdated = this.onGeometryUpdated;
  42353. this.onGeometryUpdated(geometry);
  42354. };
  42355. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  42356. this._toRemoveGeometryArray.push(geometry.id);
  42357. };
  42358. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  42359. var submeshes = [];
  42360. if (mesh.subMeshes) {
  42361. submeshes = mesh.subMeshes.map(function (sm, idx) {
  42362. return {
  42363. position: idx,
  42364. verticesStart: sm.verticesStart,
  42365. verticesCount: sm.verticesCount,
  42366. indexStart: sm.indexStart,
  42367. indexCount: sm.indexCount,
  42368. hasMaterial: !!sm.getMaterial(),
  42369. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42370. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  42371. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42372. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  42373. };
  42374. });
  42375. }
  42376. var geometryId = null;
  42377. if (mesh instanceof BABYLON.Mesh) {
  42378. geometryId = mesh.geometry ? mesh.geometry.id : null;
  42379. }
  42380. else if (mesh instanceof BABYLON.InstancedMesh) {
  42381. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  42382. }
  42383. return {
  42384. uniqueId: mesh.uniqueId,
  42385. id: mesh.id,
  42386. name: mesh.name,
  42387. geometryId: geometryId,
  42388. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42389. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  42390. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42391. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  42392. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  42393. subMeshes: submeshes,
  42394. checkCollisions: mesh.checkCollisions
  42395. };
  42396. };
  42397. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  42398. return {
  42399. id: geometry.id,
  42400. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  42401. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  42402. indices: new Uint32Array(geometry.getIndices() || []),
  42403. };
  42404. };
  42405. return CollisionCoordinatorWorker;
  42406. }());
  42407. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  42408. var CollisionCoordinatorLegacy = (function () {
  42409. function CollisionCoordinatorLegacy() {
  42410. this._scaledPosition = BABYLON.Vector3.Zero();
  42411. this._scaledVelocity = BABYLON.Vector3.Zero();
  42412. this._finalPosition = BABYLON.Vector3.Zero();
  42413. }
  42414. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42415. position.divideToRef(collider.radius, this._scaledPosition);
  42416. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42417. collider.collidedMesh = null;
  42418. collider.retry = 0;
  42419. collider.initialVelocity = this._scaledVelocity;
  42420. collider.initialPosition = this._scaledPosition;
  42421. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  42422. this._finalPosition.multiplyInPlace(collider.radius);
  42423. //run the callback
  42424. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  42425. };
  42426. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  42427. this._scene = scene;
  42428. };
  42429. CollisionCoordinatorLegacy.prototype.destroy = function () {
  42430. //Legacy need no destruction method.
  42431. };
  42432. //No update in legacy mode
  42433. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  42434. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  42435. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  42436. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  42437. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  42438. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  42439. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  42440. if (excludedMesh === void 0) { excludedMesh = null; }
  42441. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  42442. if (collider.retry >= maximumRetry) {
  42443. finalPosition.copyFrom(position);
  42444. return;
  42445. }
  42446. // Check if this is a mesh else camera or -1
  42447. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  42448. collider._initialize(position, velocity, closeDistance);
  42449. // Check all meshes
  42450. for (var index = 0; index < this._scene.meshes.length; index++) {
  42451. var mesh = this._scene.meshes[index];
  42452. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  42453. mesh._checkCollision(collider);
  42454. }
  42455. }
  42456. if (!collider.collisionFound) {
  42457. position.addToRef(velocity, finalPosition);
  42458. return;
  42459. }
  42460. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  42461. collider._getResponse(position, velocity);
  42462. }
  42463. if (velocity.length() <= closeDistance) {
  42464. finalPosition.copyFrom(position);
  42465. return;
  42466. }
  42467. collider.retry++;
  42468. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  42469. };
  42470. return CollisionCoordinatorLegacy;
  42471. }());
  42472. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  42473. })(BABYLON || (BABYLON = {}));
  42474. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  42475. var BABYLON;
  42476. (function (BABYLON) {
  42477. var Particle = (function () {
  42478. function Particle(particleSystem) {
  42479. this.particleSystem = particleSystem;
  42480. this.position = BABYLON.Vector3.Zero();
  42481. this.direction = BABYLON.Vector3.Zero();
  42482. this.color = new BABYLON.Color4(0, 0, 0, 0);
  42483. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  42484. this.lifeTime = 1.0;
  42485. this.age = 0;
  42486. this.size = 0;
  42487. this.angle = 0;
  42488. this.angularSpeed = 0;
  42489. this._currentFrameCounter = 0;
  42490. this.cellIndex = 0;
  42491. if (!this.particleSystem.isAnimationSheetEnabled) {
  42492. return;
  42493. }
  42494. this.cellIndex = this.particleSystem.startSpriteCellID;
  42495. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  42496. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  42497. }
  42498. else {
  42499. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  42500. }
  42501. }
  42502. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  42503. // (ageOffset / scaledUpdateSpeed) / available cells
  42504. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  42505. this._currentFrameCounter += scaledUpdateSpeed;
  42506. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  42507. this._currentFrameCounter = 0;
  42508. this.cellIndex++;
  42509. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42510. this.cellIndex = this.particleSystem.endSpriteCellID;
  42511. }
  42512. }
  42513. };
  42514. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  42515. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  42516. this.cellIndex++;
  42517. this._currentFrameCounter = 0;
  42518. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42519. if (this.particleSystem.spriteCellLoop) {
  42520. this.cellIndex = this.particleSystem.startSpriteCellID;
  42521. }
  42522. else {
  42523. this.cellIndex = this.particleSystem.endSpriteCellID;
  42524. }
  42525. }
  42526. }
  42527. else {
  42528. this._currentFrameCounter++;
  42529. }
  42530. };
  42531. Particle.prototype.copyTo = function (other) {
  42532. other.position.copyFrom(this.position);
  42533. other.direction.copyFrom(this.direction);
  42534. other.color.copyFrom(this.color);
  42535. other.colorStep.copyFrom(this.colorStep);
  42536. other.lifeTime = this.lifeTime;
  42537. other.age = this.age;
  42538. other.size = this.size;
  42539. other.angle = this.angle;
  42540. other.angularSpeed = this.angularSpeed;
  42541. other.particleSystem = this.particleSystem;
  42542. other.cellIndex = this.cellIndex;
  42543. };
  42544. return Particle;
  42545. }());
  42546. BABYLON.Particle = Particle;
  42547. })(BABYLON || (BABYLON = {}));
  42548. //# sourceMappingURL=babylon.particle.js.map
  42549. var BABYLON;
  42550. (function (BABYLON) {
  42551. var randomNumber = function (min, max) {
  42552. if (min === max) {
  42553. return (min);
  42554. }
  42555. var random = Math.random();
  42556. return ((random * (max - min)) + min);
  42557. };
  42558. var ParticleSystem = (function () {
  42559. // end of sheet animation
  42560. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  42561. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  42562. if (epsilon === void 0) { epsilon = 0.01; }
  42563. var _this = this;
  42564. this.name = name;
  42565. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  42566. // Members
  42567. this.animations = [];
  42568. this.renderingGroupId = 0;
  42569. this.emitter = null;
  42570. this.emitRate = 10;
  42571. this.manualEmitCount = -1;
  42572. this.updateSpeed = 0.01;
  42573. this.targetStopDuration = 0;
  42574. this.disposeOnStop = false;
  42575. this.minEmitPower = 1;
  42576. this.maxEmitPower = 1;
  42577. this.minLifeTime = 1;
  42578. this.maxLifeTime = 1;
  42579. this.minSize = 1;
  42580. this.maxSize = 1;
  42581. this.minAngularSpeed = 0;
  42582. this.maxAngularSpeed = 0;
  42583. this.layerMask = 0x0FFFFFFF;
  42584. this.customShader = null;
  42585. this.preventAutoStart = false;
  42586. /**
  42587. * An event triggered when the system is disposed.
  42588. * @type {BABYLON.Observable}
  42589. */
  42590. this.onDisposeObservable = new BABYLON.Observable();
  42591. this.onAnimationEnd = null;
  42592. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  42593. this.forceDepthWrite = false;
  42594. this.gravity = BABYLON.Vector3.Zero();
  42595. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  42596. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  42597. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  42598. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42599. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42600. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42601. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  42602. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42603. this.particles = new Array();
  42604. this._stockParticles = new Array();
  42605. this._newPartsExcess = 0;
  42606. this._vertexBuffers = {};
  42607. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  42608. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  42609. this._scaledDirection = BABYLON.Vector3.Zero();
  42610. this._scaledGravity = BABYLON.Vector3.Zero();
  42611. this._currentRenderId = -1;
  42612. this._started = false;
  42613. this._stopped = false;
  42614. this._actualFrame = 0;
  42615. // sheet animation
  42616. this.startSpriteCellID = 0;
  42617. this.endSpriteCellID = 0;
  42618. this.spriteCellLoop = true;
  42619. this.spriteCellChangeSpeed = 0;
  42620. this.spriteCellWidth = 0;
  42621. this.spriteCellHeight = 0;
  42622. this._vertexBufferSize = 11;
  42623. this.appendParticleVertexes = null;
  42624. this.id = name;
  42625. this._capacity = capacity;
  42626. this._epsilon = epsilon;
  42627. if (_isAnimationSheetEnabled) {
  42628. this._vertexBufferSize = 12;
  42629. }
  42630. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42631. this._customEffect = customEffect;
  42632. scene.particleSystems.push(this);
  42633. this._createIndexBuffer();
  42634. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  42635. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  42636. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  42637. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  42638. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  42639. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  42640. if (this._isAnimationSheetEnabled) {
  42641. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  42642. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  42643. }
  42644. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42645. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42646. this._vertexBuffers["options"] = options;
  42647. // Default behaviors
  42648. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  42649. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  42650. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  42651. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  42652. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  42653. };
  42654. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  42655. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  42656. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  42657. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  42658. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  42659. };
  42660. this.updateFunction = function (particles) {
  42661. for (var index = 0; index < particles.length; index++) {
  42662. var particle = particles[index];
  42663. particle.age += _this._scaledUpdateSpeed;
  42664. if (particle.age >= particle.lifeTime) {
  42665. _this.recycleParticle(particle);
  42666. index--;
  42667. continue;
  42668. }
  42669. else {
  42670. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  42671. particle.color.addInPlace(_this._scaledColorStep);
  42672. if (particle.color.a < 0)
  42673. particle.color.a = 0;
  42674. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  42675. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  42676. particle.position.addInPlace(_this._scaledDirection);
  42677. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  42678. particle.direction.addInPlace(_this._scaledGravity);
  42679. if (_this._isAnimationSheetEnabled) {
  42680. particle.updateCellIndex(_this._scaledUpdateSpeed);
  42681. }
  42682. }
  42683. }
  42684. };
  42685. }
  42686. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  42687. set: function (callback) {
  42688. if (this._onDisposeObserver) {
  42689. this.onDisposeObservable.remove(this._onDisposeObserver);
  42690. }
  42691. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42692. },
  42693. enumerable: true,
  42694. configurable: true
  42695. });
  42696. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  42697. get: function () {
  42698. return this._isAnimationSheetEnabled;
  42699. },
  42700. enumerable: true,
  42701. configurable: true
  42702. });
  42703. ParticleSystem.prototype._createIndexBuffer = function () {
  42704. var indices = [];
  42705. var index = 0;
  42706. for (var count = 0; count < this._capacity; count++) {
  42707. indices.push(index);
  42708. indices.push(index + 1);
  42709. indices.push(index + 2);
  42710. indices.push(index);
  42711. indices.push(index + 2);
  42712. indices.push(index + 3);
  42713. index += 4;
  42714. }
  42715. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  42716. };
  42717. ParticleSystem.prototype.recycleParticle = function (particle) {
  42718. var lastParticle = this.particles.pop();
  42719. if (lastParticle !== particle) {
  42720. lastParticle.copyTo(particle);
  42721. this._stockParticles.push(lastParticle);
  42722. }
  42723. };
  42724. ParticleSystem.prototype.getCapacity = function () {
  42725. return this._capacity;
  42726. };
  42727. ParticleSystem.prototype.isAlive = function () {
  42728. return this._alive;
  42729. };
  42730. ParticleSystem.prototype.isStarted = function () {
  42731. return this._started;
  42732. };
  42733. ParticleSystem.prototype.start = function () {
  42734. this._started = true;
  42735. this._stopped = false;
  42736. this._actualFrame = 0;
  42737. };
  42738. ParticleSystem.prototype.stop = function () {
  42739. this._stopped = true;
  42740. };
  42741. // animation sheet
  42742. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  42743. var offset = index * this._vertexBufferSize;
  42744. this._vertexData[offset] = particle.position.x;
  42745. this._vertexData[offset + 1] = particle.position.y;
  42746. this._vertexData[offset + 2] = particle.position.z;
  42747. this._vertexData[offset + 3] = particle.color.r;
  42748. this._vertexData[offset + 4] = particle.color.g;
  42749. this._vertexData[offset + 5] = particle.color.b;
  42750. this._vertexData[offset + 6] = particle.color.a;
  42751. this._vertexData[offset + 7] = particle.angle;
  42752. this._vertexData[offset + 8] = particle.size;
  42753. this._vertexData[offset + 9] = offsetX;
  42754. this._vertexData[offset + 10] = offsetY;
  42755. };
  42756. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  42757. if (offsetX === 0)
  42758. offsetX = this._epsilon;
  42759. else if (offsetX === 1)
  42760. offsetX = 1 - this._epsilon;
  42761. if (offsetY === 0)
  42762. offsetY = this._epsilon;
  42763. else if (offsetY === 1)
  42764. offsetY = 1 - this._epsilon;
  42765. var offset = index * this._vertexBufferSize;
  42766. this._vertexData[offset] = particle.position.x;
  42767. this._vertexData[offset + 1] = particle.position.y;
  42768. this._vertexData[offset + 2] = particle.position.z;
  42769. this._vertexData[offset + 3] = particle.color.r;
  42770. this._vertexData[offset + 4] = particle.color.g;
  42771. this._vertexData[offset + 5] = particle.color.b;
  42772. this._vertexData[offset + 6] = particle.color.a;
  42773. this._vertexData[offset + 7] = particle.angle;
  42774. this._vertexData[offset + 8] = particle.size;
  42775. this._vertexData[offset + 9] = offsetX;
  42776. this._vertexData[offset + 10] = offsetY;
  42777. this._vertexData[offset + 11] = particle.cellIndex;
  42778. };
  42779. ParticleSystem.prototype._update = function (newParticles) {
  42780. // Update current
  42781. this._alive = this.particles.length > 0;
  42782. this.updateFunction(this.particles);
  42783. // Add new ones
  42784. var worldMatrix;
  42785. if (this.emitter.position) {
  42786. var emitterMesh = this.emitter;
  42787. worldMatrix = emitterMesh.getWorldMatrix();
  42788. }
  42789. else {
  42790. var emitterPosition = this.emitter;
  42791. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  42792. }
  42793. var particle;
  42794. for (var index = 0; index < newParticles; index++) {
  42795. if (this.particles.length === this._capacity) {
  42796. break;
  42797. }
  42798. if (this._stockParticles.length !== 0) {
  42799. particle = this._stockParticles.pop();
  42800. particle.age = 0;
  42801. particle.cellIndex = this.startSpriteCellID;
  42802. }
  42803. else {
  42804. particle = new BABYLON.Particle(this);
  42805. }
  42806. this.particles.push(particle);
  42807. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  42808. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  42809. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  42810. particle.size = randomNumber(this.minSize, this.maxSize);
  42811. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  42812. this.startPositionFunction(worldMatrix, particle.position, particle);
  42813. var step = randomNumber(0, 1.0);
  42814. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  42815. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  42816. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  42817. }
  42818. };
  42819. ParticleSystem.prototype._getEffect = function () {
  42820. if (this._customEffect) {
  42821. return this._customEffect;
  42822. }
  42823. ;
  42824. var defines = [];
  42825. if (this._scene.clipPlane) {
  42826. defines.push("#define CLIPPLANE");
  42827. }
  42828. if (this._isAnimationSheetEnabled) {
  42829. defines.push("#define ANIMATESHEET");
  42830. }
  42831. // Effect
  42832. var join = defines.join("\n");
  42833. if (this._cachedDefines !== join) {
  42834. this._cachedDefines = join;
  42835. var attributesNamesOrOptions;
  42836. var effectCreationOption;
  42837. if (this._isAnimationSheetEnabled) {
  42838. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  42839. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  42840. }
  42841. else {
  42842. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  42843. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  42844. }
  42845. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  42846. }
  42847. return this._effect;
  42848. };
  42849. ParticleSystem.prototype.animate = function () {
  42850. if (!this._started)
  42851. return;
  42852. var effect = this._getEffect();
  42853. // Check
  42854. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  42855. return;
  42856. if (this._currentRenderId === this._scene.getRenderId()) {
  42857. return;
  42858. }
  42859. this._currentRenderId = this._scene.getRenderId();
  42860. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  42861. // determine the number of particles we need to create
  42862. var newParticles;
  42863. if (this.manualEmitCount > -1) {
  42864. newParticles = this.manualEmitCount;
  42865. this._newPartsExcess = 0;
  42866. this.manualEmitCount = 0;
  42867. }
  42868. else {
  42869. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  42870. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  42871. }
  42872. if (this._newPartsExcess > 1.0) {
  42873. newParticles += this._newPartsExcess >> 0;
  42874. this._newPartsExcess -= this._newPartsExcess >> 0;
  42875. }
  42876. this._alive = false;
  42877. if (!this._stopped) {
  42878. this._actualFrame += this._scaledUpdateSpeed;
  42879. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  42880. this.stop();
  42881. }
  42882. else {
  42883. newParticles = 0;
  42884. }
  42885. this._update(newParticles);
  42886. // Stopped?
  42887. if (this._stopped) {
  42888. if (!this._alive) {
  42889. this._started = false;
  42890. if (this.onAnimationEnd) {
  42891. this.onAnimationEnd();
  42892. }
  42893. if (this.disposeOnStop) {
  42894. this._scene._toBeDisposed.push(this);
  42895. }
  42896. }
  42897. }
  42898. // Animation sheet
  42899. if (this._isAnimationSheetEnabled) {
  42900. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  42901. }
  42902. else {
  42903. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  42904. }
  42905. // Update VBO
  42906. var offset = 0;
  42907. for (var index = 0; index < this.particles.length; index++) {
  42908. var particle = this.particles[index];
  42909. this.appendParticleVertexes(offset, particle);
  42910. offset += 4;
  42911. }
  42912. this._vertexBuffer.update(this._vertexData);
  42913. };
  42914. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  42915. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  42916. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  42917. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  42918. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  42919. };
  42920. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  42921. this._appendParticleVertex(offset++, particle, 0, 0);
  42922. this._appendParticleVertex(offset++, particle, 1, 0);
  42923. this._appendParticleVertex(offset++, particle, 1, 1);
  42924. this._appendParticleVertex(offset++, particle, 0, 1);
  42925. };
  42926. ParticleSystem.prototype.rebuild = function () {
  42927. this._createIndexBuffer();
  42928. this._vertexBuffer._rebuild();
  42929. };
  42930. ParticleSystem.prototype.render = function () {
  42931. var effect = this._getEffect();
  42932. // Check
  42933. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  42934. return 0;
  42935. var engine = this._scene.getEngine();
  42936. // Render
  42937. engine.enableEffect(effect);
  42938. engine.setState(false);
  42939. var viewMatrix = this._scene.getViewMatrix();
  42940. effect.setTexture("diffuseSampler", this.particleTexture);
  42941. effect.setMatrix("view", viewMatrix);
  42942. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42943. if (this._isAnimationSheetEnabled) {
  42944. var baseSize = this.particleTexture.getBaseSize();
  42945. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  42946. }
  42947. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  42948. if (this._scene.clipPlane) {
  42949. var clipPlane = this._scene.clipPlane;
  42950. var invView = viewMatrix.clone();
  42951. invView.invert();
  42952. effect.setMatrix("invView", invView);
  42953. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42954. }
  42955. // VBOs
  42956. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42957. // Draw order
  42958. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  42959. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  42960. }
  42961. else {
  42962. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42963. }
  42964. if (this.forceDepthWrite) {
  42965. engine.setDepthWrite(true);
  42966. }
  42967. engine.draw(true, 0, this.particles.length * 6);
  42968. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42969. return this.particles.length;
  42970. };
  42971. ParticleSystem.prototype.dispose = function () {
  42972. if (this._vertexBuffer) {
  42973. this._vertexBuffer.dispose();
  42974. this._vertexBuffer = null;
  42975. }
  42976. if (this._indexBuffer) {
  42977. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42978. this._indexBuffer = null;
  42979. }
  42980. if (this.particleTexture) {
  42981. this.particleTexture.dispose();
  42982. this.particleTexture = null;
  42983. }
  42984. // Remove from scene
  42985. var index = this._scene.particleSystems.indexOf(this);
  42986. if (index > -1) {
  42987. this._scene.particleSystems.splice(index, 1);
  42988. }
  42989. // Callback
  42990. this.onDisposeObservable.notifyObservers(this);
  42991. this.onDisposeObservable.clear();
  42992. };
  42993. // Clone
  42994. ParticleSystem.prototype.clone = function (name, newEmitter) {
  42995. var custom = null;
  42996. var program = null;
  42997. if (this.customShader != null) {
  42998. program = this.customShader;
  42999. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43000. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43001. }
  43002. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  43003. result.customShader = program;
  43004. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  43005. if (newEmitter === undefined) {
  43006. newEmitter = this.emitter;
  43007. }
  43008. result.emitter = newEmitter;
  43009. if (this.particleTexture) {
  43010. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  43011. }
  43012. if (!this.preventAutoStart) {
  43013. result.start();
  43014. }
  43015. return result;
  43016. };
  43017. ParticleSystem.prototype.serialize = function () {
  43018. var serializationObject = {};
  43019. serializationObject.name = this.name;
  43020. serializationObject.id = this.id;
  43021. // Emitter
  43022. if (this.emitter.position) {
  43023. var emitterMesh = this.emitter;
  43024. serializationObject.emitterId = emitterMesh.id;
  43025. }
  43026. else {
  43027. var emitterPosition = this.emitter;
  43028. serializationObject.emitter = emitterPosition.asArray();
  43029. }
  43030. serializationObject.capacity = this.getCapacity();
  43031. if (this.particleTexture) {
  43032. serializationObject.textureName = this.particleTexture.name;
  43033. }
  43034. // Animations
  43035. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  43036. // Particle system
  43037. serializationObject.minAngularSpeed = this.minAngularSpeed;
  43038. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  43039. serializationObject.minSize = this.minSize;
  43040. serializationObject.maxSize = this.maxSize;
  43041. serializationObject.minEmitPower = this.minEmitPower;
  43042. serializationObject.maxEmitPower = this.maxEmitPower;
  43043. serializationObject.minLifeTime = this.minLifeTime;
  43044. serializationObject.maxLifeTime = this.maxLifeTime;
  43045. serializationObject.emitRate = this.emitRate;
  43046. serializationObject.minEmitBox = this.minEmitBox.asArray();
  43047. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  43048. serializationObject.gravity = this.gravity.asArray();
  43049. serializationObject.direction1 = this.direction1.asArray();
  43050. serializationObject.direction2 = this.direction2.asArray();
  43051. serializationObject.color1 = this.color1.asArray();
  43052. serializationObject.color2 = this.color2.asArray();
  43053. serializationObject.colorDead = this.colorDead.asArray();
  43054. serializationObject.updateSpeed = this.updateSpeed;
  43055. serializationObject.targetStopDuration = this.targetStopDuration;
  43056. serializationObject.textureMask = this.textureMask.asArray();
  43057. serializationObject.blendMode = this.blendMode;
  43058. serializationObject.customShader = this.customShader;
  43059. serializationObject.preventAutoStart = this.preventAutoStart;
  43060. return serializationObject;
  43061. };
  43062. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  43063. var name = parsedParticleSystem.name;
  43064. var custom = null;
  43065. var program = null;
  43066. if (parsedParticleSystem.customShader) {
  43067. program = parsedParticleSystem.customShader;
  43068. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43069. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43070. }
  43071. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  43072. particleSystem.customShader = program;
  43073. if (parsedParticleSystem.id) {
  43074. particleSystem.id = parsedParticleSystem.id;
  43075. }
  43076. // Auto start
  43077. if (parsedParticleSystem.preventAutoStart) {
  43078. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  43079. }
  43080. // Texture
  43081. if (parsedParticleSystem.textureName) {
  43082. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  43083. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  43084. }
  43085. // Emitter
  43086. if (parsedParticleSystem.emitterId) {
  43087. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  43088. }
  43089. else {
  43090. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  43091. }
  43092. // Animations
  43093. if (parsedParticleSystem.animations) {
  43094. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  43095. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  43096. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43097. }
  43098. }
  43099. if (parsedParticleSystem.autoAnimate) {
  43100. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  43101. }
  43102. // Particle system
  43103. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  43104. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  43105. particleSystem.minSize = parsedParticleSystem.minSize;
  43106. particleSystem.maxSize = parsedParticleSystem.maxSize;
  43107. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  43108. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  43109. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  43110. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  43111. particleSystem.emitRate = parsedParticleSystem.emitRate;
  43112. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  43113. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  43114. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  43115. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  43116. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  43117. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  43118. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  43119. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  43120. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  43121. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  43122. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  43123. particleSystem.blendMode = parsedParticleSystem.blendMode;
  43124. if (!particleSystem.preventAutoStart) {
  43125. particleSystem.start();
  43126. }
  43127. return particleSystem;
  43128. };
  43129. // Statics
  43130. ParticleSystem.BLENDMODE_ONEONE = 0;
  43131. ParticleSystem.BLENDMODE_STANDARD = 1;
  43132. return ParticleSystem;
  43133. }());
  43134. BABYLON.ParticleSystem = ParticleSystem;
  43135. })(BABYLON || (BABYLON = {}));
  43136. //# sourceMappingURL=babylon.particleSystem.js.map
  43137. var BABYLON;
  43138. (function (BABYLON) {
  43139. var SolidParticle = (function () {
  43140. /**
  43141. * Creates a Solid Particle object.
  43142. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  43143. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  43144. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  43145. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  43146. * `shapeId` (integer) is the model shape identifier in the SPS.
  43147. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  43148. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  43149. */
  43150. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  43151. this.idx = 0; // particle global index
  43152. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  43153. this.position = BABYLON.Vector3.Zero(); // position
  43154. this.rotation = BABYLON.Vector3.Zero(); // rotation
  43155. this.scaling = BABYLON.Vector3.One(); // scaling
  43156. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  43157. this.velocity = BABYLON.Vector3.Zero(); // velocity
  43158. this.alive = true; // alive
  43159. this.isVisible = true; // visibility
  43160. this._pos = 0; // index of this particle in the global "positions" array
  43161. this.shapeId = 0; // model shape id
  43162. this.idxInShape = 0; // index of the particle in its shape id
  43163. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  43164. this.idx = particleIndex;
  43165. this._pos = positionIndex;
  43166. this._model = model;
  43167. this.shapeId = shapeId;
  43168. this.idxInShape = idxInShape;
  43169. this._sps = sps;
  43170. if (modelBoundingInfo) {
  43171. this._modelBoundingInfo = modelBoundingInfo;
  43172. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  43173. }
  43174. }
  43175. Object.defineProperty(SolidParticle.prototype, "scale", {
  43176. /**
  43177. * legacy support, changed scale to scaling
  43178. */
  43179. get: function () {
  43180. return this.scaling;
  43181. },
  43182. set: function (scale) {
  43183. this.scaling = scale;
  43184. },
  43185. enumerable: true,
  43186. configurable: true
  43187. });
  43188. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  43189. /**
  43190. * legacy support, changed quaternion to rotationQuaternion
  43191. */
  43192. get: function () {
  43193. return this.rotationQuaternion;
  43194. },
  43195. set: function (q) {
  43196. this.rotationQuaternion = q;
  43197. },
  43198. enumerable: true,
  43199. configurable: true
  43200. });
  43201. /**
  43202. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  43203. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  43204. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  43205. */
  43206. SolidParticle.prototype.intersectsMesh = function (target) {
  43207. if (!this._boundingInfo || !target._boundingInfo) {
  43208. return false;
  43209. }
  43210. if (this._sps._bSphereOnly) {
  43211. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  43212. }
  43213. return this._boundingInfo.intersects(target._boundingInfo, false);
  43214. };
  43215. return SolidParticle;
  43216. }());
  43217. BABYLON.SolidParticle = SolidParticle;
  43218. var ModelShape = (function () {
  43219. /**
  43220. * 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.
  43221. * SPS internal tool, don't use it manually.
  43222. */
  43223. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  43224. this.shapeID = id;
  43225. this._shape = shape;
  43226. this._shapeUV = shapeUV;
  43227. this._positionFunction = posFunction;
  43228. this._vertexFunction = vtxFunction;
  43229. }
  43230. return ModelShape;
  43231. }());
  43232. BABYLON.ModelShape = ModelShape;
  43233. })(BABYLON || (BABYLON = {}));
  43234. //# sourceMappingURL=babylon.solidParticle.js.map
  43235. var BABYLON;
  43236. (function (BABYLON) {
  43237. /**
  43238. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  43239. */
  43240. var SolidParticleSystem = (function () {
  43241. /**
  43242. * Creates a SPS (Solid Particle System) object.
  43243. * `name` (String) is the SPS name, this will be the underlying mesh name.
  43244. * `scene` (Scene) is the scene in which the SPS is added.
  43245. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  43246. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  43247. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  43248. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  43249. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  43250. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  43251. */
  43252. function SolidParticleSystem(name, scene, options) {
  43253. // public members
  43254. /**
  43255. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  43256. * Example : var p = SPS.particles[i];
  43257. */
  43258. this.particles = new Array();
  43259. /**
  43260. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  43261. */
  43262. this.nbParticles = 0;
  43263. /**
  43264. * If the particles must ever face the camera (default false). Useful for planar particles.
  43265. */
  43266. this.billboard = false;
  43267. /**
  43268. * Recompute normals when adding a shape
  43269. */
  43270. this.recomputeNormals = true;
  43271. /**
  43272. * This a counter ofr your own usage. It's not set by any SPS functions.
  43273. */
  43274. this.counter = 0;
  43275. /**
  43276. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  43277. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  43278. */
  43279. this.vars = {};
  43280. this._positions = new Array();
  43281. this._indices = new Array();
  43282. this._normals = new Array();
  43283. this._colors = new Array();
  43284. this._uvs = new Array();
  43285. this._index = 0; // indices index
  43286. this._updatable = true;
  43287. this._pickable = false;
  43288. this._isVisibilityBoxLocked = false;
  43289. this._alwaysVisible = false;
  43290. this._shapeCounter = 0;
  43291. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  43292. this._color = new BABYLON.Color4(0, 0, 0, 0);
  43293. this._computeParticleColor = true;
  43294. this._computeParticleTexture = true;
  43295. this._computeParticleRotation = true;
  43296. this._computeParticleVertex = false;
  43297. this._computeBoundingBox = false;
  43298. this._cam_axisZ = BABYLON.Vector3.Zero();
  43299. this._cam_axisY = BABYLON.Vector3.Zero();
  43300. this._cam_axisX = BABYLON.Vector3.Zero();
  43301. this._axisX = BABYLON.Axis.X;
  43302. this._axisY = BABYLON.Axis.Y;
  43303. this._axisZ = BABYLON.Axis.Z;
  43304. this._camDir = BABYLON.Vector3.Zero();
  43305. this._rotMatrix = new BABYLON.Matrix();
  43306. this._invertMatrix = new BABYLON.Matrix();
  43307. this._rotated = BABYLON.Vector3.Zero();
  43308. this._quaternion = new BABYLON.Quaternion();
  43309. this._vertex = BABYLON.Vector3.Zero();
  43310. this._normal = BABYLON.Vector3.Zero();
  43311. this._yaw = 0.0;
  43312. this._pitch = 0.0;
  43313. this._roll = 0.0;
  43314. this._halfroll = 0.0;
  43315. this._halfpitch = 0.0;
  43316. this._halfyaw = 0.0;
  43317. this._sinRoll = 0.0;
  43318. this._cosRoll = 0.0;
  43319. this._sinPitch = 0.0;
  43320. this._cosPitch = 0.0;
  43321. this._sinYaw = 0.0;
  43322. this._cosYaw = 0.0;
  43323. this._mustUnrotateFixedNormals = false;
  43324. this._minimum = BABYLON.Tmp.Vector3[0];
  43325. this._maximum = BABYLON.Tmp.Vector3[1];
  43326. this._scale = BABYLON.Tmp.Vector3[2];
  43327. this._translation = BABYLON.Tmp.Vector3[3];
  43328. this._minBbox = BABYLON.Tmp.Vector3[4];
  43329. this._maxBbox = BABYLON.Tmp.Vector3[5];
  43330. this._particlesIntersect = false;
  43331. this._bSphereOnly = false;
  43332. this._bSphereRadiusFactor = 1.0;
  43333. this.name = name;
  43334. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43335. this._camera = scene.activeCamera;
  43336. this._pickable = options ? options.isPickable : false;
  43337. this._particlesIntersect = options ? options.particleIntersection : false;
  43338. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  43339. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  43340. if (options && options.updatable) {
  43341. this._updatable = options.updatable;
  43342. }
  43343. else {
  43344. this._updatable = true;
  43345. }
  43346. if (this._pickable) {
  43347. this.pickedParticles = [];
  43348. }
  43349. }
  43350. /**
  43351. * Builds the SPS underlying mesh. Returns a standard Mesh.
  43352. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  43353. */
  43354. SolidParticleSystem.prototype.buildMesh = function () {
  43355. if (this.nbParticles === 0) {
  43356. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  43357. this.addShape(triangle, 1);
  43358. triangle.dispose();
  43359. }
  43360. this._positions32 = new Float32Array(this._positions);
  43361. this._uvs32 = new Float32Array(this._uvs);
  43362. this._colors32 = new Float32Array(this._colors);
  43363. if (this.recomputeNormals) {
  43364. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  43365. }
  43366. this._normals32 = new Float32Array(this._normals);
  43367. this._fixedNormal32 = new Float32Array(this._normals);
  43368. if (this._mustUnrotateFixedNormals) {
  43369. this._unrotateFixedNormals();
  43370. }
  43371. var vertexData = new BABYLON.VertexData();
  43372. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  43373. vertexData.indices = this._indices;
  43374. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  43375. if (this._uvs32) {
  43376. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  43377. ;
  43378. }
  43379. if (this._colors32) {
  43380. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  43381. }
  43382. var mesh = new BABYLON.Mesh(this.name, this._scene);
  43383. vertexData.applyToMesh(mesh, this._updatable);
  43384. this.mesh = mesh;
  43385. this.mesh.isPickable = this._pickable;
  43386. // free memory
  43387. this._positions = null;
  43388. this._normals = null;
  43389. this._uvs = null;
  43390. this._colors = null;
  43391. if (!this._updatable) {
  43392. this.particles.length = 0;
  43393. }
  43394. return mesh;
  43395. };
  43396. /**
  43397. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  43398. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  43399. * Thus the particles generated from `digest()` have their property `position` set yet.
  43400. * `mesh` ( Mesh ) is the mesh to be digested
  43401. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  43402. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  43403. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  43404. */
  43405. SolidParticleSystem.prototype.digest = function (mesh, options) {
  43406. var size = (options && options.facetNb) || 1;
  43407. var number = (options && options.number);
  43408. var delta = (options && options.delta) || 0;
  43409. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43410. var meshInd = mesh.getIndices();
  43411. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43412. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43413. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43414. var f = 0; // facet counter
  43415. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  43416. // compute size from number
  43417. if (number) {
  43418. number = (number > totalFacets) ? totalFacets : number;
  43419. size = Math.round(totalFacets / number);
  43420. delta = 0;
  43421. }
  43422. else {
  43423. size = (size > totalFacets) ? totalFacets : size;
  43424. }
  43425. var facetPos = []; // submesh positions
  43426. var facetInd = []; // submesh indices
  43427. var facetUV = []; // submesh UV
  43428. var facetCol = []; // submesh colors
  43429. var barycenter = BABYLON.Tmp.Vector3[0];
  43430. var rand;
  43431. var sizeO = size;
  43432. while (f < totalFacets) {
  43433. size = sizeO + Math.floor((1 + delta) * Math.random());
  43434. if (f > totalFacets - size) {
  43435. size = totalFacets - f;
  43436. }
  43437. // reset temp arrays
  43438. facetPos.length = 0;
  43439. facetInd.length = 0;
  43440. facetUV.length = 0;
  43441. facetCol.length = 0;
  43442. // iterate over "size" facets
  43443. var fi = 0;
  43444. for (var j = f * 3; j < (f + size) * 3; j++) {
  43445. facetInd.push(fi);
  43446. var i = meshInd[j];
  43447. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  43448. if (meshUV) {
  43449. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  43450. }
  43451. if (meshCol) {
  43452. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  43453. }
  43454. fi++;
  43455. }
  43456. // create a model shape for each single particle
  43457. var idx = this.nbParticles;
  43458. var shape = this._posToShape(facetPos);
  43459. var shapeUV = this._uvsToShapeUV(facetUV);
  43460. // compute the barycenter of the shape
  43461. var v;
  43462. for (v = 0; v < shape.length; v++) {
  43463. barycenter.addInPlace(shape[v]);
  43464. }
  43465. barycenter.scaleInPlace(1 / shape.length);
  43466. // shift the shape from its barycenter to the origin
  43467. for (v = 0; v < shape.length; v++) {
  43468. shape[v].subtractInPlace(barycenter);
  43469. }
  43470. var bInfo;
  43471. if (this._particlesIntersect) {
  43472. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  43473. }
  43474. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  43475. // add the particle in the SPS
  43476. var currentPos = this._positions.length;
  43477. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  43478. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  43479. // initialize the particle position
  43480. this.particles[this.nbParticles].position.addInPlace(barycenter);
  43481. this._index += shape.length;
  43482. idx++;
  43483. this.nbParticles++;
  43484. this._shapeCounter++;
  43485. f += size;
  43486. }
  43487. return this;
  43488. };
  43489. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  43490. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  43491. var index = 0;
  43492. var idx = 0;
  43493. for (var p = 0; p < this.particles.length; p++) {
  43494. this._particle = this.particles[p];
  43495. this._shape = this._particle._model._shape;
  43496. if (this._particle.rotationQuaternion) {
  43497. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  43498. }
  43499. else {
  43500. this._yaw = this._particle.rotation.y;
  43501. this._pitch = this._particle.rotation.x;
  43502. this._roll = this._particle.rotation.z;
  43503. this._quaternionRotationYPR();
  43504. }
  43505. this._quaternionToRotationMatrix();
  43506. this._rotMatrix.invertToRef(this._invertMatrix);
  43507. for (var pt = 0; pt < this._shape.length; pt++) {
  43508. idx = index + pt * 3;
  43509. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  43510. this._fixedNormal32[idx] = this._normal.x;
  43511. this._fixedNormal32[idx + 1] = this._normal.y;
  43512. this._fixedNormal32[idx + 2] = this._normal.z;
  43513. }
  43514. index = idx + 3;
  43515. }
  43516. };
  43517. //reset copy
  43518. SolidParticleSystem.prototype._resetCopy = function () {
  43519. this._copy.position.x = 0;
  43520. this._copy.position.y = 0;
  43521. this._copy.position.z = 0;
  43522. this._copy.rotation.x = 0;
  43523. this._copy.rotation.y = 0;
  43524. this._copy.rotation.z = 0;
  43525. this._copy.rotationQuaternion = null;
  43526. this._copy.scaling.x = 1;
  43527. this._copy.scaling.y = 1;
  43528. this._copy.scaling.z = 1;
  43529. this._copy.uvs.x = 0;
  43530. this._copy.uvs.y = 0;
  43531. this._copy.uvs.z = 1;
  43532. this._copy.uvs.w = 1;
  43533. this._copy.color = null;
  43534. };
  43535. // _meshBuilder : inserts the shape model in the global SPS mesh
  43536. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  43537. var i;
  43538. var u = 0;
  43539. var c = 0;
  43540. var n = 0;
  43541. this._resetCopy();
  43542. if (options && options.positionFunction) {
  43543. options.positionFunction(this._copy, idx, idxInShape);
  43544. this._mustUnrotateFixedNormals = true;
  43545. }
  43546. if (this._copy.rotationQuaternion) {
  43547. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43548. }
  43549. else {
  43550. this._yaw = this._copy.rotation.y;
  43551. this._pitch = this._copy.rotation.x;
  43552. this._roll = this._copy.rotation.z;
  43553. this._quaternionRotationYPR();
  43554. }
  43555. this._quaternionToRotationMatrix();
  43556. for (i = 0; i < shape.length; i++) {
  43557. this._vertex.x = shape[i].x;
  43558. this._vertex.y = shape[i].y;
  43559. this._vertex.z = shape[i].z;
  43560. if (options && options.vertexFunction) {
  43561. options.vertexFunction(this._copy, this._vertex, i);
  43562. }
  43563. this._vertex.x *= this._copy.scaling.x;
  43564. this._vertex.y *= this._copy.scaling.y;
  43565. this._vertex.z *= this._copy.scaling.z;
  43566. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43567. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  43568. if (meshUV) {
  43569. 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);
  43570. u += 2;
  43571. }
  43572. if (this._copy.color) {
  43573. this._color = this._copy.color;
  43574. }
  43575. else if (meshCol && meshCol[c] !== undefined) {
  43576. this._color.r = meshCol[c];
  43577. this._color.g = meshCol[c + 1];
  43578. this._color.b = meshCol[c + 2];
  43579. this._color.a = meshCol[c + 3];
  43580. }
  43581. else {
  43582. this._color.r = 1;
  43583. this._color.g = 1;
  43584. this._color.b = 1;
  43585. this._color.a = 1;
  43586. }
  43587. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  43588. c += 4;
  43589. if (!this.recomputeNormals && meshNor) {
  43590. this._normal.x = meshNor[n];
  43591. this._normal.y = meshNor[n + 1];
  43592. this._normal.z = meshNor[n + 2];
  43593. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  43594. normals.push(this._normal.x, this._normal.y, this._normal.z);
  43595. n += 3;
  43596. }
  43597. }
  43598. for (i = 0; i < meshInd.length; i++) {
  43599. indices.push(p + meshInd[i]);
  43600. }
  43601. if (this._pickable) {
  43602. var nbfaces = meshInd.length / 3;
  43603. for (i = 0; i < nbfaces; i++) {
  43604. this.pickedParticles.push({ idx: idx, faceId: i });
  43605. }
  43606. }
  43607. return this._copy;
  43608. };
  43609. // returns a shape array from positions array
  43610. SolidParticleSystem.prototype._posToShape = function (positions) {
  43611. var shape = [];
  43612. for (var i = 0; i < positions.length; i += 3) {
  43613. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  43614. }
  43615. return shape;
  43616. };
  43617. // returns a shapeUV array from a Vector4 uvs
  43618. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  43619. var shapeUV = [];
  43620. if (uvs) {
  43621. for (var i = 0; i < uvs.length; i++)
  43622. shapeUV.push(uvs[i]);
  43623. }
  43624. return shapeUV;
  43625. };
  43626. // adds a new particle object in the particles array
  43627. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  43628. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  43629. this.particles.push(sp);
  43630. return sp;
  43631. };
  43632. /**
  43633. * Adds some particles to the SPS from the model shape. Returns the shape id.
  43634. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  43635. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  43636. * `nb` (positive integer) the number of particles to be created from this model
  43637. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  43638. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  43639. */
  43640. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  43641. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43642. var meshInd = mesh.getIndices();
  43643. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43644. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43645. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43646. var bbInfo;
  43647. if (this._particlesIntersect) {
  43648. bbInfo = mesh.getBoundingInfo();
  43649. }
  43650. var shape = this._posToShape(meshPos);
  43651. var shapeUV = this._uvsToShapeUV(meshUV);
  43652. var posfunc = options ? options.positionFunction : null;
  43653. var vtxfunc = options ? options.vertexFunction : null;
  43654. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  43655. // particles
  43656. var sp;
  43657. var currentCopy;
  43658. var idx = this.nbParticles;
  43659. for (var i = 0; i < nb; i++) {
  43660. var currentPos = this._positions.length;
  43661. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  43662. if (this._updatable) {
  43663. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  43664. sp.position.copyFrom(currentCopy.position);
  43665. sp.rotation.copyFrom(currentCopy.rotation);
  43666. if (currentCopy.rotationQuaternion) {
  43667. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  43668. }
  43669. if (currentCopy.color) {
  43670. sp.color.copyFrom(currentCopy.color);
  43671. }
  43672. sp.scaling.copyFrom(currentCopy.scaling);
  43673. sp.uvs.copyFrom(currentCopy.uvs);
  43674. }
  43675. this._index += shape.length;
  43676. idx++;
  43677. }
  43678. this.nbParticles += nb;
  43679. this._shapeCounter++;
  43680. return this._shapeCounter - 1;
  43681. };
  43682. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  43683. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  43684. this._resetCopy();
  43685. if (particle._model._positionFunction) {
  43686. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  43687. }
  43688. if (this._copy.rotationQuaternion) {
  43689. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43690. }
  43691. else {
  43692. this._yaw = this._copy.rotation.y;
  43693. this._pitch = this._copy.rotation.x;
  43694. this._roll = this._copy.rotation.z;
  43695. this._quaternionRotationYPR();
  43696. }
  43697. this._quaternionToRotationMatrix();
  43698. this._shape = particle._model._shape;
  43699. for (var pt = 0; pt < this._shape.length; pt++) {
  43700. this._vertex.x = this._shape[pt].x;
  43701. this._vertex.y = this._shape[pt].y;
  43702. this._vertex.z = this._shape[pt].z;
  43703. if (particle._model._vertexFunction) {
  43704. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  43705. }
  43706. this._vertex.x *= this._copy.scaling.x;
  43707. this._vertex.y *= this._copy.scaling.y;
  43708. this._vertex.z *= this._copy.scaling.z;
  43709. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43710. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  43711. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  43712. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  43713. }
  43714. particle.position.x = 0.0;
  43715. particle.position.y = 0.0;
  43716. particle.position.z = 0.0;
  43717. particle.rotation.x = 0.0;
  43718. particle.rotation.y = 0.0;
  43719. particle.rotation.z = 0.0;
  43720. particle.rotationQuaternion = null;
  43721. particle.scaling.x = 1.0;
  43722. particle.scaling.y = 1.0;
  43723. particle.scaling.z = 1.0;
  43724. };
  43725. /**
  43726. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  43727. * Returns the SPS.
  43728. */
  43729. SolidParticleSystem.prototype.rebuildMesh = function () {
  43730. for (var p = 0; p < this.particles.length; p++) {
  43731. this._rebuildParticle(this.particles[p]);
  43732. }
  43733. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43734. return this;
  43735. };
  43736. /**
  43737. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  43738. * This method calls `updateParticle()` for each particle of the SPS.
  43739. * For an animated SPS, it is usually called within the render loop.
  43740. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  43741. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  43742. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  43743. * Returns the SPS.
  43744. */
  43745. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  43746. if (start === void 0) { start = 0; }
  43747. if (end === void 0) { end = this.nbParticles - 1; }
  43748. if (update === void 0) { update = true; }
  43749. if (!this._updatable) {
  43750. return;
  43751. }
  43752. // custom beforeUpdate
  43753. this.beforeUpdateParticles(start, end, update);
  43754. this._cam_axisX.x = 1.0;
  43755. this._cam_axisX.y = 0.0;
  43756. this._cam_axisX.z = 0.0;
  43757. this._cam_axisY.x = 0.0;
  43758. this._cam_axisY.y = 1.0;
  43759. this._cam_axisY.z = 0.0;
  43760. this._cam_axisZ.x = 0.0;
  43761. this._cam_axisZ.y = 0.0;
  43762. this._cam_axisZ.z = 1.0;
  43763. // if the particles will always face the camera
  43764. if (this.billboard) {
  43765. this.mesh.computeWorldMatrix(true);
  43766. // compute the camera position and un-rotate it by the current mesh rotation
  43767. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  43768. this._quaternionToRotationMatrix();
  43769. this._rotMatrix.invertToRef(this._invertMatrix);
  43770. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  43771. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  43772. this._cam_axisZ.normalize();
  43773. // same for camera up vector extracted from the cam view matrix
  43774. var view = this._camera.getViewMatrix(true);
  43775. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  43776. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  43777. this._cam_axisY.normalize();
  43778. this._cam_axisX.normalize();
  43779. }
  43780. }
  43781. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  43782. var idx = 0; // current position index in the global array positions32
  43783. var index = 0; // position start index in the global array positions32 of the current particle
  43784. var colidx = 0; // current color index in the global array colors32
  43785. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  43786. var uvidx = 0; // current uv index in the global array uvs32
  43787. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  43788. var pt = 0; // current index in the particle model shape
  43789. if (this.mesh.isFacetDataEnabled) {
  43790. this._computeBoundingBox = true;
  43791. }
  43792. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  43793. if (this._computeBoundingBox) {
  43794. if (start == 0 && end == this.nbParticles - 1) {
  43795. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  43796. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  43797. }
  43798. else {
  43799. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  43800. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  43801. }
  43802. }
  43803. // particle loop
  43804. index = this.particles[start]._pos;
  43805. var vpos = (index / 3) | 0;
  43806. colorIndex = vpos * 4;
  43807. uvIndex = vpos * 2;
  43808. for (var p = start; p <= end; p++) {
  43809. this._particle = this.particles[p];
  43810. this._shape = this._particle._model._shape;
  43811. this._shapeUV = this._particle._model._shapeUV;
  43812. // call to custom user function to update the particle properties
  43813. this.updateParticle(this._particle);
  43814. // skip the computations for inactive or already invisible particles
  43815. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  43816. // increment indexes for the next particle
  43817. pt = this._shape.length;
  43818. index += pt * 3;
  43819. colorIndex += pt * 4;
  43820. uvIndex += pt * 2;
  43821. continue;
  43822. }
  43823. if (this._particle.isVisible) {
  43824. this._particle._stillInvisible = false; // un-mark permanent invisibility
  43825. // particle rotation matrix
  43826. if (this.billboard) {
  43827. this._particle.rotation.x = 0.0;
  43828. this._particle.rotation.y = 0.0;
  43829. }
  43830. if (this._computeParticleRotation || this.billboard) {
  43831. if (this._particle.rotationQuaternion) {
  43832. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  43833. }
  43834. else {
  43835. this._yaw = this._particle.rotation.y;
  43836. this._pitch = this._particle.rotation.x;
  43837. this._roll = this._particle.rotation.z;
  43838. this._quaternionRotationYPR();
  43839. }
  43840. this._quaternionToRotationMatrix();
  43841. }
  43842. // particle vertex loop
  43843. for (pt = 0; pt < this._shape.length; pt++) {
  43844. idx = index + pt * 3;
  43845. colidx = colorIndex + pt * 4;
  43846. uvidx = uvIndex + pt * 2;
  43847. this._vertex.x = this._shape[pt].x;
  43848. this._vertex.y = this._shape[pt].y;
  43849. this._vertex.z = this._shape[pt].z;
  43850. if (this._computeParticleVertex) {
  43851. this.updateParticleVertex(this._particle, this._vertex, pt);
  43852. }
  43853. // positions
  43854. this._vertex.x *= this._particle.scaling.x;
  43855. this._vertex.y *= this._particle.scaling.y;
  43856. this._vertex.z *= this._particle.scaling.z;
  43857. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  43858. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  43859. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  43860. 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;
  43861. 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;
  43862. 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;
  43863. if (this._computeBoundingBox) {
  43864. if (this._positions32[idx] < this._minimum.x) {
  43865. this._minimum.x = this._positions32[idx];
  43866. }
  43867. if (this._positions32[idx] > this._maximum.x) {
  43868. this._maximum.x = this._positions32[idx];
  43869. }
  43870. if (this._positions32[idx + 1] < this._minimum.y) {
  43871. this._minimum.y = this._positions32[idx + 1];
  43872. }
  43873. if (this._positions32[idx + 1] > this._maximum.y) {
  43874. this._maximum.y = this._positions32[idx + 1];
  43875. }
  43876. if (this._positions32[idx + 2] < this._minimum.z) {
  43877. this._minimum.z = this._positions32[idx + 2];
  43878. }
  43879. if (this._positions32[idx + 2] > this._maximum.z) {
  43880. this._maximum.z = this._positions32[idx + 2];
  43881. }
  43882. }
  43883. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  43884. if (!this._computeParticleVertex) {
  43885. this._normal.x = this._fixedNormal32[idx];
  43886. this._normal.y = this._fixedNormal32[idx + 1];
  43887. this._normal.z = this._fixedNormal32[idx + 2];
  43888. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  43889. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  43890. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  43891. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  43892. 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;
  43893. 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;
  43894. }
  43895. if (this._computeParticleColor) {
  43896. this._colors32[colidx] = this._particle.color.r;
  43897. this._colors32[colidx + 1] = this._particle.color.g;
  43898. this._colors32[colidx + 2] = this._particle.color.b;
  43899. this._colors32[colidx + 3] = this._particle.color.a;
  43900. }
  43901. if (this._computeParticleTexture) {
  43902. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  43903. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  43904. }
  43905. }
  43906. }
  43907. else {
  43908. this._particle._stillInvisible = true; // mark the particle as invisible
  43909. for (pt = 0; pt < this._shape.length; pt++) {
  43910. idx = index + pt * 3;
  43911. colidx = colorIndex + pt * 4;
  43912. uvidx = uvIndex + pt * 2;
  43913. this._positions32[idx] = 0.0;
  43914. this._positions32[idx + 1] = 0.0;
  43915. this._positions32[idx + 2] = 0.0;
  43916. this._normals32[idx] = 0.0;
  43917. this._normals32[idx + 1] = 0.0;
  43918. this._normals32[idx + 2] = 0.0;
  43919. if (this._computeParticleColor) {
  43920. this._colors32[colidx] = this._particle.color.r;
  43921. this._colors32[colidx + 1] = this._particle.color.g;
  43922. this._colors32[colidx + 2] = this._particle.color.b;
  43923. this._colors32[colidx + 3] = this._particle.color.a;
  43924. }
  43925. if (this._computeParticleTexture) {
  43926. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  43927. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  43928. }
  43929. }
  43930. }
  43931. // if the particle intersections must be computed : update the bbInfo
  43932. if (this._particlesIntersect) {
  43933. var bInfo = this._particle._boundingInfo;
  43934. var bBox = bInfo.boundingBox;
  43935. var bSphere = bInfo.boundingSphere;
  43936. if (!this._bSphereOnly) {
  43937. // place, scale and rotate the particle bbox within the SPS local system, then update it
  43938. for (var b = 0; b < bBox.vectors.length; b++) {
  43939. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  43940. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  43941. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  43942. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  43943. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  43944. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  43945. 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;
  43946. 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;
  43947. 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;
  43948. }
  43949. bBox._update(this.mesh._worldMatrix);
  43950. }
  43951. // place and scale the particle bouding sphere in the SPS local system, then update it
  43952. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  43953. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  43954. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  43955. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  43956. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  43957. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  43958. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  43959. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  43960. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  43961. 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));
  43962. bSphere._update(this.mesh._worldMatrix);
  43963. }
  43964. // increment indexes for the next particle
  43965. index = idx + 3;
  43966. colorIndex = colidx + 4;
  43967. uvIndex = uvidx + 2;
  43968. }
  43969. // if the VBO must be updated
  43970. if (update) {
  43971. if (this._computeParticleColor) {
  43972. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  43973. }
  43974. if (this._computeParticleTexture) {
  43975. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  43976. }
  43977. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43978. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  43979. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  43980. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  43981. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  43982. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  43983. for (var i = 0; i < this._normals32.length; i++) {
  43984. this._fixedNormal32[i] = this._normals32[i];
  43985. }
  43986. }
  43987. if (!this.mesh.areNormalsFrozen) {
  43988. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  43989. }
  43990. }
  43991. }
  43992. if (this._computeBoundingBox) {
  43993. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  43994. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  43995. }
  43996. this.afterUpdateParticles(start, end, update);
  43997. return this;
  43998. };
  43999. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  44000. this._halfroll = this._roll * 0.5;
  44001. this._halfpitch = this._pitch * 0.5;
  44002. this._halfyaw = this._yaw * 0.5;
  44003. this._sinRoll = Math.sin(this._halfroll);
  44004. this._cosRoll = Math.cos(this._halfroll);
  44005. this._sinPitch = Math.sin(this._halfpitch);
  44006. this._cosPitch = Math.cos(this._halfpitch);
  44007. this._sinYaw = Math.sin(this._halfyaw);
  44008. this._cosYaw = Math.cos(this._halfyaw);
  44009. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  44010. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  44011. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  44012. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  44013. };
  44014. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  44015. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  44016. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  44017. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  44018. this._rotMatrix.m[3] = 0;
  44019. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  44020. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  44021. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  44022. this._rotMatrix.m[7] = 0;
  44023. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  44024. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  44025. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  44026. this._rotMatrix.m[11] = 0;
  44027. this._rotMatrix.m[12] = 0;
  44028. this._rotMatrix.m[13] = 0;
  44029. this._rotMatrix.m[14] = 0;
  44030. this._rotMatrix.m[15] = 1.0;
  44031. };
  44032. /**
  44033. * Disposes the SPS.
  44034. * Returns nothing.
  44035. */
  44036. SolidParticleSystem.prototype.dispose = function () {
  44037. this.mesh.dispose();
  44038. this.vars = null;
  44039. // drop references to internal big arrays for the GC
  44040. this._positions = null;
  44041. this._indices = null;
  44042. this._normals = null;
  44043. this._uvs = null;
  44044. this._colors = null;
  44045. this._positions32 = null;
  44046. this._normals32 = null;
  44047. this._fixedNormal32 = null;
  44048. this._uvs32 = null;
  44049. this._colors32 = null;
  44050. this.pickedParticles = null;
  44051. };
  44052. /**
  44053. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  44054. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44055. * Returns the SPS.
  44056. */
  44057. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  44058. if (!this._isVisibilityBoxLocked) {
  44059. this.mesh.refreshBoundingInfo();
  44060. }
  44061. return this;
  44062. };
  44063. /**
  44064. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  44065. * @param size the size (float) of the visibility box
  44066. * note : this doesn't lock the SPS mesh bounding box.
  44067. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44068. */
  44069. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  44070. var vis = size / 2;
  44071. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  44072. };
  44073. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  44074. // getter and setter
  44075. get: function () {
  44076. return this._alwaysVisible;
  44077. },
  44078. /**
  44079. * Sets the SPS as always visible or not
  44080. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44081. */
  44082. set: function (val) {
  44083. this._alwaysVisible = val;
  44084. this.mesh.alwaysSelectAsActiveMesh = val;
  44085. },
  44086. enumerable: true,
  44087. configurable: true
  44088. });
  44089. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  44090. get: function () {
  44091. return this._isVisibilityBoxLocked;
  44092. },
  44093. /**
  44094. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  44095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44096. */
  44097. set: function (val) {
  44098. this._isVisibilityBoxLocked = val;
  44099. this.mesh.getBoundingInfo().isLocked = val;
  44100. },
  44101. enumerable: true,
  44102. configurable: true
  44103. });
  44104. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  44105. // getters
  44106. get: function () {
  44107. return this._computeParticleRotation;
  44108. },
  44109. // Optimizer setters
  44110. /**
  44111. * Tells to `setParticles()` to compute the particle rotations or not.
  44112. * Default value : true. The SPS is faster when it's set to false.
  44113. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  44114. */
  44115. set: function (val) {
  44116. this._computeParticleRotation = val;
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  44122. get: function () {
  44123. return this._computeParticleColor;
  44124. },
  44125. /**
  44126. * Tells to `setParticles()` to compute the particle colors or not.
  44127. * Default value : true. The SPS is faster when it's set to false.
  44128. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  44129. */
  44130. set: function (val) {
  44131. this._computeParticleColor = val;
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  44137. get: function () {
  44138. return this._computeParticleTexture;
  44139. },
  44140. /**
  44141. * Tells to `setParticles()` to compute the particle textures or not.
  44142. * Default value : true. The SPS is faster when it's set to false.
  44143. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  44144. */
  44145. set: function (val) {
  44146. this._computeParticleTexture = val;
  44147. },
  44148. enumerable: true,
  44149. configurable: true
  44150. });
  44151. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  44152. get: function () {
  44153. return this._computeParticleVertex;
  44154. },
  44155. /**
  44156. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  44157. * Default value : false. The SPS is faster when it's set to false.
  44158. * Note : the particle custom vertex positions aren't stored values.
  44159. */
  44160. set: function (val) {
  44161. this._computeParticleVertex = val;
  44162. },
  44163. enumerable: true,
  44164. configurable: true
  44165. });
  44166. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  44167. get: function () {
  44168. return this._computeBoundingBox;
  44169. },
  44170. /**
  44171. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  44172. */
  44173. set: function (val) {
  44174. this._computeBoundingBox = val;
  44175. },
  44176. enumerable: true,
  44177. configurable: true
  44178. });
  44179. // =======================================================================
  44180. // Particle behavior logic
  44181. // these following methods may be overwritten by the user to fit his needs
  44182. /**
  44183. * This function does nothing. It may be overwritten to set all the particle first values.
  44184. * The SPS doesn't call this function, you may have to call it by your own.
  44185. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44186. */
  44187. SolidParticleSystem.prototype.initParticles = function () {
  44188. };
  44189. /**
  44190. * This function does nothing. It may be overwritten to recycle a particle.
  44191. * The SPS doesn't call this function, you may have to call it by your own.
  44192. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44193. */
  44194. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  44195. return particle;
  44196. };
  44197. /**
  44198. * Updates a particle : this function should be overwritten by the user.
  44199. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  44200. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44201. * ex : just set a particle position or velocity and recycle conditions
  44202. */
  44203. SolidParticleSystem.prototype.updateParticle = function (particle) {
  44204. return particle;
  44205. };
  44206. /**
  44207. * Updates a vertex of a particle : it can be overwritten by the user.
  44208. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  44209. * @param particle the current particle
  44210. * @param vertex the current index of the current particle
  44211. * @param pt the index of the current vertex in the particle shape
  44212. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  44213. * ex : just set a vertex particle position
  44214. */
  44215. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  44216. return vertex;
  44217. };
  44218. /**
  44219. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  44220. * This does nothing and may be overwritten by the user.
  44221. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44222. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44223. * @param update the boolean update value actually passed to setParticles()
  44224. */
  44225. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  44226. };
  44227. /**
  44228. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  44229. * This will be passed three parameters.
  44230. * This does nothing and may be overwritten by the user.
  44231. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44232. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44233. * @param update the boolean update value actually passed to setParticles()
  44234. */
  44235. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  44236. };
  44237. return SolidParticleSystem;
  44238. }());
  44239. BABYLON.SolidParticleSystem = SolidParticleSystem;
  44240. })(BABYLON || (BABYLON = {}));
  44241. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  44242. /// <reference path="babylon.mesh.ts" />
  44243. var BABYLON;
  44244. (function (BABYLON) {
  44245. var GroundMesh = (function (_super) {
  44246. __extends(GroundMesh, _super);
  44247. function GroundMesh(name, scene) {
  44248. var _this = _super.call(this, name, scene) || this;
  44249. _this.generateOctree = false;
  44250. _this._worldInverse = new BABYLON.Matrix();
  44251. return _this;
  44252. }
  44253. GroundMesh.prototype.getClassName = function () {
  44254. return "GroundMesh";
  44255. };
  44256. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  44257. get: function () {
  44258. return Math.min(this._subdivisionsX, this._subdivisionsY);
  44259. },
  44260. enumerable: true,
  44261. configurable: true
  44262. });
  44263. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  44264. get: function () {
  44265. return this._subdivisionsX;
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  44271. get: function () {
  44272. return this._subdivisionsY;
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  44278. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  44279. this._subdivisionsX = chunksCount;
  44280. this._subdivisionsY = chunksCount;
  44281. this.subdivide(chunksCount);
  44282. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  44283. };
  44284. /**
  44285. * Returns a height (y) value in the Worl system :
  44286. * the ground altitude at the coordinates (x, z) expressed in the World system.
  44287. * Returns the ground y position if (x, z) are outside the ground surface.
  44288. */
  44289. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  44290. var world = this.getWorldMatrix();
  44291. var invMat = BABYLON.Tmp.Matrix[5];
  44292. world.invertToRef(invMat);
  44293. var tmpVect = BABYLON.Tmp.Vector3[8];
  44294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  44295. x = tmpVect.x;
  44296. z = tmpVect.z;
  44297. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44298. return this.position.y;
  44299. }
  44300. if (!this._heightQuads || this._heightQuads.length == 0) {
  44301. this._initHeightQuads();
  44302. this._computeHeightQuads();
  44303. }
  44304. var facet = this._getFacetAt(x, z);
  44305. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  44306. // return y in the World system
  44307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  44308. return tmpVect.y;
  44309. };
  44310. /**
  44311. * Returns a normalized vector (Vector3) orthogonal to the ground
  44312. * at the ground coordinates (x, z) expressed in the World system.
  44313. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  44314. */
  44315. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  44316. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  44317. this.getNormalAtCoordinatesToRef(x, z, normal);
  44318. return normal;
  44319. };
  44320. /**
  44321. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  44322. * at the ground coordinates (x, z) expressed in the World system.
  44323. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  44324. * Returns the GroundMesh.
  44325. */
  44326. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  44327. var world = this.getWorldMatrix();
  44328. var tmpMat = BABYLON.Tmp.Matrix[5];
  44329. world.invertToRef(tmpMat);
  44330. var tmpVect = BABYLON.Tmp.Vector3[8];
  44331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  44332. x = tmpVect.x;
  44333. z = tmpVect.z;
  44334. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44335. return this;
  44336. }
  44337. if (!this._heightQuads || this._heightQuads.length == 0) {
  44338. this._initHeightQuads();
  44339. this._computeHeightQuads();
  44340. }
  44341. var facet = this._getFacetAt(x, z);
  44342. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  44343. return this;
  44344. };
  44345. /**
  44346. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  44347. * if the ground has been updated.
  44348. * This can be used in the render loop.
  44349. * Returns the GroundMesh.
  44350. */
  44351. GroundMesh.prototype.updateCoordinateHeights = function () {
  44352. if (!this._heightQuads || this._heightQuads.length == 0) {
  44353. this._initHeightQuads();
  44354. }
  44355. this._computeHeightQuads();
  44356. return this;
  44357. };
  44358. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  44359. GroundMesh.prototype._getFacetAt = function (x, z) {
  44360. // retrieve col and row from x, z coordinates in the ground local system
  44361. var subdivisionsX = this._subdivisionsX;
  44362. var subdivisionsY = this._subdivisionsY;
  44363. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  44364. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  44365. var quad = this._heightQuads[row * this._subdivisionsX + col];
  44366. var facet;
  44367. if (z < quad.slope.x * x + quad.slope.y) {
  44368. facet = quad.facet1;
  44369. }
  44370. else {
  44371. facet = quad.facet2;
  44372. }
  44373. return facet;
  44374. };
  44375. // Creates and populates the heightMap array with "facet" elements :
  44376. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  44377. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44378. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44379. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44380. // Returns the GroundMesh.
  44381. GroundMesh.prototype._initHeightQuads = function () {
  44382. var subdivisionsX = this._subdivisionsX;
  44383. var subdivisionsY = this._subdivisionsY;
  44384. this._heightQuads = new Array();
  44385. for (var row = 0; row < subdivisionsY; row++) {
  44386. for (var col = 0; col < subdivisionsX; col++) {
  44387. 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) };
  44388. this._heightQuads[row * subdivisionsX + col] = quad;
  44389. }
  44390. }
  44391. return this;
  44392. };
  44393. // Compute each quad element values and update the the heightMap array :
  44394. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44395. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44396. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44397. // Returns the GroundMesh.
  44398. GroundMesh.prototype._computeHeightQuads = function () {
  44399. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44400. var v1 = BABYLON.Tmp.Vector3[3];
  44401. var v2 = BABYLON.Tmp.Vector3[2];
  44402. var v3 = BABYLON.Tmp.Vector3[1];
  44403. var v4 = BABYLON.Tmp.Vector3[0];
  44404. var v1v2 = BABYLON.Tmp.Vector3[4];
  44405. var v1v3 = BABYLON.Tmp.Vector3[5];
  44406. var v1v4 = BABYLON.Tmp.Vector3[6];
  44407. var norm1 = BABYLON.Tmp.Vector3[7];
  44408. var norm2 = BABYLON.Tmp.Vector3[8];
  44409. var i = 0;
  44410. var j = 0;
  44411. var k = 0;
  44412. var cd = 0; // 2D slope coefficient : z = cd * x + h
  44413. var h = 0;
  44414. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  44415. var d2 = 0;
  44416. var subdivisionsX = this._subdivisionsX;
  44417. var subdivisionsY = this._subdivisionsY;
  44418. for (var row = 0; row < subdivisionsY; row++) {
  44419. for (var col = 0; col < subdivisionsX; col++) {
  44420. i = col * 3;
  44421. j = row * (subdivisionsX + 1) * 3;
  44422. k = (row + 1) * (subdivisionsX + 1) * 3;
  44423. v1.x = positions[j + i];
  44424. v1.y = positions[j + i + 1];
  44425. v1.z = positions[j + i + 2];
  44426. v2.x = positions[j + i + 3];
  44427. v2.y = positions[j + i + 4];
  44428. v2.z = positions[j + i + 5];
  44429. v3.x = positions[k + i];
  44430. v3.y = positions[k + i + 1];
  44431. v3.z = positions[k + i + 2];
  44432. v4.x = positions[k + i + 3];
  44433. v4.y = positions[k + i + 4];
  44434. v4.z = positions[k + i + 5];
  44435. // 2D slope V1V4
  44436. cd = (v4.z - v1.z) / (v4.x - v1.x);
  44437. h = v1.z - cd * v1.x; // v1 belongs to the slope
  44438. // facet equations :
  44439. // we compute each facet normal vector
  44440. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  44441. // we compute the value d by applying the equation to v1 which belongs to the plane
  44442. // then we store the facet equation in a Vector4
  44443. v2.subtractToRef(v1, v1v2);
  44444. v3.subtractToRef(v1, v1v3);
  44445. v4.subtractToRef(v1, v1v4);
  44446. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  44447. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  44448. norm1.normalize();
  44449. norm2.normalize();
  44450. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  44451. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  44452. var quad = this._heightQuads[row * subdivisionsX + col];
  44453. quad.slope.copyFromFloats(cd, h);
  44454. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  44455. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  44456. }
  44457. }
  44458. return this;
  44459. };
  44460. GroundMesh.prototype.serialize = function (serializationObject) {
  44461. _super.prototype.serialize.call(this, serializationObject);
  44462. serializationObject.subdivisionsX = this._subdivisionsX;
  44463. serializationObject.subdivisionsY = this._subdivisionsY;
  44464. serializationObject.minX = this._minX;
  44465. serializationObject.maxX = this._maxX;
  44466. serializationObject.minZ = this._minZ;
  44467. serializationObject.maxZ = this._maxZ;
  44468. serializationObject.width = this._width;
  44469. serializationObject.height = this._height;
  44470. };
  44471. GroundMesh.Parse = function (parsedMesh, scene) {
  44472. var result = new GroundMesh(parsedMesh.name, scene);
  44473. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  44474. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  44475. result._minX = parsedMesh.minX;
  44476. result._maxX = parsedMesh.maxX;
  44477. result._minZ = parsedMesh.minZ;
  44478. result._maxZ = parsedMesh.maxZ;
  44479. result._width = parsedMesh.width;
  44480. result._height = parsedMesh.height;
  44481. return result;
  44482. };
  44483. return GroundMesh;
  44484. }(BABYLON.Mesh));
  44485. BABYLON.GroundMesh = GroundMesh;
  44486. })(BABYLON || (BABYLON = {}));
  44487. //# sourceMappingURL=babylon.groundMesh.js.map
  44488. var BABYLON;
  44489. (function (BABYLON) {
  44490. /**
  44491. * Creates an instance based on a source mesh.
  44492. */
  44493. var InstancedMesh = (function (_super) {
  44494. __extends(InstancedMesh, _super);
  44495. function InstancedMesh(name, source) {
  44496. var _this = _super.call(this, name, source.getScene()) || this;
  44497. source.instances.push(_this);
  44498. _this._sourceMesh = source;
  44499. _this.position.copyFrom(source.position);
  44500. _this.rotation.copyFrom(source.rotation);
  44501. _this.scaling.copyFrom(source.scaling);
  44502. if (source.rotationQuaternion) {
  44503. _this.rotationQuaternion = source.rotationQuaternion.clone();
  44504. }
  44505. _this.infiniteDistance = source.infiniteDistance;
  44506. _this.setPivotMatrix(source.getPivotMatrix());
  44507. _this.refreshBoundingInfo();
  44508. _this._syncSubMeshes();
  44509. return _this;
  44510. }
  44511. /**
  44512. * Returns the string "InstancedMesh".
  44513. */
  44514. InstancedMesh.prototype.getClassName = function () {
  44515. return "InstancedMesh";
  44516. };
  44517. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  44518. // Methods
  44519. get: function () {
  44520. return this._sourceMesh.receiveShadows;
  44521. },
  44522. enumerable: true,
  44523. configurable: true
  44524. });
  44525. Object.defineProperty(InstancedMesh.prototype, "material", {
  44526. get: function () {
  44527. return this._sourceMesh.material;
  44528. },
  44529. enumerable: true,
  44530. configurable: true
  44531. });
  44532. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  44533. get: function () {
  44534. return this._sourceMesh.visibility;
  44535. },
  44536. enumerable: true,
  44537. configurable: true
  44538. });
  44539. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  44540. get: function () {
  44541. return this._sourceMesh.skeleton;
  44542. },
  44543. enumerable: true,
  44544. configurable: true
  44545. });
  44546. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  44547. get: function () {
  44548. return this._sourceMesh.renderingGroupId;
  44549. },
  44550. enumerable: true,
  44551. configurable: true
  44552. });
  44553. /**
  44554. * Returns the total number of vertices (integer).
  44555. */
  44556. InstancedMesh.prototype.getTotalVertices = function () {
  44557. return this._sourceMesh.getTotalVertices();
  44558. };
  44559. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  44560. get: function () {
  44561. return this._sourceMesh;
  44562. },
  44563. enumerable: true,
  44564. configurable: true
  44565. });
  44566. /**
  44567. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  44568. */
  44569. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  44570. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  44571. };
  44572. /**
  44573. * Sets the vertex data of the mesh geometry for the requested `kind`.
  44574. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  44575. * The `data` are either a numeric array either a Float32Array.
  44576. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  44577. * 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).
  44578. * Note that a new underlying VertexBuffer object is created each call.
  44579. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  44580. *
  44581. * Possible `kind` values :
  44582. * - BABYLON.VertexBuffer.PositionKind
  44583. * - BABYLON.VertexBuffer.UVKind
  44584. * - BABYLON.VertexBuffer.UV2Kind
  44585. * - BABYLON.VertexBuffer.UV3Kind
  44586. * - BABYLON.VertexBuffer.UV4Kind
  44587. * - BABYLON.VertexBuffer.UV5Kind
  44588. * - BABYLON.VertexBuffer.UV6Kind
  44589. * - BABYLON.VertexBuffer.ColorKind
  44590. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44591. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44592. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44593. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44594. *
  44595. * Returns the Mesh.
  44596. */
  44597. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  44598. if (this.sourceMesh) {
  44599. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  44600. }
  44601. return this.sourceMesh;
  44602. };
  44603. /**
  44604. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  44605. * If the mesh has no geometry, it is simply returned as it is.
  44606. * The `data` are either a numeric array either a Float32Array.
  44607. * No new underlying VertexBuffer object is created.
  44608. * 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.
  44609. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  44610. *
  44611. * Possible `kind` values :
  44612. * - BABYLON.VertexBuffer.PositionKind
  44613. * - BABYLON.VertexBuffer.UVKind
  44614. * - BABYLON.VertexBuffer.UV2Kind
  44615. * - BABYLON.VertexBuffer.UV3Kind
  44616. * - BABYLON.VertexBuffer.UV4Kind
  44617. * - BABYLON.VertexBuffer.UV5Kind
  44618. * - BABYLON.VertexBuffer.UV6Kind
  44619. * - BABYLON.VertexBuffer.ColorKind
  44620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44624. *
  44625. * Returns the Mesh.
  44626. */
  44627. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  44628. if (this.sourceMesh) {
  44629. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  44630. }
  44631. return this.sourceMesh;
  44632. };
  44633. /**
  44634. * Sets the mesh indices.
  44635. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  44636. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  44637. * This method creates a new index buffer each call.
  44638. * Returns the Mesh.
  44639. */
  44640. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  44641. if (this.sourceMesh) {
  44642. this.sourceMesh.setIndices(indices, totalVertices);
  44643. }
  44644. return this.sourceMesh;
  44645. };
  44646. /**
  44647. * Boolean : True if the mesh owns the requested kind of data.
  44648. */
  44649. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  44650. return this._sourceMesh.isVerticesDataPresent(kind);
  44651. };
  44652. /**
  44653. * Returns an array of indices (IndicesArray).
  44654. */
  44655. InstancedMesh.prototype.getIndices = function () {
  44656. return this._sourceMesh.getIndices();
  44657. };
  44658. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  44659. get: function () {
  44660. return this._sourceMesh._positions;
  44661. },
  44662. enumerable: true,
  44663. configurable: true
  44664. });
  44665. /**
  44666. * Sets a new updated BoundingInfo to the mesh.
  44667. * Returns the mesh.
  44668. */
  44669. InstancedMesh.prototype.refreshBoundingInfo = function () {
  44670. var meshBB = this._sourceMesh.getBoundingInfo();
  44671. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  44672. this._updateBoundingInfo();
  44673. return this;
  44674. };
  44675. InstancedMesh.prototype._preActivate = function () {
  44676. if (this._currentLOD) {
  44677. this._currentLOD._preActivate();
  44678. }
  44679. return this;
  44680. };
  44681. InstancedMesh.prototype._activate = function (renderId) {
  44682. if (this._currentLOD) {
  44683. this._currentLOD._registerInstanceForRenderId(this, renderId);
  44684. }
  44685. return this;
  44686. };
  44687. /**
  44688. * Returns the current associated LOD AbstractMesh.
  44689. */
  44690. InstancedMesh.prototype.getLOD = function (camera) {
  44691. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  44692. if (this._currentLOD === this.sourceMesh) {
  44693. return this;
  44694. }
  44695. return this._currentLOD;
  44696. };
  44697. InstancedMesh.prototype._syncSubMeshes = function () {
  44698. this.releaseSubMeshes();
  44699. if (this._sourceMesh.subMeshes) {
  44700. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  44701. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  44702. }
  44703. }
  44704. return this;
  44705. };
  44706. InstancedMesh.prototype._generatePointsArray = function () {
  44707. return this._sourceMesh._generatePointsArray();
  44708. };
  44709. /**
  44710. * Creates a new InstancedMesh from the current mesh.
  44711. * - name (string) : the cloned mesh name
  44712. * - newParent (optional Node) : the optional Node to parent the clone to.
  44713. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44714. *
  44715. * Returns the clone.
  44716. */
  44717. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44718. var result = this._sourceMesh.createInstance(name);
  44719. // Deep copy
  44720. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44721. // Bounding info
  44722. this.refreshBoundingInfo();
  44723. // Parent
  44724. if (newParent) {
  44725. result.parent = newParent;
  44726. }
  44727. if (!doNotCloneChildren) {
  44728. // Children
  44729. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44730. var mesh = this.getScene().meshes[index];
  44731. if (mesh.parent === this) {
  44732. mesh.clone(mesh.name, result);
  44733. }
  44734. }
  44735. }
  44736. result.computeWorldMatrix(true);
  44737. return result;
  44738. };
  44739. /**
  44740. * Disposes the InstancedMesh.
  44741. * Returns nothing.
  44742. */
  44743. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  44744. // Remove from mesh
  44745. var index = this._sourceMesh.instances.indexOf(this);
  44746. this._sourceMesh.instances.splice(index, 1);
  44747. _super.prototype.dispose.call(this, doNotRecurse);
  44748. };
  44749. return InstancedMesh;
  44750. }(BABYLON.AbstractMesh));
  44751. BABYLON.InstancedMesh = InstancedMesh;
  44752. })(BABYLON || (BABYLON = {}));
  44753. //# sourceMappingURL=babylon.instancedMesh.js.map
  44754. /// <reference path="babylon.mesh.ts" />
  44755. var BABYLON;
  44756. (function (BABYLON) {
  44757. var LinesMesh = (function (_super) {
  44758. __extends(LinesMesh, _super);
  44759. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  44760. if (parent === void 0) { parent = null; }
  44761. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  44762. _this.useVertexColor = useVertexColor;
  44763. _this.color = new BABYLON.Color3(1, 1, 1);
  44764. _this.alpha = 1;
  44765. if (source) {
  44766. _this.color = source.color.clone();
  44767. _this.alpha = source.alpha;
  44768. _this.useVertexColor = source.useVertexColor;
  44769. }
  44770. _this._intersectionThreshold = 0.1;
  44771. var options = {
  44772. attributes: [BABYLON.VertexBuffer.PositionKind],
  44773. uniforms: ["world", "viewProjection"],
  44774. needAlphaBlending: false,
  44775. };
  44776. if (!useVertexColor) {
  44777. options.uniforms.push("color");
  44778. options.needAlphaBlending = true;
  44779. }
  44780. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  44781. return _this;
  44782. }
  44783. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  44784. /**
  44785. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44786. * This margin is expressed in world space coordinates, so its value may vary.
  44787. * Default value is 0.1
  44788. * @returns the intersection Threshold value.
  44789. */
  44790. get: function () {
  44791. return this._intersectionThreshold;
  44792. },
  44793. /**
  44794. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44795. * This margin is expressed in world space coordinates, so its value may vary.
  44796. * @param value the new threshold to apply
  44797. */
  44798. set: function (value) {
  44799. if (this._intersectionThreshold === value) {
  44800. return;
  44801. }
  44802. this._intersectionThreshold = value;
  44803. if (this.geometry) {
  44804. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  44805. }
  44806. },
  44807. enumerable: true,
  44808. configurable: true
  44809. });
  44810. /**
  44811. * Returns the string "LineMesh"
  44812. */
  44813. LinesMesh.prototype.getClassName = function () {
  44814. return "LinesMesh";
  44815. };
  44816. Object.defineProperty(LinesMesh.prototype, "material", {
  44817. get: function () {
  44818. return this._colorShader;
  44819. },
  44820. enumerable: true,
  44821. configurable: true
  44822. });
  44823. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44824. get: function () {
  44825. return false;
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. LinesMesh.prototype.createInstance = function (name) {
  44831. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44832. return null;
  44833. };
  44834. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44835. // VBOs
  44836. this._geometry._bind(this._colorShader.getEffect());
  44837. // Color
  44838. if (!this.useVertexColor) {
  44839. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44840. }
  44841. return this;
  44842. };
  44843. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44844. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44845. return this;
  44846. }
  44847. var engine = this.getScene().getEngine();
  44848. // Draw order
  44849. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44850. return this;
  44851. };
  44852. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44853. this._colorShader.dispose();
  44854. _super.prototype.dispose.call(this, doNotRecurse);
  44855. };
  44856. /**
  44857. * Returns a new LineMesh object cloned from the current one.
  44858. */
  44859. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44860. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44861. };
  44862. return LinesMesh;
  44863. }(BABYLON.Mesh));
  44864. BABYLON.LinesMesh = LinesMesh;
  44865. })(BABYLON || (BABYLON = {}));
  44866. //# sourceMappingURL=babylon.linesMesh.js.map
  44867. var BABYLON;
  44868. (function (BABYLON) {
  44869. var ShaderMaterial = (function (_super) {
  44870. __extends(ShaderMaterial, _super);
  44871. function ShaderMaterial(name, scene, shaderPath, options) {
  44872. var _this = _super.call(this, name, scene) || this;
  44873. _this._textures = {};
  44874. _this._textureArrays = {};
  44875. _this._floats = {};
  44876. _this._floatsArrays = {};
  44877. _this._colors3 = {};
  44878. _this._colors3Arrays = {};
  44879. _this._colors4 = {};
  44880. _this._vectors2 = {};
  44881. _this._vectors3 = {};
  44882. _this._vectors4 = {};
  44883. _this._matrices = {};
  44884. _this._matrices3x3 = {};
  44885. _this._matrices2x2 = {};
  44886. _this._vectors3Arrays = {};
  44887. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44888. _this._shaderPath = shaderPath;
  44889. options.needAlphaBlending = options.needAlphaBlending || false;
  44890. options.needAlphaTesting = options.needAlphaTesting || false;
  44891. options.attributes = options.attributes || ["position", "normal", "uv"];
  44892. options.uniforms = options.uniforms || ["worldViewProjection"];
  44893. options.uniformBuffers = options.uniformBuffers || [];
  44894. options.samplers = options.samplers || [];
  44895. options.defines = options.defines || [];
  44896. _this._options = options;
  44897. return _this;
  44898. }
  44899. ShaderMaterial.prototype.getClassName = function () {
  44900. return "ShaderMaterial";
  44901. };
  44902. ShaderMaterial.prototype.needAlphaBlending = function () {
  44903. return this._options.needAlphaBlending;
  44904. };
  44905. ShaderMaterial.prototype.needAlphaTesting = function () {
  44906. return this._options.needAlphaTesting;
  44907. };
  44908. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44909. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44910. this._options.uniforms.push(uniformName);
  44911. }
  44912. };
  44913. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44914. if (this._options.samplers.indexOf(name) === -1) {
  44915. this._options.samplers.push(name);
  44916. }
  44917. this._textures[name] = texture;
  44918. return this;
  44919. };
  44920. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44921. if (this._options.samplers.indexOf(name) === -1) {
  44922. this._options.samplers.push(name);
  44923. }
  44924. this._checkUniform(name);
  44925. this._textureArrays[name] = textures;
  44926. return this;
  44927. };
  44928. ShaderMaterial.prototype.setFloat = function (name, value) {
  44929. this._checkUniform(name);
  44930. this._floats[name] = value;
  44931. return this;
  44932. };
  44933. ShaderMaterial.prototype.setFloats = function (name, value) {
  44934. this._checkUniform(name);
  44935. this._floatsArrays[name] = value;
  44936. return this;
  44937. };
  44938. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44939. this._checkUniform(name);
  44940. this._colors3[name] = value;
  44941. return this;
  44942. };
  44943. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  44944. this._checkUniform(name);
  44945. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  44946. color.toArray(arr, arr.length);
  44947. return arr;
  44948. }, []);
  44949. return this;
  44950. };
  44951. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44952. this._checkUniform(name);
  44953. this._colors4[name] = value;
  44954. return this;
  44955. };
  44956. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44957. this._checkUniform(name);
  44958. this._vectors2[name] = value;
  44959. return this;
  44960. };
  44961. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44962. this._checkUniform(name);
  44963. this._vectors3[name] = value;
  44964. return this;
  44965. };
  44966. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44967. this._checkUniform(name);
  44968. this._vectors4[name] = value;
  44969. return this;
  44970. };
  44971. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44972. this._checkUniform(name);
  44973. this._matrices[name] = value;
  44974. return this;
  44975. };
  44976. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44977. this._checkUniform(name);
  44978. this._matrices3x3[name] = value;
  44979. return this;
  44980. };
  44981. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44982. this._checkUniform(name);
  44983. this._matrices2x2[name] = value;
  44984. return this;
  44985. };
  44986. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44987. this._checkUniform(name);
  44988. this._vectors3Arrays[name] = value;
  44989. return this;
  44990. };
  44991. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44992. if (!mesh) {
  44993. return true;
  44994. }
  44995. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44996. return false;
  44997. }
  44998. return false;
  44999. };
  45000. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45001. var scene = this.getScene();
  45002. var engine = scene.getEngine();
  45003. if (!this.checkReadyOnEveryCall) {
  45004. if (this._renderId === scene.getRenderId()) {
  45005. if (this._checkCache(scene, mesh, useInstances)) {
  45006. return true;
  45007. }
  45008. }
  45009. }
  45010. // Instances
  45011. var defines = [];
  45012. var attribs = [];
  45013. var fallbacks = new BABYLON.EffectFallbacks();
  45014. if (useInstances) {
  45015. defines.push("#define INSTANCES");
  45016. }
  45017. for (var index = 0; index < this._options.defines.length; index++) {
  45018. defines.push(this._options.defines[index]);
  45019. }
  45020. for (var index = 0; index < this._options.attributes.length; index++) {
  45021. attribs.push(this._options.attributes[index]);
  45022. }
  45023. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45024. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45025. defines.push("#define VERTEXCOLOR");
  45026. }
  45027. // Bones
  45028. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45029. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45030. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45031. if (mesh.numBoneInfluencers > 4) {
  45032. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45033. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45034. }
  45035. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45036. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45037. fallbacks.addCPUSkinningFallback(0, mesh);
  45038. if (this._options.uniforms.indexOf("mBones") === -1) {
  45039. this._options.uniforms.push("mBones");
  45040. }
  45041. }
  45042. else {
  45043. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45044. }
  45045. // Textures
  45046. for (var name in this._textures) {
  45047. if (!this._textures[name].isReady()) {
  45048. return false;
  45049. }
  45050. }
  45051. // Alpha test
  45052. if (engine.getAlphaTesting()) {
  45053. defines.push("#define ALPHATEST");
  45054. }
  45055. var previousEffect = this._effect;
  45056. var join = defines.join("\n");
  45057. this._effect = engine.createEffect(this._shaderPath, {
  45058. attributes: attribs,
  45059. uniformsNames: this._options.uniforms,
  45060. uniformBuffersNames: this._options.uniformBuffers,
  45061. samplers: this._options.samplers,
  45062. defines: join,
  45063. fallbacks: fallbacks,
  45064. onCompiled: this.onCompiled,
  45065. onError: this.onError
  45066. }, engine);
  45067. if (!this._effect.isReady()) {
  45068. return false;
  45069. }
  45070. if (previousEffect !== this._effect) {
  45071. scene.resetCachedMaterial();
  45072. }
  45073. this._renderId = scene.getRenderId();
  45074. return true;
  45075. };
  45076. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45077. var scene = this.getScene();
  45078. if (this._options.uniforms.indexOf("world") !== -1) {
  45079. this._effect.setMatrix("world", world);
  45080. }
  45081. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45082. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45083. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45084. }
  45085. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45086. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45087. }
  45088. };
  45089. ShaderMaterial.prototype.bind = function (world, mesh) {
  45090. // Std values
  45091. this.bindOnlyWorldMatrix(world);
  45092. if (this.getScene().getCachedMaterial() !== this) {
  45093. if (this._options.uniforms.indexOf("view") !== -1) {
  45094. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45095. }
  45096. if (this._options.uniforms.indexOf("projection") !== -1) {
  45097. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45098. }
  45099. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45100. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45101. }
  45102. // Bones
  45103. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45104. var name;
  45105. // Texture
  45106. for (name in this._textures) {
  45107. this._effect.setTexture(name, this._textures[name]);
  45108. }
  45109. // Texture arrays
  45110. for (name in this._textureArrays) {
  45111. this._effect.setTextureArray(name, this._textureArrays[name]);
  45112. }
  45113. // Float
  45114. for (name in this._floats) {
  45115. this._effect.setFloat(name, this._floats[name]);
  45116. }
  45117. // Float s
  45118. for (name in this._floatsArrays) {
  45119. this._effect.setArray(name, this._floatsArrays[name]);
  45120. }
  45121. // Color3
  45122. for (name in this._colors3) {
  45123. this._effect.setColor3(name, this._colors3[name]);
  45124. }
  45125. for (name in this._colors3Arrays) {
  45126. this._effect.setArray3(name, this._colors3Arrays[name]);
  45127. }
  45128. // Color4
  45129. for (name in this._colors4) {
  45130. var color = this._colors4[name];
  45131. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45132. }
  45133. // Vector2
  45134. for (name in this._vectors2) {
  45135. this._effect.setVector2(name, this._vectors2[name]);
  45136. }
  45137. // Vector3
  45138. for (name in this._vectors3) {
  45139. this._effect.setVector3(name, this._vectors3[name]);
  45140. }
  45141. // Vector4
  45142. for (name in this._vectors4) {
  45143. this._effect.setVector4(name, this._vectors4[name]);
  45144. }
  45145. // Matrix
  45146. for (name in this._matrices) {
  45147. this._effect.setMatrix(name, this._matrices[name]);
  45148. }
  45149. // Matrix 3x3
  45150. for (name in this._matrices3x3) {
  45151. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45152. }
  45153. // Matrix 2x2
  45154. for (name in this._matrices2x2) {
  45155. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45156. }
  45157. // Vector3Array
  45158. for (name in this._vectors3Arrays) {
  45159. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45160. }
  45161. }
  45162. this._afterBind(mesh);
  45163. };
  45164. ShaderMaterial.prototype.getActiveTextures = function () {
  45165. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45166. for (var name in this._textures) {
  45167. activeTextures.push(this._textures[name]);
  45168. }
  45169. for (var name in this._textureArrays) {
  45170. var array = this._textureArrays[name];
  45171. for (var index = 0; index < array.length; index++) {
  45172. activeTextures.push(array[index]);
  45173. }
  45174. }
  45175. return activeTextures;
  45176. };
  45177. ShaderMaterial.prototype.hasTexture = function (texture) {
  45178. if (_super.prototype.hasTexture.call(this, texture)) {
  45179. return true;
  45180. }
  45181. for (var name in this._textures) {
  45182. if (this._textures[name] === texture) {
  45183. return true;
  45184. }
  45185. }
  45186. for (var name in this._textureArrays) {
  45187. var array = this._textureArrays[name];
  45188. for (var index = 0; index < array.length; index++) {
  45189. if (array[index] === texture) {
  45190. return true;
  45191. }
  45192. }
  45193. }
  45194. return false;
  45195. };
  45196. ShaderMaterial.prototype.clone = function (name) {
  45197. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45198. return newShaderMaterial;
  45199. };
  45200. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45201. if (forceDisposeTextures) {
  45202. var name;
  45203. for (name in this._textures) {
  45204. this._textures[name].dispose();
  45205. }
  45206. for (name in this._textureArrays) {
  45207. var array = this._textureArrays[name];
  45208. for (var index = 0; index < array.length; index++) {
  45209. array[index].dispose();
  45210. }
  45211. }
  45212. }
  45213. this._textures = {};
  45214. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45215. };
  45216. ShaderMaterial.prototype.serialize = function () {
  45217. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45218. serializationObject.customType = "BABYLON.ShaderMaterial";
  45219. serializationObject.options = this._options;
  45220. serializationObject.shaderPath = this._shaderPath;
  45221. var name;
  45222. // Texture
  45223. serializationObject.textures = {};
  45224. for (name in this._textures) {
  45225. serializationObject.textures[name] = this._textures[name].serialize();
  45226. }
  45227. // Texture arrays
  45228. serializationObject.textureArrays = {};
  45229. for (name in this._textureArrays) {
  45230. serializationObject.textureArrays[name] = [];
  45231. var array = this._textureArrays[name];
  45232. for (var index = 0; index < array.length; index++) {
  45233. serializationObject.textureArrays[name].push(array[index].serialize());
  45234. }
  45235. }
  45236. // Float
  45237. serializationObject.floats = {};
  45238. for (name in this._floats) {
  45239. serializationObject.floats[name] = this._floats[name];
  45240. }
  45241. // Float s
  45242. serializationObject.floatArrays = {};
  45243. for (name in this._floatsArrays) {
  45244. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45245. }
  45246. // Color3
  45247. serializationObject.colors3 = {};
  45248. for (name in this._colors3) {
  45249. serializationObject.colors3[name] = this._colors3[name].asArray();
  45250. }
  45251. // Color3 array
  45252. serializationObject.colors3Arrays = {};
  45253. for (name in this._colors3Arrays) {
  45254. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  45255. }
  45256. // Color4
  45257. serializationObject.colors4 = {};
  45258. for (name in this._colors4) {
  45259. serializationObject.colors4[name] = this._colors4[name].asArray();
  45260. }
  45261. // Vector2
  45262. serializationObject.vectors2 = {};
  45263. for (name in this._vectors2) {
  45264. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45265. }
  45266. // Vector3
  45267. serializationObject.vectors3 = {};
  45268. for (name in this._vectors3) {
  45269. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45270. }
  45271. // Vector4
  45272. serializationObject.vectors4 = {};
  45273. for (name in this._vectors4) {
  45274. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45275. }
  45276. // Matrix
  45277. serializationObject.matrices = {};
  45278. for (name in this._matrices) {
  45279. serializationObject.matrices[name] = this._matrices[name].asArray();
  45280. }
  45281. // Matrix 3x3
  45282. serializationObject.matrices3x3 = {};
  45283. for (name in this._matrices3x3) {
  45284. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45285. }
  45286. // Matrix 2x2
  45287. serializationObject.matrices2x2 = {};
  45288. for (name in this._matrices2x2) {
  45289. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45290. }
  45291. // Vector3Array
  45292. serializationObject.vectors3Arrays = {};
  45293. for (name in this._vectors3Arrays) {
  45294. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45295. }
  45296. return serializationObject;
  45297. };
  45298. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45299. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45300. var name;
  45301. // Texture
  45302. for (name in source.textures) {
  45303. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45304. }
  45305. // Texture arrays
  45306. for (name in source.textureArrays) {
  45307. var array = source.textureArrays[name];
  45308. var textureArray = new Array();
  45309. for (var index = 0; index < array.length; index++) {
  45310. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45311. }
  45312. material.setTextureArray(name, textureArray);
  45313. }
  45314. // Float
  45315. for (name in source.floats) {
  45316. material.setFloat(name, source.floats[name]);
  45317. }
  45318. // Float s
  45319. for (name in source.floatsArrays) {
  45320. material.setFloats(name, source.floatsArrays[name]);
  45321. }
  45322. // Color3
  45323. for (name in source.colors3) {
  45324. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45325. }
  45326. // Color3 arrays
  45327. for (name in source.colors3Arrays) {
  45328. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  45329. if (i % 3 === 0) {
  45330. arr.push([num]);
  45331. }
  45332. else {
  45333. arr[arr.length - 1].push(num);
  45334. }
  45335. return arr;
  45336. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  45337. material.setColor3Array(name, colors);
  45338. }
  45339. // Color4
  45340. for (name in source.colors4) {
  45341. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45342. }
  45343. // Vector2
  45344. for (name in source.vectors2) {
  45345. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45346. }
  45347. // Vector3
  45348. for (name in source.vectors3) {
  45349. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45350. }
  45351. // Vector4
  45352. for (name in source.vectors4) {
  45353. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45354. }
  45355. // Matrix
  45356. for (name in source.matrices) {
  45357. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45358. }
  45359. // Matrix 3x3
  45360. for (name in source.matrices3x3) {
  45361. material.setMatrix3x3(name, source.matrices3x3[name]);
  45362. }
  45363. // Matrix 2x2
  45364. for (name in source.matrices2x2) {
  45365. material.setMatrix2x2(name, source.matrices2x2[name]);
  45366. }
  45367. // Vector3Array
  45368. for (name in source.vectors3Arrays) {
  45369. material.setArray3(name, source.vectors3Arrays[name]);
  45370. }
  45371. return material;
  45372. };
  45373. return ShaderMaterial;
  45374. }(BABYLON.Material));
  45375. BABYLON.ShaderMaterial = ShaderMaterial;
  45376. })(BABYLON || (BABYLON = {}));
  45377. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45378. var BABYLON;
  45379. (function (BABYLON) {
  45380. var MeshBuilder = (function () {
  45381. function MeshBuilder() {
  45382. }
  45383. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  45384. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  45385. return BABYLON.Mesh.DOUBLESIDE;
  45386. }
  45387. if (orientation === undefined || orientation === null) {
  45388. return BABYLON.Mesh.FRONTSIDE;
  45389. }
  45390. return orientation;
  45391. };
  45392. /**
  45393. * Creates a box mesh.
  45394. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  45395. * The parameter `size` sets the size (float) of each box side (default 1).
  45396. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  45397. * 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).
  45398. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  45399. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45400. * 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).
  45401. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45403. */
  45404. MeshBuilder.CreateBox = function (name, options, scene) {
  45405. var box = new BABYLON.Mesh(name, scene);
  45406. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45407. box._originalBuilderSideOrientation = options.sideOrientation;
  45408. var vertexData = BABYLON.VertexData.CreateBox(options);
  45409. vertexData.applyToMesh(box, options.updatable);
  45410. return box;
  45411. };
  45412. /**
  45413. * Creates a sphere mesh.
  45414. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  45415. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  45416. * 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`).
  45417. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  45418. * 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
  45419. * 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).
  45420. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45421. * 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).
  45422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45424. */
  45425. MeshBuilder.CreateSphere = function (name, options, scene) {
  45426. var sphere = new BABYLON.Mesh(name, scene);
  45427. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45428. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45429. var vertexData = BABYLON.VertexData.CreateSphere(options);
  45430. vertexData.applyToMesh(sphere, options.updatable);
  45431. return sphere;
  45432. };
  45433. /**
  45434. * Creates a plane polygonal mesh. By default, this is a disc.
  45435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  45436. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  45437. * 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.
  45438. * 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
  45439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45440. * 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).
  45441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45443. */
  45444. MeshBuilder.CreateDisc = function (name, options, scene) {
  45445. var disc = new BABYLON.Mesh(name, scene);
  45446. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45447. disc._originalBuilderSideOrientation = options.sideOrientation;
  45448. var vertexData = BABYLON.VertexData.CreateDisc(options);
  45449. vertexData.applyToMesh(disc, options.updatable);
  45450. return disc;
  45451. };
  45452. /**
  45453. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  45454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  45455. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  45456. * 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`).
  45457. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  45458. * 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.
  45459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45460. * 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).
  45461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45463. */
  45464. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  45465. var sphere = new BABYLON.Mesh(name, scene);
  45466. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45467. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45468. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  45469. vertexData.applyToMesh(sphere, options.updatable);
  45470. return sphere;
  45471. };
  45472. ;
  45473. /**
  45474. * Creates a ribbon mesh.
  45475. * 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.
  45476. *
  45477. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  45478. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  45479. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  45480. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  45481. * 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.
  45482. * 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.
  45483. * 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
  45484. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45485. * 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).
  45486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45487. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45488. * 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.
  45489. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  45490. * 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
  45491. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  45492. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  45493. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45494. */
  45495. MeshBuilder.CreateRibbon = function (name, options, scene) {
  45496. var pathArray = options.pathArray;
  45497. var closeArray = options.closeArray;
  45498. var closePath = options.closePath;
  45499. var offset = options.offset;
  45500. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45501. var instance = options.instance;
  45502. var updatable = options.updatable;
  45503. if (instance) {
  45504. // positionFunction : ribbon case
  45505. // only pathArray and sideOrientation parameters are taken into account for positions update
  45506. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  45507. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  45508. var positionFunction = function (positions) {
  45509. var minlg = pathArray[0].length;
  45510. var i = 0;
  45511. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  45512. for (var si = 1; si <= ns; si++) {
  45513. for (var p = 0; p < pathArray.length; p++) {
  45514. var path = pathArray[p];
  45515. var l = path.length;
  45516. minlg = (minlg < l) ? minlg : l;
  45517. var j = 0;
  45518. while (j < minlg) {
  45519. positions[i] = path[j].x;
  45520. positions[i + 1] = path[j].y;
  45521. positions[i + 2] = path[j].z;
  45522. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  45523. BABYLON.Tmp.Vector3[0].x = path[j].x;
  45524. }
  45525. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  45526. BABYLON.Tmp.Vector3[1].x = path[j].x;
  45527. }
  45528. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  45529. BABYLON.Tmp.Vector3[0].y = path[j].y;
  45530. }
  45531. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  45532. BABYLON.Tmp.Vector3[1].y = path[j].y;
  45533. }
  45534. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  45535. BABYLON.Tmp.Vector3[0].z = path[j].z;
  45536. }
  45537. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  45538. BABYLON.Tmp.Vector3[1].z = path[j].z;
  45539. }
  45540. j++;
  45541. i += 3;
  45542. }
  45543. if (instance._closePath) {
  45544. positions[i] = path[0].x;
  45545. positions[i + 1] = path[0].y;
  45546. positions[i + 2] = path[0].z;
  45547. i += 3;
  45548. }
  45549. }
  45550. }
  45551. };
  45552. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45553. positionFunction(positions);
  45554. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  45555. instance._boundingInfo.update(instance._worldMatrix);
  45556. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  45557. if (options.colors) {
  45558. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45559. for (var c = 0; c < options.colors.length; c++) {
  45560. colors[c * 4] = options.colors[c].r;
  45561. colors[c * 4 + 1] = options.colors[c].g;
  45562. colors[c * 4 + 2] = options.colors[c].b;
  45563. colors[c * 4 + 3] = options.colors[c].a;
  45564. }
  45565. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  45566. }
  45567. if (options.uvs) {
  45568. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45569. for (var i = 0; i < options.uvs.length; i++) {
  45570. uvs[i * 2] = options.uvs[i].x;
  45571. uvs[i * 2 + 1] = options.uvs[i].y;
  45572. }
  45573. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  45574. }
  45575. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  45576. var indices = instance.getIndices();
  45577. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45578. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  45579. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  45580. if (instance._closePath) {
  45581. var indexFirst = 0;
  45582. var indexLast = 0;
  45583. for (var p = 0; p < pathArray.length; p++) {
  45584. indexFirst = instance._idx[p] * 3;
  45585. if (p + 1 < pathArray.length) {
  45586. indexLast = (instance._idx[p + 1] - 1) * 3;
  45587. }
  45588. else {
  45589. indexLast = normals.length - 3;
  45590. }
  45591. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  45592. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  45593. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  45594. normals[indexLast] = normals[indexFirst];
  45595. normals[indexLast + 1] = normals[indexFirst + 1];
  45596. normals[indexLast + 2] = normals[indexFirst + 2];
  45597. }
  45598. }
  45599. if (!(instance.areNormalsFrozen)) {
  45600. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  45601. }
  45602. }
  45603. return instance;
  45604. }
  45605. else {
  45606. var ribbon = new BABYLON.Mesh(name, scene);
  45607. ribbon._originalBuilderSideOrientation = sideOrientation;
  45608. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  45609. if (closePath) {
  45610. ribbon._idx = vertexData._idx;
  45611. }
  45612. ribbon._closePath = closePath;
  45613. ribbon._closeArray = closeArray;
  45614. vertexData.applyToMesh(ribbon, updatable);
  45615. return ribbon;
  45616. }
  45617. };
  45618. /**
  45619. * Creates a cylinder or a cone mesh.
  45620. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  45621. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  45622. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  45623. * 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.
  45624. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  45625. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  45626. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  45627. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  45628. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  45629. * 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).
  45630. * 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
  45631. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  45632. * 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
  45633. * 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.
  45634. * If `enclose` is false, a ring surface is one element.
  45635. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  45636. * 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
  45637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45638. * 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).
  45639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45641. */
  45642. MeshBuilder.CreateCylinder = function (name, options, scene) {
  45643. var cylinder = new BABYLON.Mesh(name, scene);
  45644. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45645. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  45646. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  45647. vertexData.applyToMesh(cylinder, options.updatable);
  45648. return cylinder;
  45649. };
  45650. /**
  45651. * Creates a torus mesh.
  45652. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  45653. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  45654. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  45655. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  45656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45657. * 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).
  45658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45660. */
  45661. MeshBuilder.CreateTorus = function (name, options, scene) {
  45662. var torus = new BABYLON.Mesh(name, scene);
  45663. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45664. torus._originalBuilderSideOrientation = options.sideOrientation;
  45665. var vertexData = BABYLON.VertexData.CreateTorus(options);
  45666. vertexData.applyToMesh(torus, options.updatable);
  45667. return torus;
  45668. };
  45669. /**
  45670. * Creates a torus knot mesh.
  45671. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  45672. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  45673. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  45674. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  45675. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  45676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45677. * 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).
  45678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45680. */
  45681. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  45682. var torusKnot = new BABYLON.Mesh(name, scene);
  45683. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45684. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  45685. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  45686. vertexData.applyToMesh(torusKnot, options.updatable);
  45687. return torusKnot;
  45688. };
  45689. /**
  45690. * Creates a line system mesh.
  45691. * A line system is a pool of many lines gathered in a single mesh.
  45692. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  45693. * 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.
  45694. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  45695. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  45696. * 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
  45697. * 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
  45698. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  45699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45700. */
  45701. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  45702. var instance = options.instance;
  45703. var lines = options.lines;
  45704. if (instance) {
  45705. var positionFunction = function (positions) {
  45706. var i = 0;
  45707. for (var l = 0; l < lines.length; l++) {
  45708. var points = lines[l];
  45709. for (var p = 0; p < points.length; p++) {
  45710. positions[i] = points[p].x;
  45711. positions[i + 1] = points[p].y;
  45712. positions[i + 2] = points[p].z;
  45713. i += 3;
  45714. }
  45715. }
  45716. };
  45717. instance.updateMeshPositions(positionFunction, false);
  45718. return instance;
  45719. }
  45720. // line system creation
  45721. var lineSystem = new BABYLON.LinesMesh(name, scene);
  45722. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  45723. vertexData.applyToMesh(lineSystem, options.updatable);
  45724. return lineSystem;
  45725. };
  45726. /**
  45727. * Creates a line mesh.
  45728. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  45729. * 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.
  45730. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  45731. * The parameter `points` is an array successive Vector3.
  45732. * 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
  45733. * When updating an instance, remember that only point positions can change, not the number of points.
  45734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45735. */
  45736. MeshBuilder.CreateLines = function (name, options, scene) {
  45737. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  45738. return lines;
  45739. };
  45740. /**
  45741. * Creates a dashed line mesh.
  45742. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  45743. * 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.
  45744. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  45745. * The parameter `points` is an array successive Vector3.
  45746. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  45747. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  45748. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  45749. * 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
  45750. * When updating an instance, remember that only point positions can change, not the number of points.
  45751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45752. */
  45753. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  45754. var points = options.points;
  45755. var instance = options.instance;
  45756. var gapSize = options.gapSize || 1;
  45757. var dashSize = options.dashSize || 3;
  45758. if (instance) {
  45759. var positionFunction = function (positions) {
  45760. var curvect = BABYLON.Vector3.Zero();
  45761. var nbSeg = positions.length / 6;
  45762. var lg = 0;
  45763. var nb = 0;
  45764. var shft = 0;
  45765. var dashshft = 0;
  45766. var curshft = 0;
  45767. var p = 0;
  45768. var i = 0;
  45769. var j = 0;
  45770. for (i = 0; i < points.length - 1; i++) {
  45771. points[i + 1].subtractToRef(points[i], curvect);
  45772. lg += curvect.length();
  45773. }
  45774. shft = lg / nbSeg;
  45775. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  45776. for (i = 0; i < points.length - 1; i++) {
  45777. points[i + 1].subtractToRef(points[i], curvect);
  45778. nb = Math.floor(curvect.length() / shft);
  45779. curvect.normalize();
  45780. j = 0;
  45781. while (j < nb && p < positions.length) {
  45782. curshft = shft * j;
  45783. positions[p] = points[i].x + curshft * curvect.x;
  45784. positions[p + 1] = points[i].y + curshft * curvect.y;
  45785. positions[p + 2] = points[i].z + curshft * curvect.z;
  45786. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  45787. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  45788. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  45789. p += 6;
  45790. j++;
  45791. }
  45792. }
  45793. while (p < positions.length) {
  45794. positions[p] = points[i].x;
  45795. positions[p + 1] = points[i].y;
  45796. positions[p + 2] = points[i].z;
  45797. p += 3;
  45798. }
  45799. };
  45800. instance.updateMeshPositions(positionFunction, false);
  45801. return instance;
  45802. }
  45803. // dashed lines creation
  45804. var dashedLines = new BABYLON.LinesMesh(name, scene);
  45805. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  45806. vertexData.applyToMesh(dashedLines, options.updatable);
  45807. dashedLines.dashSize = dashSize;
  45808. dashedLines.gapSize = gapSize;
  45809. return dashedLines;
  45810. };
  45811. /**
  45812. * Creates an extruded shape mesh.
  45813. * 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.
  45814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  45815. *
  45816. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  45817. * 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
  45818. * extruded along the Z axis.
  45819. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  45820. * 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.
  45821. * The parameter `scale` (float, default 1) is the value to scale the shape.
  45822. * 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
  45823. * 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
  45824. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  45825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45826. * 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).
  45827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45828. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45830. */
  45831. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  45832. var path = options.path;
  45833. var shape = options.shape;
  45834. var scale = options.scale || 1;
  45835. var rotation = options.rotation || 0;
  45836. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  45837. var updatable = options.updatable;
  45838. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45839. var instance = options.instance;
  45840. var invertUV = options.invertUV || false;
  45841. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  45842. };
  45843. /**
  45844. * Creates an custom extruded shape mesh.
  45845. * 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.
  45846. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  45847. *
  45848. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  45849. * 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
  45850. * extruded along the Z axis.
  45851. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  45852. * 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
  45853. * and the distance of this point from the begining of the path :
  45854. * ```javascript
  45855. * var rotationFunction = function(i, distance) {
  45856. * // do things
  45857. * return rotationValue; }
  45858. * ```
  45859. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  45860. * 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
  45861. * and the distance of this point from the begining of the path :
  45862. * ```javascript
  45863. * var scaleFunction = function(i, distance) {
  45864. * // do things
  45865. * return scaleValue;}
  45866. * ```
  45867. * It must returns a float value that will be the scale value applied to the shape on each path point.
  45868. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  45869. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  45870. * 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
  45871. * 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
  45872. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  45873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45874. * 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).
  45875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45876. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45878. */
  45879. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  45880. var path = options.path;
  45881. var shape = options.shape;
  45882. var scaleFunction = options.scaleFunction || (function () { return 1; });
  45883. var rotationFunction = options.rotationFunction || (function () { return 0; });
  45884. var ribbonCloseArray = options.ribbonCloseArray || false;
  45885. var ribbonClosePath = options.ribbonClosePath || false;
  45886. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  45887. var updatable = options.updatable;
  45888. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45889. var instance = options.instance;
  45890. var invertUV = options.invertUV || false;
  45891. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  45892. };
  45893. /**
  45894. * Creates lathe mesh.
  45895. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  45896. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  45897. *
  45898. * 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
  45899. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  45900. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  45901. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  45902. * 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.
  45903. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  45904. * 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
  45905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45906. * 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).
  45907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45908. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45910. */
  45911. MeshBuilder.CreateLathe = function (name, options, scene) {
  45912. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  45913. var closed = (options.closed === undefined) ? true : options.closed;
  45914. var shape = options.shape;
  45915. var radius = options.radius || 1;
  45916. var tessellation = options.tessellation || 64;
  45917. var updatable = options.updatable;
  45918. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45919. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  45920. var pi2 = Math.PI * 2;
  45921. var paths = new Array();
  45922. var invertUV = options.invertUV || false;
  45923. var i = 0;
  45924. var p = 0;
  45925. var step = pi2 / tessellation * arc;
  45926. var rotated;
  45927. var path = new Array();
  45928. ;
  45929. for (i = 0; i <= tessellation; i++) {
  45930. var path = [];
  45931. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  45932. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  45933. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  45934. }
  45935. for (p = 0; p < shape.length; p++) {
  45936. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  45937. path.push(rotated);
  45938. }
  45939. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  45940. 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));
  45941. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  45942. }
  45943. paths.push(path);
  45944. }
  45945. // lathe ribbon
  45946. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  45947. return lathe;
  45948. };
  45949. /**
  45950. * Creates a plane mesh.
  45951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  45952. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  45953. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  45954. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  45955. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45956. * 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).
  45957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45959. */
  45960. MeshBuilder.CreatePlane = function (name, options, scene) {
  45961. var plane = new BABYLON.Mesh(name, scene);
  45962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45963. plane._originalBuilderSideOrientation = options.sideOrientation;
  45964. var vertexData = BABYLON.VertexData.CreatePlane(options);
  45965. vertexData.applyToMesh(plane, options.updatable);
  45966. if (options.sourcePlane) {
  45967. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  45968. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  45969. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  45970. plane.rotate(vectorProduct, product);
  45971. }
  45972. return plane;
  45973. };
  45974. /**
  45975. * Creates a ground mesh.
  45976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  45977. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  45978. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  45979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45980. */
  45981. MeshBuilder.CreateGround = function (name, options, scene) {
  45982. var ground = new BABYLON.GroundMesh(name, scene);
  45983. ground._setReady(false);
  45984. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  45985. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  45986. ground._width = options.width || 1;
  45987. ground._height = options.height || 1;
  45988. ground._maxX = ground._width / 2;
  45989. ground._maxZ = ground._height / 2;
  45990. ground._minX = -ground._maxX;
  45991. ground._minZ = -ground._maxZ;
  45992. var vertexData = BABYLON.VertexData.CreateGround(options);
  45993. vertexData.applyToMesh(ground, options.updatable);
  45994. ground._setReady(true);
  45995. return ground;
  45996. };
  45997. /**
  45998. * Creates a tiled ground mesh.
  45999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  46000. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  46001. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  46002. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  46003. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  46004. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  46005. * numbers of subdivisions on the ground width and height of each tile.
  46006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46007. */
  46008. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  46009. var tiledGround = new BABYLON.Mesh(name, scene);
  46010. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  46011. vertexData.applyToMesh(tiledGround, options.updatable);
  46012. return tiledGround;
  46013. };
  46014. /**
  46015. * Creates a ground mesh from a height map.
  46016. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  46017. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  46018. * The parameter `url` sets the URL of the height map image resource.
  46019. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  46020. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  46021. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  46022. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  46023. * 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.
  46024. * 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).
  46025. * This function is passed the newly built mesh :
  46026. * ```javascript
  46027. * function(mesh) { // do things
  46028. * return; }
  46029. * ```
  46030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46031. */
  46032. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  46033. var width = options.width || 10.0;
  46034. var height = options.height || 10.0;
  46035. var subdivisions = options.subdivisions || 1 | 0;
  46036. var minHeight = options.minHeight || 0.0;
  46037. var maxHeight = options.maxHeight || 1.0;
  46038. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  46039. var updatable = options.updatable;
  46040. var onReady = options.onReady;
  46041. var ground = new BABYLON.GroundMesh(name, scene);
  46042. ground._subdivisionsX = subdivisions;
  46043. ground._subdivisionsY = subdivisions;
  46044. ground._width = width;
  46045. ground._height = height;
  46046. ground._maxX = ground._width / 2.0;
  46047. ground._maxZ = ground._height / 2.0;
  46048. ground._minX = -ground._maxX;
  46049. ground._minZ = -ground._maxZ;
  46050. ground._setReady(false);
  46051. var onload = function (img) {
  46052. // Getting height map data
  46053. var canvas = document.createElement("canvas");
  46054. var context = canvas.getContext("2d");
  46055. var bufferWidth = img.width;
  46056. var bufferHeight = img.height;
  46057. canvas.width = bufferWidth;
  46058. canvas.height = bufferHeight;
  46059. context.drawImage(img, 0, 0);
  46060. // Create VertexData from map data
  46061. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  46062. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  46063. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  46064. width: width, height: height,
  46065. subdivisions: subdivisions,
  46066. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  46067. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  46068. });
  46069. vertexData.applyToMesh(ground, updatable);
  46070. ground._setReady(true);
  46071. //execute ready callback, if set
  46072. if (onReady) {
  46073. onReady(ground);
  46074. }
  46075. };
  46076. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  46077. return ground;
  46078. };
  46079. /**
  46080. * Creates a polygon mesh.
  46081. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  46082. * 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.
  46083. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46084. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46085. * 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).
  46086. * Remember you can only change the shape positions, not their number when updating a polygon.
  46087. */
  46088. MeshBuilder.CreatePolygon = function (name, options, scene) {
  46089. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46090. var shape = options.shape;
  46091. var holes = options.holes || [];
  46092. var depth = options.depth || 0;
  46093. var contours = [];
  46094. var hole = [];
  46095. for (var i = 0; i < shape.length; i++) {
  46096. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  46097. }
  46098. var epsilon = 0.00000001;
  46099. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  46100. contours.pop();
  46101. }
  46102. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  46103. for (var hNb = 0; hNb < holes.length; hNb++) {
  46104. hole = [];
  46105. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  46106. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  46107. }
  46108. polygonTriangulation.addHole(hole);
  46109. }
  46110. var polygon = polygonTriangulation.build(options.updatable, depth);
  46111. polygon._originalBuilderSideOrientation = options.sideOrientation;
  46112. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  46113. vertexData.applyToMesh(polygon, options.updatable);
  46114. return polygon;
  46115. };
  46116. ;
  46117. /**
  46118. * Creates an extruded polygon mesh, with depth in the Y direction.
  46119. * 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).
  46120. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46121. */
  46122. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  46123. return MeshBuilder.CreatePolygon(name, options, scene);
  46124. };
  46125. ;
  46126. /**
  46127. * Creates a tube mesh.
  46128. * 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.
  46129. *
  46130. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  46131. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  46132. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  46133. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  46134. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  46135. * 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.
  46136. * It must return a radius value (positive float) :
  46137. * ```javascript
  46138. * var radiusFunction = function(i, distance) {
  46139. * // do things
  46140. * return radius; }
  46141. * ```
  46142. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  46143. * 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
  46144. * 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
  46145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46146. * 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).
  46147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46148. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46150. */
  46151. MeshBuilder.CreateTube = function (name, options, scene) {
  46152. var path = options.path;
  46153. var instance = options.instance;
  46154. var radius = 1.0;
  46155. if (instance) {
  46156. radius = instance.radius;
  46157. }
  46158. if (options.radius !== undefined) {
  46159. radius = options.radius;
  46160. }
  46161. ;
  46162. var tessellation = options.tessellation || 64 | 0;
  46163. var radiusFunction = options.radiusFunction;
  46164. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46165. var invertUV = options.invertUV || false;
  46166. var updatable = options.updatable;
  46167. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46168. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  46169. // tube geometry
  46170. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  46171. var tangents = path3D.getTangents();
  46172. var normals = path3D.getNormals();
  46173. var distances = path3D.getDistances();
  46174. var pi2 = Math.PI * 2;
  46175. var step = pi2 / tessellation * arc;
  46176. var returnRadius = function () { return radius; };
  46177. var radiusFunctionFinal = radiusFunction || returnRadius;
  46178. var circlePath;
  46179. var rad;
  46180. var normal;
  46181. var rotated;
  46182. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46183. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46184. for (var i = 0; i < path.length; i++) {
  46185. rad = radiusFunctionFinal(i, distances[i]); // current radius
  46186. circlePath = Array(); // current circle array
  46187. normal = normals[i]; // current normal
  46188. for (var t = 0; t < tessellation; t++) {
  46189. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  46190. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  46191. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  46192. rotated.scaleInPlace(rad).addInPlace(path[i]);
  46193. circlePath[t] = rotated;
  46194. }
  46195. circlePaths[index] = circlePath;
  46196. index++;
  46197. }
  46198. // cap
  46199. var capPath = function (nbPoints, pathIndex) {
  46200. var pointCap = Array();
  46201. for (var i = 0; i < nbPoints; i++) {
  46202. pointCap.push(path[pathIndex]);
  46203. }
  46204. return pointCap;
  46205. };
  46206. switch (cap) {
  46207. case BABYLON.Mesh.NO_CAP:
  46208. break;
  46209. case BABYLON.Mesh.CAP_START:
  46210. circlePaths[0] = capPath(tessellation, 0);
  46211. circlePaths[1] = circlePaths[2].slice(0);
  46212. break;
  46213. case BABYLON.Mesh.CAP_END:
  46214. circlePaths[index] = circlePaths[index - 1].slice(0);
  46215. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46216. break;
  46217. case BABYLON.Mesh.CAP_ALL:
  46218. circlePaths[0] = capPath(tessellation, 0);
  46219. circlePaths[1] = circlePaths[2].slice(0);
  46220. circlePaths[index] = circlePaths[index - 1].slice(0);
  46221. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46222. break;
  46223. default:
  46224. break;
  46225. }
  46226. return circlePaths;
  46227. };
  46228. var path3D;
  46229. var pathArray;
  46230. if (instance) {
  46231. var arc = options.arc || instance.arc;
  46232. path3D = (instance.path3D).update(path);
  46233. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  46234. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  46235. instance.path3D = path3D;
  46236. instance.pathArray = pathArray;
  46237. instance.arc = arc;
  46238. instance.radius = radius;
  46239. return instance;
  46240. }
  46241. // tube creation
  46242. path3D = new BABYLON.Path3D(path);
  46243. var newPathArray = new Array();
  46244. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46245. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  46246. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  46247. tube.pathArray = pathArray;
  46248. tube.path3D = path3D;
  46249. tube.tessellation = tessellation;
  46250. tube.cap = cap;
  46251. tube.arc = options.arc;
  46252. tube.radius = radius;
  46253. return tube;
  46254. };
  46255. /**
  46256. * Creates a polyhedron mesh.
  46257. *
  46258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  46259. * 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
  46260. * to choose the wanted type.
  46261. * The parameter `size` (positive float, default 1) sets the polygon size.
  46262. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  46263. * 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`.
  46264. * 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
  46265. * 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)`).
  46266. * 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
  46267. * 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.
  46268. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46269. * 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).
  46270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46272. */
  46273. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  46274. var polyhedron = new BABYLON.Mesh(name, scene);
  46275. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46276. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  46277. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  46278. vertexData.applyToMesh(polyhedron, options.updatable);
  46279. return polyhedron;
  46280. };
  46281. /**
  46282. * Creates a decal mesh.
  46283. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  46284. * 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.
  46285. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  46286. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  46287. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  46288. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  46289. */
  46290. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  46291. var indices = sourceMesh.getIndices();
  46292. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46293. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46294. var position = options.position || BABYLON.Vector3.Zero();
  46295. var normal = options.normal || BABYLON.Vector3.Up();
  46296. var size = options.size || BABYLON.Vector3.One();
  46297. var angle = options.angle || 0;
  46298. // Getting correct rotation
  46299. if (!normal) {
  46300. var target = new BABYLON.Vector3(0, 0, 1);
  46301. var camera = sourceMesh.getScene().activeCamera;
  46302. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  46303. normal = camera.globalPosition.subtract(cameraWorldTarget);
  46304. }
  46305. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  46306. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  46307. var pitch = Math.atan2(normal.y, len);
  46308. // Matrix
  46309. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  46310. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  46311. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  46312. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  46313. var vertexData = new BABYLON.VertexData();
  46314. vertexData.indices = [];
  46315. vertexData.positions = [];
  46316. vertexData.normals = [];
  46317. vertexData.uvs = [];
  46318. var currentVertexDataIndex = 0;
  46319. var extractDecalVector3 = function (indexId) {
  46320. var vertexId = indices[indexId];
  46321. var result = new BABYLON.PositionNormalVertex();
  46322. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  46323. // Send vector to decal local world
  46324. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  46325. // Get normal
  46326. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  46327. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  46328. return result;
  46329. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  46330. var clip = function (vertices, axis) {
  46331. if (vertices.length === 0) {
  46332. return vertices;
  46333. }
  46334. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  46335. var clipVertices = function (v0, v1) {
  46336. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  46337. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  46338. };
  46339. var result = new Array();
  46340. for (var index = 0; index < vertices.length; index += 3) {
  46341. var v1Out;
  46342. var v2Out;
  46343. var v3Out;
  46344. var total = 0;
  46345. var nV1, nV2, nV3, nV4;
  46346. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  46347. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  46348. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  46349. v1Out = d1 > 0;
  46350. v2Out = d2 > 0;
  46351. v3Out = d3 > 0;
  46352. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  46353. switch (total) {
  46354. case 0:
  46355. result.push(vertices[index]);
  46356. result.push(vertices[index + 1]);
  46357. result.push(vertices[index + 2]);
  46358. break;
  46359. case 1:
  46360. if (v1Out) {
  46361. nV1 = vertices[index + 1];
  46362. nV2 = vertices[index + 2];
  46363. nV3 = clipVertices(vertices[index], nV1);
  46364. nV4 = clipVertices(vertices[index], nV2);
  46365. }
  46366. if (v2Out) {
  46367. nV1 = vertices[index];
  46368. nV2 = vertices[index + 2];
  46369. nV3 = clipVertices(vertices[index + 1], nV1);
  46370. nV4 = clipVertices(vertices[index + 1], nV2);
  46371. result.push(nV3);
  46372. result.push(nV2.clone());
  46373. result.push(nV1.clone());
  46374. result.push(nV2.clone());
  46375. result.push(nV3.clone());
  46376. result.push(nV4);
  46377. break;
  46378. }
  46379. if (v3Out) {
  46380. nV1 = vertices[index];
  46381. nV2 = vertices[index + 1];
  46382. nV3 = clipVertices(vertices[index + 2], nV1);
  46383. nV4 = clipVertices(vertices[index + 2], nV2);
  46384. }
  46385. result.push(nV1.clone());
  46386. result.push(nV2.clone());
  46387. result.push(nV3);
  46388. result.push(nV4);
  46389. result.push(nV3.clone());
  46390. result.push(nV2.clone());
  46391. break;
  46392. case 2:
  46393. if (!v1Out) {
  46394. nV1 = vertices[index].clone();
  46395. nV2 = clipVertices(nV1, vertices[index + 1]);
  46396. nV3 = clipVertices(nV1, vertices[index + 2]);
  46397. result.push(nV1);
  46398. result.push(nV2);
  46399. result.push(nV3);
  46400. }
  46401. if (!v2Out) {
  46402. nV1 = vertices[index + 1].clone();
  46403. nV2 = clipVertices(nV1, vertices[index + 2]);
  46404. nV3 = clipVertices(nV1, vertices[index]);
  46405. result.push(nV1);
  46406. result.push(nV2);
  46407. result.push(nV3);
  46408. }
  46409. if (!v3Out) {
  46410. nV1 = vertices[index + 2].clone();
  46411. nV2 = clipVertices(nV1, vertices[index]);
  46412. nV3 = clipVertices(nV1, vertices[index + 1]);
  46413. result.push(nV1);
  46414. result.push(nV2);
  46415. result.push(nV3);
  46416. }
  46417. break;
  46418. case 3:
  46419. break;
  46420. }
  46421. }
  46422. return result;
  46423. };
  46424. for (var index = 0; index < indices.length; index += 3) {
  46425. var faceVertices = new Array();
  46426. faceVertices.push(extractDecalVector3(index));
  46427. faceVertices.push(extractDecalVector3(index + 1));
  46428. faceVertices.push(extractDecalVector3(index + 2));
  46429. // Clip
  46430. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  46431. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  46432. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  46433. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  46434. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  46435. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  46436. if (faceVertices.length === 0) {
  46437. continue;
  46438. }
  46439. // Add UVs and get back to world
  46440. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  46441. var vertex = faceVertices[vIndex];
  46442. //TODO check for Int32Array | Uint32Array | Uint16Array
  46443. vertexData.indices.push(currentVertexDataIndex);
  46444. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  46445. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  46446. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  46447. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  46448. currentVertexDataIndex++;
  46449. }
  46450. }
  46451. // Return mesh
  46452. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  46453. vertexData.applyToMesh(decal);
  46454. decal.position = position.clone();
  46455. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  46456. return decal;
  46457. };
  46458. // Privates
  46459. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  46460. // extrusion geometry
  46461. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  46462. var tangents = path3D.getTangents();
  46463. var normals = path3D.getNormals();
  46464. var binormals = path3D.getBinormals();
  46465. var distances = path3D.getDistances();
  46466. var angle = 0;
  46467. var returnScale = function () { return scale; };
  46468. var returnRotation = function () { return rotation; };
  46469. var rotate = custom ? rotateFunction : returnRotation;
  46470. var scl = custom ? scaleFunction : returnScale;
  46471. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46472. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46473. for (var i = 0; i < curve.length; i++) {
  46474. var shapePath = new Array();
  46475. var angleStep = rotate(i, distances[i]);
  46476. var scaleRatio = scl(i, distances[i]);
  46477. for (var p = 0; p < shape.length; p++) {
  46478. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  46479. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  46480. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  46481. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  46482. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  46483. shapePath[p] = rotated;
  46484. }
  46485. shapePaths[index] = shapePath;
  46486. angle += angleStep;
  46487. index++;
  46488. }
  46489. // cap
  46490. var capPath = function (shapePath) {
  46491. var pointCap = Array();
  46492. var barycenter = BABYLON.Vector3.Zero();
  46493. var i;
  46494. for (i = 0; i < shapePath.length; i++) {
  46495. barycenter.addInPlace(shapePath[i]);
  46496. }
  46497. barycenter.scaleInPlace(1.0 / shapePath.length);
  46498. for (i = 0; i < shapePath.length; i++) {
  46499. pointCap.push(barycenter);
  46500. }
  46501. return pointCap;
  46502. };
  46503. switch (cap) {
  46504. case BABYLON.Mesh.NO_CAP:
  46505. break;
  46506. case BABYLON.Mesh.CAP_START:
  46507. shapePaths[0] = capPath(shapePaths[2]);
  46508. shapePaths[1] = shapePaths[2];
  46509. break;
  46510. case BABYLON.Mesh.CAP_END:
  46511. shapePaths[index] = shapePaths[index - 1];
  46512. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46513. break;
  46514. case BABYLON.Mesh.CAP_ALL:
  46515. shapePaths[0] = capPath(shapePaths[2]);
  46516. shapePaths[1] = shapePaths[2];
  46517. shapePaths[index] = shapePaths[index - 1];
  46518. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46519. break;
  46520. default:
  46521. break;
  46522. }
  46523. return shapePaths;
  46524. };
  46525. var path3D;
  46526. var pathArray;
  46527. if (instance) {
  46528. path3D = (instance.path3D).update(curve);
  46529. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  46530. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  46531. return instance;
  46532. }
  46533. // extruded shape creation
  46534. path3D = new BABYLON.Path3D(curve);
  46535. var newShapePaths = new Array();
  46536. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46537. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  46538. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  46539. extrudedGeneric.pathArray = pathArray;
  46540. extrudedGeneric.path3D = path3D;
  46541. extrudedGeneric.cap = cap;
  46542. return extrudedGeneric;
  46543. };
  46544. return MeshBuilder;
  46545. }());
  46546. BABYLON.MeshBuilder = MeshBuilder;
  46547. })(BABYLON || (BABYLON = {}));
  46548. //# sourceMappingURL=babylon.meshBuilder.js.map
  46549. var BABYLON;
  46550. (function (BABYLON) {
  46551. var AudioEngine = (function () {
  46552. function AudioEngine() {
  46553. this._audioContext = null;
  46554. this._audioContextInitialized = false;
  46555. this.canUseWebAudio = false;
  46556. this.WarnedWebAudioUnsupported = false;
  46557. this.unlocked = false;
  46558. this.isMP3supported = false;
  46559. this.isOGGsupported = false;
  46560. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  46561. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  46562. this.canUseWebAudio = true;
  46563. }
  46564. var audioElem = document.createElement('audio');
  46565. try {
  46566. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  46567. this.isMP3supported = true;
  46568. }
  46569. }
  46570. catch (e) {
  46571. // protect error during capability check.
  46572. }
  46573. try {
  46574. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  46575. this.isOGGsupported = true;
  46576. }
  46577. }
  46578. catch (e) {
  46579. // protect error during capability check.
  46580. }
  46581. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  46582. this._unlockiOSaudio();
  46583. }
  46584. else {
  46585. this.unlocked = true;
  46586. }
  46587. }
  46588. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  46589. get: function () {
  46590. if (!this._audioContextInitialized) {
  46591. this._initializeAudioContext();
  46592. }
  46593. return this._audioContext;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. AudioEngine.prototype._unlockiOSaudio = function () {
  46599. var _this = this;
  46600. var unlockaudio = function () {
  46601. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  46602. var source = _this.audioContext.createBufferSource();
  46603. source.buffer = buffer;
  46604. source.connect(_this.audioContext.destination);
  46605. source.start(0);
  46606. setTimeout(function () {
  46607. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  46608. _this.unlocked = true;
  46609. window.removeEventListener('touchend', unlockaudio, false);
  46610. if (_this.onAudioUnlocked) {
  46611. _this.onAudioUnlocked();
  46612. }
  46613. }
  46614. }, 0);
  46615. };
  46616. window.addEventListener('touchend', unlockaudio, false);
  46617. };
  46618. AudioEngine.prototype._initializeAudioContext = function () {
  46619. try {
  46620. if (this.canUseWebAudio) {
  46621. this._audioContext = new AudioContext();
  46622. // create a global volume gain node
  46623. this.masterGain = this._audioContext.createGain();
  46624. this.masterGain.gain.value = 1;
  46625. this.masterGain.connect(this._audioContext.destination);
  46626. this._audioContextInitialized = true;
  46627. }
  46628. }
  46629. catch (e) {
  46630. this.canUseWebAudio = false;
  46631. BABYLON.Tools.Error("Web Audio: " + e.message);
  46632. }
  46633. };
  46634. AudioEngine.prototype.dispose = function () {
  46635. if (this.canUseWebAudio && this._audioContextInitialized) {
  46636. if (this._connectedAnalyser) {
  46637. this._connectedAnalyser.stopDebugCanvas();
  46638. this._connectedAnalyser.dispose();
  46639. this.masterGain.disconnect();
  46640. this.masterGain.connect(this._audioContext.destination);
  46641. this._connectedAnalyser = null;
  46642. }
  46643. this.masterGain.gain.value = 1;
  46644. }
  46645. this.WarnedWebAudioUnsupported = false;
  46646. };
  46647. AudioEngine.prototype.getGlobalVolume = function () {
  46648. if (this.canUseWebAudio && this._audioContextInitialized) {
  46649. return this.masterGain.gain.value;
  46650. }
  46651. else {
  46652. return -1;
  46653. }
  46654. };
  46655. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  46656. if (this.canUseWebAudio && this._audioContextInitialized) {
  46657. this.masterGain.gain.value = newVolume;
  46658. }
  46659. };
  46660. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  46661. if (this._connectedAnalyser) {
  46662. this._connectedAnalyser.stopDebugCanvas();
  46663. }
  46664. if (this.canUseWebAudio && this._audioContextInitialized) {
  46665. this._connectedAnalyser = analyser;
  46666. this.masterGain.disconnect();
  46667. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  46668. }
  46669. };
  46670. return AudioEngine;
  46671. }());
  46672. BABYLON.AudioEngine = AudioEngine;
  46673. })(BABYLON || (BABYLON = {}));
  46674. //# sourceMappingURL=babylon.audioEngine.js.map
  46675. var BABYLON;
  46676. (function (BABYLON) {
  46677. var Sound = (function () {
  46678. /**
  46679. * Create a sound and attach it to a scene
  46680. * @param name Name of your sound
  46681. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  46682. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  46683. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  46684. */
  46685. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  46686. var _this = this;
  46687. this.autoplay = false;
  46688. this.loop = false;
  46689. this.useCustomAttenuation = false;
  46690. this.spatialSound = false;
  46691. this.refDistance = 1;
  46692. this.rolloffFactor = 1;
  46693. this.maxDistance = 100;
  46694. this.distanceModel = "linear";
  46695. this._panningModel = "equalpower";
  46696. this._playbackRate = 1;
  46697. this._streaming = false;
  46698. this._startTime = 0;
  46699. this._startOffset = 0;
  46700. this._position = BABYLON.Vector3.Zero();
  46701. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  46702. this._volume = 1;
  46703. this._isLoaded = false;
  46704. this._isReadyToPlay = false;
  46705. this.isPlaying = false;
  46706. this.isPaused = false;
  46707. this._isDirectional = false;
  46708. // Used if you'd like to create a directional sound.
  46709. // If not set, the sound will be omnidirectional
  46710. this._coneInnerAngle = 360;
  46711. this._coneOuterAngle = 360;
  46712. this._coneOuterGain = 0;
  46713. this._isOutputConnected = false;
  46714. this._urlType = "Unknown";
  46715. this.name = name;
  46716. this._scene = scene;
  46717. this._readyToPlayCallback = readyToPlayCallback;
  46718. // Default custom attenuation function is a linear attenuation
  46719. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  46720. if (currentDistance < maxDistance) {
  46721. return currentVolume * (1 - currentDistance / maxDistance);
  46722. }
  46723. else {
  46724. return 0;
  46725. }
  46726. };
  46727. if (options) {
  46728. this.autoplay = options.autoplay || false;
  46729. this.loop = options.loop || false;
  46730. // if volume === 0, we need another way to check this option
  46731. if (options.volume !== undefined) {
  46732. this._volume = options.volume;
  46733. }
  46734. this.spatialSound = options.spatialSound || false;
  46735. this.maxDistance = options.maxDistance || 100;
  46736. this.useCustomAttenuation = options.useCustomAttenuation || false;
  46737. this.rolloffFactor = options.rolloffFactor || 1;
  46738. this.refDistance = options.refDistance || 1;
  46739. this.distanceModel = options.distanceModel || "linear";
  46740. this._playbackRate = options.playbackRate || 1;
  46741. this._streaming = options.streaming || false;
  46742. }
  46743. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46744. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  46745. this._soundGain.gain.value = this._volume;
  46746. this._inputAudioNode = this._soundGain;
  46747. this._ouputAudioNode = this._soundGain;
  46748. if (this.spatialSound) {
  46749. this._createSpatialParameters();
  46750. }
  46751. this._scene.mainSoundTrack.AddSound(this);
  46752. var validParameter = true;
  46753. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  46754. if (urlOrArrayBuffer) {
  46755. if (typeof (urlOrArrayBuffer) === "string")
  46756. this._urlType = "String";
  46757. if (Array.isArray(urlOrArrayBuffer))
  46758. this._urlType = "Array";
  46759. if (urlOrArrayBuffer instanceof ArrayBuffer)
  46760. this._urlType = "ArrayBuffer";
  46761. var urls = [];
  46762. var codecSupportedFound = false;
  46763. switch (this._urlType) {
  46764. case "ArrayBuffer":
  46765. if (urlOrArrayBuffer.byteLength > 0) {
  46766. codecSupportedFound = true;
  46767. this._soundLoaded(urlOrArrayBuffer);
  46768. }
  46769. break;
  46770. case "String":
  46771. urls.push(urlOrArrayBuffer);
  46772. case "Array":
  46773. if (urls.length === 0)
  46774. urls = urlOrArrayBuffer;
  46775. // If we found a supported format, we load it immediately and stop the loop
  46776. for (var i = 0; i < urls.length; i++) {
  46777. var url = urls[i];
  46778. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  46779. codecSupportedFound = true;
  46780. }
  46781. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  46782. codecSupportedFound = true;
  46783. }
  46784. if (url.indexOf(".wav", url.length - 4) !== -1) {
  46785. codecSupportedFound = true;
  46786. }
  46787. if (url.indexOf("blob:") !== -1) {
  46788. codecSupportedFound = true;
  46789. }
  46790. if (codecSupportedFound) {
  46791. // Loading sound using XHR2
  46792. if (!this._streaming) {
  46793. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  46794. }
  46795. else {
  46796. this._htmlAudioElement = new Audio(url);
  46797. this._htmlAudioElement.controls = false;
  46798. this._htmlAudioElement.loop = this.loop;
  46799. this._htmlAudioElement.crossOrigin = "anonymous";
  46800. this._htmlAudioElement.preload = "auto";
  46801. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  46802. _this._isReadyToPlay = true;
  46803. if (_this.autoplay) {
  46804. _this.play();
  46805. }
  46806. if (_this._readyToPlayCallback) {
  46807. _this._readyToPlayCallback();
  46808. }
  46809. });
  46810. document.body.appendChild(this._htmlAudioElement);
  46811. }
  46812. break;
  46813. }
  46814. }
  46815. break;
  46816. default:
  46817. validParameter = false;
  46818. break;
  46819. }
  46820. if (!validParameter) {
  46821. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  46822. }
  46823. else {
  46824. if (!codecSupportedFound) {
  46825. this._isReadyToPlay = true;
  46826. // Simulating a ready to play event to avoid breaking code path
  46827. if (this._readyToPlayCallback) {
  46828. window.setTimeout(function () {
  46829. _this._readyToPlayCallback();
  46830. }, 1000);
  46831. }
  46832. }
  46833. }
  46834. }
  46835. }
  46836. else {
  46837. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  46838. this._scene.mainSoundTrack.AddSound(this);
  46839. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  46840. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  46841. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  46842. }
  46843. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  46844. if (this._readyToPlayCallback) {
  46845. window.setTimeout(function () {
  46846. _this._readyToPlayCallback();
  46847. }, 1000);
  46848. }
  46849. }
  46850. }
  46851. Sound.prototype.dispose = function () {
  46852. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  46853. if (this.isPlaying) {
  46854. this.stop();
  46855. }
  46856. this._isReadyToPlay = false;
  46857. if (this.soundTrackId === -1) {
  46858. this._scene.mainSoundTrack.RemoveSound(this);
  46859. }
  46860. else {
  46861. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  46862. }
  46863. if (this._soundGain) {
  46864. this._soundGain.disconnect();
  46865. this._soundGain = null;
  46866. }
  46867. if (this._soundPanner) {
  46868. this._soundPanner.disconnect();
  46869. this._soundPanner = null;
  46870. }
  46871. if (this._soundSource) {
  46872. this._soundSource.disconnect();
  46873. this._soundSource = null;
  46874. }
  46875. this._audioBuffer = null;
  46876. if (this._htmlAudioElement) {
  46877. this._htmlAudioElement.pause();
  46878. this._htmlAudioElement.src = "";
  46879. document.body.removeChild(this._htmlAudioElement);
  46880. }
  46881. if (this._connectedMesh) {
  46882. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  46883. this._connectedMesh = null;
  46884. }
  46885. }
  46886. };
  46887. Sound.prototype.isReady = function () {
  46888. return this._isReadyToPlay;
  46889. };
  46890. Sound.prototype._soundLoaded = function (audioData) {
  46891. var _this = this;
  46892. this._isLoaded = true;
  46893. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  46894. _this._audioBuffer = buffer;
  46895. _this._isReadyToPlay = true;
  46896. if (_this.autoplay) {
  46897. _this.play();
  46898. }
  46899. if (_this._readyToPlayCallback) {
  46900. _this._readyToPlayCallback();
  46901. }
  46902. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  46903. };
  46904. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  46905. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46906. this._audioBuffer = audioBuffer;
  46907. this._isReadyToPlay = true;
  46908. }
  46909. };
  46910. Sound.prototype.updateOptions = function (options) {
  46911. if (options) {
  46912. this.loop = options.loop || this.loop;
  46913. this.maxDistance = options.maxDistance || this.maxDistance;
  46914. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  46915. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  46916. this.refDistance = options.refDistance || this.refDistance;
  46917. this.distanceModel = options.distanceModel || this.distanceModel;
  46918. this._playbackRate = options.playbackRate || this._playbackRate;
  46919. this._updateSpatialParameters();
  46920. if (this.isPlaying) {
  46921. if (this._streaming) {
  46922. this._htmlAudioElement.playbackRate = this._playbackRate;
  46923. }
  46924. else {
  46925. this._soundSource.playbackRate.value = this._playbackRate;
  46926. }
  46927. }
  46928. }
  46929. };
  46930. Sound.prototype._createSpatialParameters = function () {
  46931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46932. if (this._scene.headphone) {
  46933. this._panningModel = "HRTF";
  46934. }
  46935. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  46936. this._updateSpatialParameters();
  46937. this._soundPanner.connect(this._ouputAudioNode);
  46938. this._inputAudioNode = this._soundPanner;
  46939. }
  46940. };
  46941. Sound.prototype._updateSpatialParameters = function () {
  46942. if (this.spatialSound) {
  46943. if (this.useCustomAttenuation) {
  46944. // Tricks to disable in a way embedded Web Audio attenuation
  46945. this._soundPanner.distanceModel = "linear";
  46946. this._soundPanner.maxDistance = Number.MAX_VALUE;
  46947. this._soundPanner.refDistance = 1;
  46948. this._soundPanner.rolloffFactor = 1;
  46949. this._soundPanner.panningModel = this._panningModel;
  46950. }
  46951. else {
  46952. this._soundPanner.distanceModel = this.distanceModel;
  46953. this._soundPanner.maxDistance = this.maxDistance;
  46954. this._soundPanner.refDistance = this.refDistance;
  46955. this._soundPanner.rolloffFactor = this.rolloffFactor;
  46956. this._soundPanner.panningModel = this._panningModel;
  46957. }
  46958. }
  46959. };
  46960. Sound.prototype.switchPanningModelToHRTF = function () {
  46961. this._panningModel = "HRTF";
  46962. this._switchPanningModel();
  46963. };
  46964. Sound.prototype.switchPanningModelToEqualPower = function () {
  46965. this._panningModel = "equalpower";
  46966. this._switchPanningModel();
  46967. };
  46968. Sound.prototype._switchPanningModel = function () {
  46969. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  46970. this._soundPanner.panningModel = this._panningModel;
  46971. }
  46972. };
  46973. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  46974. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46975. if (this._isOutputConnected) {
  46976. this._ouputAudioNode.disconnect();
  46977. }
  46978. this._ouputAudioNode.connect(soundTrackAudioNode);
  46979. this._isOutputConnected = true;
  46980. }
  46981. };
  46982. /**
  46983. * Transform this sound into a directional source
  46984. * @param coneInnerAngle Size of the inner cone in degree
  46985. * @param coneOuterAngle Size of the outer cone in degree
  46986. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  46987. */
  46988. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  46989. if (coneOuterAngle < coneInnerAngle) {
  46990. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  46991. return;
  46992. }
  46993. this._coneInnerAngle = coneInnerAngle;
  46994. this._coneOuterAngle = coneOuterAngle;
  46995. this._coneOuterGain = coneOuterGain;
  46996. this._isDirectional = true;
  46997. if (this.isPlaying && this.loop) {
  46998. this.stop();
  46999. this.play();
  47000. }
  47001. };
  47002. Sound.prototype.setPosition = function (newPosition) {
  47003. this._position = newPosition;
  47004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  47005. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47006. }
  47007. };
  47008. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  47009. this._localDirection = newLocalDirection;
  47010. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  47011. this._updateDirection();
  47012. }
  47013. };
  47014. Sound.prototype._updateDirection = function () {
  47015. var mat = this._connectedMesh.getWorldMatrix();
  47016. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  47017. direction.normalize();
  47018. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  47019. };
  47020. Sound.prototype.updateDistanceFromListener = function () {
  47021. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  47022. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  47023. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  47024. }
  47025. };
  47026. Sound.prototype.setAttenuationFunction = function (callback) {
  47027. this._customAttenuationFunction = callback;
  47028. };
  47029. /**
  47030. * Play the sound
  47031. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  47032. * @param offset (optional) Start the sound setting it at a specific time
  47033. */
  47034. Sound.prototype.play = function (time, offset) {
  47035. var _this = this;
  47036. if (this._isReadyToPlay && this._scene.audioEnabled) {
  47037. try {
  47038. if (this._startOffset < 0) {
  47039. time = -this._startOffset;
  47040. this._startOffset = 0;
  47041. }
  47042. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47043. if (!this._soundSource || !this._streamingSource) {
  47044. if (this.spatialSound) {
  47045. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47046. if (this._isDirectional) {
  47047. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  47048. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  47049. this._soundPanner.coneOuterGain = this._coneOuterGain;
  47050. if (this._connectedMesh) {
  47051. this._updateDirection();
  47052. }
  47053. else {
  47054. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  47055. }
  47056. }
  47057. }
  47058. }
  47059. if (this._streaming) {
  47060. if (!this._streamingSource) {
  47061. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  47062. this._htmlAudioElement.onended = function () { _this._onended(); };
  47063. this._htmlAudioElement.playbackRate = this._playbackRate;
  47064. }
  47065. this._streamingSource.disconnect();
  47066. this._streamingSource.connect(this._inputAudioNode);
  47067. this._htmlAudioElement.play();
  47068. }
  47069. else {
  47070. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  47071. this._soundSource.buffer = this._audioBuffer;
  47072. this._soundSource.connect(this._inputAudioNode);
  47073. this._soundSource.loop = this.loop;
  47074. this._soundSource.playbackRate.value = this._playbackRate;
  47075. this._soundSource.onended = function () { _this._onended(); };
  47076. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  47077. }
  47078. this._startTime = startTime;
  47079. this.isPlaying = true;
  47080. this.isPaused = false;
  47081. }
  47082. catch (ex) {
  47083. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  47084. }
  47085. }
  47086. };
  47087. Sound.prototype._onended = function () {
  47088. this.isPlaying = false;
  47089. if (this.onended) {
  47090. this.onended();
  47091. }
  47092. };
  47093. /**
  47094. * Stop the sound
  47095. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  47096. */
  47097. Sound.prototype.stop = function (time) {
  47098. if (this.isPlaying) {
  47099. if (this._streaming) {
  47100. this._htmlAudioElement.pause();
  47101. // Test needed for Firefox or it will generate an Invalid State Error
  47102. if (this._htmlAudioElement.currentTime > 0) {
  47103. this._htmlAudioElement.currentTime = 0;
  47104. }
  47105. }
  47106. else {
  47107. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47108. this._soundSource.stop(stopTime);
  47109. this._soundSource.onended = null;
  47110. if (!this.isPaused) {
  47111. this._startOffset = 0;
  47112. }
  47113. }
  47114. this.isPlaying = false;
  47115. }
  47116. };
  47117. Sound.prototype.pause = function () {
  47118. if (this.isPlaying) {
  47119. this.isPaused = true;
  47120. if (this._streaming) {
  47121. this._htmlAudioElement.pause();
  47122. }
  47123. else {
  47124. this.stop(0);
  47125. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  47126. }
  47127. }
  47128. };
  47129. Sound.prototype.setVolume = function (newVolume, time) {
  47130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47131. if (time) {
  47132. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  47133. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  47134. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  47135. }
  47136. else {
  47137. this._soundGain.gain.value = newVolume;
  47138. }
  47139. }
  47140. this._volume = newVolume;
  47141. };
  47142. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  47143. this._playbackRate = newPlaybackRate;
  47144. if (this.isPlaying) {
  47145. if (this._streaming) {
  47146. this._htmlAudioElement.playbackRate = this._playbackRate;
  47147. }
  47148. else {
  47149. this._soundSource.playbackRate.value = this._playbackRate;
  47150. }
  47151. }
  47152. };
  47153. Sound.prototype.getVolume = function () {
  47154. return this._volume;
  47155. };
  47156. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  47157. var _this = this;
  47158. if (this._connectedMesh) {
  47159. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47160. this._registerFunc = null;
  47161. }
  47162. this._connectedMesh = meshToConnectTo;
  47163. if (!this.spatialSound) {
  47164. this.spatialSound = true;
  47165. this._createSpatialParameters();
  47166. if (this.isPlaying && this.loop) {
  47167. this.stop();
  47168. this.play();
  47169. }
  47170. }
  47171. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  47172. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  47173. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  47174. };
  47175. Sound.prototype.detachFromMesh = function () {
  47176. if (this._connectedMesh) {
  47177. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47178. this._registerFunc = null;
  47179. this._connectedMesh = null;
  47180. }
  47181. };
  47182. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  47183. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  47184. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  47185. this._updateDirection();
  47186. }
  47187. };
  47188. Sound.prototype.clone = function () {
  47189. var _this = this;
  47190. if (!this._streaming) {
  47191. var setBufferAndRun = function () {
  47192. if (_this._isReadyToPlay) {
  47193. clonedSound._audioBuffer = _this.getAudioBuffer();
  47194. clonedSound._isReadyToPlay = true;
  47195. if (clonedSound.autoplay) {
  47196. clonedSound.play();
  47197. }
  47198. }
  47199. else {
  47200. window.setTimeout(setBufferAndRun, 300);
  47201. }
  47202. };
  47203. var currentOptions = {
  47204. autoplay: this.autoplay, loop: this.loop,
  47205. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  47206. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  47207. refDistance: this.refDistance, distanceModel: this.distanceModel
  47208. };
  47209. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  47210. if (this.useCustomAttenuation) {
  47211. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  47212. }
  47213. clonedSound.setPosition(this._position);
  47214. clonedSound.setPlaybackRate(this._playbackRate);
  47215. setBufferAndRun();
  47216. return clonedSound;
  47217. }
  47218. else {
  47219. return null;
  47220. }
  47221. };
  47222. Sound.prototype.getAudioBuffer = function () {
  47223. return this._audioBuffer;
  47224. };
  47225. Sound.prototype.serialize = function () {
  47226. var serializationObject = {
  47227. name: this.name,
  47228. url: this.name,
  47229. autoplay: this.autoplay,
  47230. loop: this.loop,
  47231. volume: this._volume,
  47232. spatialSound: this.spatialSound,
  47233. maxDistance: this.maxDistance,
  47234. rolloffFactor: this.rolloffFactor,
  47235. refDistance: this.refDistance,
  47236. distanceModel: this.distanceModel,
  47237. playbackRate: this._playbackRate,
  47238. panningModel: this._panningModel,
  47239. soundTrackId: this.soundTrackId
  47240. };
  47241. if (this.spatialSound) {
  47242. if (this._connectedMesh)
  47243. serializationObject.connectedMeshId = this._connectedMesh.id;
  47244. serializationObject.position = this._position.asArray();
  47245. serializationObject.refDistance = this.refDistance;
  47246. serializationObject.distanceModel = this.distanceModel;
  47247. serializationObject.isDirectional = this._isDirectional;
  47248. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  47249. serializationObject.coneInnerAngle = this._coneInnerAngle;
  47250. serializationObject.coneOuterAngle = this._coneOuterAngle;
  47251. serializationObject.coneOuterGain = this._coneOuterGain;
  47252. }
  47253. return serializationObject;
  47254. };
  47255. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  47256. var soundName = parsedSound.name;
  47257. var soundUrl;
  47258. if (parsedSound.url) {
  47259. soundUrl = rootUrl + parsedSound.url;
  47260. }
  47261. else {
  47262. soundUrl = rootUrl + soundName;
  47263. }
  47264. var options = {
  47265. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  47266. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  47267. rolloffFactor: parsedSound.rolloffFactor,
  47268. refDistance: parsedSound.refDistance,
  47269. distanceModel: parsedSound.distanceModel,
  47270. playbackRate: parsedSound.playbackRate
  47271. };
  47272. var newSound;
  47273. if (!sourceSound) {
  47274. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  47275. scene._addPendingData(newSound);
  47276. }
  47277. else {
  47278. var setBufferAndRun = function () {
  47279. if (sourceSound._isReadyToPlay) {
  47280. newSound._audioBuffer = sourceSound.getAudioBuffer();
  47281. newSound._isReadyToPlay = true;
  47282. if (newSound.autoplay) {
  47283. newSound.play();
  47284. }
  47285. }
  47286. else {
  47287. window.setTimeout(setBufferAndRun, 300);
  47288. }
  47289. };
  47290. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  47291. setBufferAndRun();
  47292. }
  47293. if (parsedSound.position) {
  47294. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  47295. newSound.setPosition(soundPosition);
  47296. }
  47297. if (parsedSound.isDirectional) {
  47298. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  47299. if (parsedSound.localDirectionToMesh) {
  47300. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  47301. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  47302. }
  47303. }
  47304. if (parsedSound.connectedMeshId) {
  47305. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  47306. if (connectedMesh) {
  47307. newSound.attachToMesh(connectedMesh);
  47308. }
  47309. }
  47310. return newSound;
  47311. };
  47312. return Sound;
  47313. }());
  47314. BABYLON.Sound = Sound;
  47315. })(BABYLON || (BABYLON = {}));
  47316. //# sourceMappingURL=babylon.sound.js.map
  47317. var BABYLON;
  47318. (function (BABYLON) {
  47319. var SoundTrack = (function () {
  47320. function SoundTrack(scene, options) {
  47321. this.id = -1;
  47322. this._isMainTrack = false;
  47323. this._isInitialized = false;
  47324. this._scene = scene;
  47325. this.soundCollection = new Array();
  47326. this._options = options;
  47327. if (!this._isMainTrack) {
  47328. this._scene.soundTracks.push(this);
  47329. this.id = this._scene.soundTracks.length - 1;
  47330. }
  47331. }
  47332. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  47333. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47334. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  47335. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  47336. if (this._options) {
  47337. if (this._options.volume) {
  47338. this._outputAudioNode.gain.value = this._options.volume;
  47339. }
  47340. if (this._options.mainTrack) {
  47341. this._isMainTrack = this._options.mainTrack;
  47342. }
  47343. }
  47344. this._isInitialized = true;
  47345. }
  47346. };
  47347. SoundTrack.prototype.dispose = function () {
  47348. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47349. if (this._connectedAnalyser) {
  47350. this._connectedAnalyser.stopDebugCanvas();
  47351. }
  47352. while (this.soundCollection.length) {
  47353. this.soundCollection[0].dispose();
  47354. }
  47355. if (this._outputAudioNode) {
  47356. this._outputAudioNode.disconnect();
  47357. }
  47358. this._outputAudioNode = null;
  47359. }
  47360. };
  47361. SoundTrack.prototype.AddSound = function (sound) {
  47362. if (!this._isInitialized) {
  47363. this._initializeSoundTrackAudioGraph();
  47364. }
  47365. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47366. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  47367. }
  47368. if (sound.soundTrackId) {
  47369. if (sound.soundTrackId === -1) {
  47370. this._scene.mainSoundTrack.RemoveSound(sound);
  47371. }
  47372. else {
  47373. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  47374. }
  47375. }
  47376. this.soundCollection.push(sound);
  47377. sound.soundTrackId = this.id;
  47378. };
  47379. SoundTrack.prototype.RemoveSound = function (sound) {
  47380. var index = this.soundCollection.indexOf(sound);
  47381. if (index !== -1) {
  47382. this.soundCollection.splice(index, 1);
  47383. }
  47384. };
  47385. SoundTrack.prototype.setVolume = function (newVolume) {
  47386. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47387. this._outputAudioNode.gain.value = newVolume;
  47388. }
  47389. };
  47390. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  47391. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47392. for (var i = 0; i < this.soundCollection.length; i++) {
  47393. this.soundCollection[i].switchPanningModelToHRTF();
  47394. }
  47395. }
  47396. };
  47397. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  47398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47399. for (var i = 0; i < this.soundCollection.length; i++) {
  47400. this.soundCollection[i].switchPanningModelToEqualPower();
  47401. }
  47402. }
  47403. };
  47404. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  47405. if (this._connectedAnalyser) {
  47406. this._connectedAnalyser.stopDebugCanvas();
  47407. }
  47408. this._connectedAnalyser = analyser;
  47409. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47410. this._outputAudioNode.disconnect();
  47411. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  47412. }
  47413. };
  47414. return SoundTrack;
  47415. }());
  47416. BABYLON.SoundTrack = SoundTrack;
  47417. })(BABYLON || (BABYLON = {}));
  47418. //# sourceMappingURL=babylon.soundtrack.js.map
  47419. var BABYLON;
  47420. (function (BABYLON) {
  47421. var Analyser = (function () {
  47422. function Analyser(scene) {
  47423. this.SMOOTHING = 0.75;
  47424. this.FFT_SIZE = 512;
  47425. this.BARGRAPHAMPLITUDE = 256;
  47426. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47427. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47428. this._scene = scene;
  47429. this._audioEngine = BABYLON.Engine.audioEngine;
  47430. if (this._audioEngine.canUseWebAudio) {
  47431. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47432. this._webAudioAnalyser.minDecibels = -140;
  47433. this._webAudioAnalyser.maxDecibels = 0;
  47434. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47435. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47436. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47437. }
  47438. }
  47439. Analyser.prototype.getFrequencyBinCount = function () {
  47440. if (this._audioEngine.canUseWebAudio) {
  47441. return this._webAudioAnalyser.frequencyBinCount;
  47442. }
  47443. else {
  47444. return 0;
  47445. }
  47446. };
  47447. Analyser.prototype.getByteFrequencyData = function () {
  47448. if (this._audioEngine.canUseWebAudio) {
  47449. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47450. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47451. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47452. }
  47453. return this._byteFreqs;
  47454. };
  47455. Analyser.prototype.getByteTimeDomainData = function () {
  47456. if (this._audioEngine.canUseWebAudio) {
  47457. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47458. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47459. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47460. }
  47461. return this._byteTime;
  47462. };
  47463. Analyser.prototype.getFloatFrequencyData = function () {
  47464. if (this._audioEngine.canUseWebAudio) {
  47465. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47466. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47467. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47468. }
  47469. return this._floatFreqs;
  47470. };
  47471. Analyser.prototype.drawDebugCanvas = function () {
  47472. var _this = this;
  47473. if (this._audioEngine.canUseWebAudio) {
  47474. if (!this._debugCanvas) {
  47475. this._debugCanvas = document.createElement("canvas");
  47476. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47477. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47478. this._debugCanvas.style.position = "absolute";
  47479. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47480. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47481. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47482. document.body.appendChild(this._debugCanvas);
  47483. this._registerFunc = function () {
  47484. _this.drawDebugCanvas();
  47485. };
  47486. this._scene.registerBeforeRender(this._registerFunc);
  47487. }
  47488. if (this._registerFunc) {
  47489. var workingArray = this.getByteFrequencyData();
  47490. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47491. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47492. // Draw the frequency domain chart.
  47493. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47494. var value = workingArray[i];
  47495. var percent = value / this.BARGRAPHAMPLITUDE;
  47496. var height = this.DEBUGCANVASSIZE.height * percent;
  47497. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47498. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47499. var hue = i / this.getFrequencyBinCount() * 360;
  47500. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47501. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47502. }
  47503. }
  47504. }
  47505. };
  47506. Analyser.prototype.stopDebugCanvas = function () {
  47507. if (this._debugCanvas) {
  47508. this._scene.unregisterBeforeRender(this._registerFunc);
  47509. this._registerFunc = null;
  47510. document.body.removeChild(this._debugCanvas);
  47511. this._debugCanvas = null;
  47512. this._debugCanvasContext = null;
  47513. }
  47514. };
  47515. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47516. if (this._audioEngine.canUseWebAudio) {
  47517. inputAudioNode.connect(this._webAudioAnalyser);
  47518. this._webAudioAnalyser.connect(outputAudioNode);
  47519. }
  47520. };
  47521. Analyser.prototype.dispose = function () {
  47522. if (this._audioEngine.canUseWebAudio) {
  47523. this._webAudioAnalyser.disconnect();
  47524. }
  47525. };
  47526. return Analyser;
  47527. }());
  47528. BABYLON.Analyser = Analyser;
  47529. })(BABYLON || (BABYLON = {}));
  47530. //# sourceMappingURL=babylon.analyser.js.map
  47531. var BABYLON;
  47532. (function (BABYLON) {
  47533. var CubeTexture = (function (_super) {
  47534. __extends(CubeTexture, _super);
  47535. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  47536. if (onLoad === void 0) { onLoad = null; }
  47537. if (onError === void 0) { onError = null; }
  47538. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  47539. if (prefiltered === void 0) { prefiltered = false; }
  47540. if (forcedExtension === void 0) { forcedExtension = null; }
  47541. var _this = _super.call(this, scene) || this;
  47542. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  47543. _this.name = rootUrl;
  47544. _this.url = rootUrl;
  47545. _this._noMipmap = noMipmap;
  47546. _this.hasAlpha = false;
  47547. _this._format = format;
  47548. _this._prefiltered = prefiltered;
  47549. _this.isCube = true;
  47550. _this._textureMatrix = BABYLON.Matrix.Identity();
  47551. if (prefiltered) {
  47552. _this.gammaSpace = false;
  47553. }
  47554. if (!rootUrl && !files) {
  47555. return _this;
  47556. }
  47557. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  47558. if (!files) {
  47559. if (!extensions) {
  47560. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  47561. }
  47562. files = [];
  47563. for (var index = 0; index < extensions.length; index++) {
  47564. files.push(rootUrl + extensions[index]);
  47565. }
  47566. _this._extensions = extensions;
  47567. }
  47568. _this._files = files;
  47569. if (!_this._texture) {
  47570. if (!scene.useDelayedTextureLoading) {
  47571. if (prefiltered) {
  47572. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  47573. }
  47574. else {
  47575. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  47576. }
  47577. }
  47578. else {
  47579. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  47580. }
  47581. }
  47582. else if (onLoad) {
  47583. if (_this._texture.isReady) {
  47584. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  47585. }
  47586. else {
  47587. _this._texture.onLoadedObservable.add(onLoad);
  47588. }
  47589. }
  47590. return _this;
  47591. }
  47592. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  47593. return new CubeTexture("", scene, null, noMipmap, files);
  47594. };
  47595. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  47596. if (forcedExtension === void 0) { forcedExtension = null; }
  47597. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  47598. };
  47599. // Methods
  47600. CubeTexture.prototype.delayLoad = function () {
  47601. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  47602. return;
  47603. }
  47604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  47605. this._texture = this._getFromCache(this.url, this._noMipmap);
  47606. if (!this._texture) {
  47607. if (this._prefiltered) {
  47608. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  47609. }
  47610. else {
  47611. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  47612. }
  47613. }
  47614. };
  47615. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  47616. return this._textureMatrix;
  47617. };
  47618. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  47619. this._textureMatrix = value;
  47620. };
  47621. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  47622. var texture = BABYLON.SerializationHelper.Parse(function () {
  47623. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  47624. }, parsedTexture, scene);
  47625. // Animations
  47626. if (parsedTexture.animations) {
  47627. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  47628. var parsedAnimation = parsedTexture.animations[animationIndex];
  47629. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  47630. }
  47631. }
  47632. return texture;
  47633. };
  47634. CubeTexture.prototype.clone = function () {
  47635. var _this = this;
  47636. return BABYLON.SerializationHelper.Clone(function () {
  47637. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  47638. }, this);
  47639. };
  47640. return CubeTexture;
  47641. }(BABYLON.BaseTexture));
  47642. BABYLON.CubeTexture = CubeTexture;
  47643. })(BABYLON || (BABYLON = {}));
  47644. //# sourceMappingURL=babylon.cubeTexture.js.map
  47645. var BABYLON;
  47646. (function (BABYLON) {
  47647. var RenderTargetTexture = (function (_super) {
  47648. __extends(RenderTargetTexture, _super);
  47649. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  47650. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  47651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47652. if (isCube === void 0) { isCube = false; }
  47653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47654. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  47655. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  47656. if (isMulti === void 0) { isMulti = false; }
  47657. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47658. _this.isCube = isCube;
  47659. /**
  47660. * Use this list to define the list of mesh you want to render.
  47661. */
  47662. _this.renderList = new Array();
  47663. _this.renderParticles = true;
  47664. _this.renderSprites = false;
  47665. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  47666. _this.ignoreCameraViewport = false;
  47667. // Events
  47668. /**
  47669. * An event triggered when the texture is unbind.
  47670. * @type {BABYLON.Observable}
  47671. */
  47672. _this.onBeforeBindObservable = new BABYLON.Observable();
  47673. /**
  47674. * An event triggered when the texture is unbind.
  47675. * @type {BABYLON.Observable}
  47676. */
  47677. _this.onAfterUnbindObservable = new BABYLON.Observable();
  47678. /**
  47679. * An event triggered before rendering the texture
  47680. * @type {BABYLON.Observable}
  47681. */
  47682. _this.onBeforeRenderObservable = new BABYLON.Observable();
  47683. /**
  47684. * An event triggered after rendering the texture
  47685. * @type {BABYLON.Observable}
  47686. */
  47687. _this.onAfterRenderObservable = new BABYLON.Observable();
  47688. /**
  47689. * An event triggered after the texture clear
  47690. * @type {BABYLON.Observable}
  47691. */
  47692. _this.onClearObservable = new BABYLON.Observable();
  47693. _this._currentRefreshId = -1;
  47694. _this._refreshRate = 1;
  47695. _this._samples = 1;
  47696. scene = _this.getScene();
  47697. _this.name = name;
  47698. _this.isRenderTarget = true;
  47699. _this._size = size;
  47700. _this._generateMipMaps = generateMipMaps;
  47701. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  47702. // Rendering groups
  47703. _this._renderingManager = new BABYLON.RenderingManager(scene);
  47704. if (isMulti) {
  47705. return _this;
  47706. }
  47707. _this._renderTargetOptions = {
  47708. generateMipMaps: generateMipMaps,
  47709. type: type,
  47710. samplingMode: samplingMode,
  47711. generateDepthBuffer: generateDepthBuffer,
  47712. generateStencilBuffer: generateStencilBuffer
  47713. };
  47714. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  47715. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47716. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47717. }
  47718. if (isCube) {
  47719. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  47720. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  47721. _this._textureMatrix = BABYLON.Matrix.Identity();
  47722. }
  47723. else {
  47724. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  47725. }
  47726. return _this;
  47727. }
  47728. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  47729. get: function () {
  47730. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  47736. get: function () {
  47737. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  47743. get: function () {
  47744. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  47750. set: function (callback) {
  47751. if (this._onAfterUnbindObserver) {
  47752. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  47753. }
  47754. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  47755. },
  47756. enumerable: true,
  47757. configurable: true
  47758. });
  47759. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  47760. set: function (callback) {
  47761. if (this._onBeforeRenderObserver) {
  47762. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47763. }
  47764. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  47770. set: function (callback) {
  47771. if (this._onAfterRenderObserver) {
  47772. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47773. }
  47774. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47775. },
  47776. enumerable: true,
  47777. configurable: true
  47778. });
  47779. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  47780. set: function (callback) {
  47781. if (this._onClearObserver) {
  47782. this.onClearObservable.remove(this._onClearObserver);
  47783. }
  47784. this._onClearObserver = this.onClearObservable.add(callback);
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  47790. get: function () {
  47791. return this._renderTargetOptions;
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  47797. get: function () {
  47798. return this._samples;
  47799. },
  47800. set: function (value) {
  47801. if (this._samples === value) {
  47802. return;
  47803. }
  47804. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  47805. },
  47806. enumerable: true,
  47807. configurable: true
  47808. });
  47809. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  47810. this._currentRefreshId = -1;
  47811. };
  47812. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  47813. get: function () {
  47814. return this._refreshRate;
  47815. },
  47816. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  47817. set: function (value) {
  47818. this._refreshRate = value;
  47819. this.resetRefreshCounter();
  47820. },
  47821. enumerable: true,
  47822. configurable: true
  47823. });
  47824. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  47825. if (!this._postProcessManager) {
  47826. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  47827. this._postProcesses = new Array();
  47828. }
  47829. this._postProcesses.push(postProcess);
  47830. this._postProcesses[0].autoClear = false;
  47831. };
  47832. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  47833. if (!this._postProcesses) {
  47834. return;
  47835. }
  47836. if (dispose) {
  47837. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  47838. var postProcess = _a[_i];
  47839. postProcess.dispose();
  47840. postProcess = null;
  47841. }
  47842. }
  47843. this._postProcesses = [];
  47844. };
  47845. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  47846. if (!this._postProcesses) {
  47847. return;
  47848. }
  47849. var index = this._postProcesses.indexOf(postProcess);
  47850. if (index === -1) {
  47851. return;
  47852. }
  47853. this._postProcesses.splice(index, 1);
  47854. if (this._postProcesses.length > 0) {
  47855. this._postProcesses[0].autoClear = false;
  47856. }
  47857. };
  47858. RenderTargetTexture.prototype._shouldRender = function () {
  47859. if (this._currentRefreshId === -1) {
  47860. this._currentRefreshId = 1;
  47861. return true;
  47862. }
  47863. if (this.refreshRate === this._currentRefreshId) {
  47864. this._currentRefreshId = 1;
  47865. return true;
  47866. }
  47867. this._currentRefreshId++;
  47868. return false;
  47869. };
  47870. RenderTargetTexture.prototype.getRenderSize = function () {
  47871. return this._size;
  47872. };
  47873. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  47874. get: function () {
  47875. return true;
  47876. },
  47877. enumerable: true,
  47878. configurable: true
  47879. });
  47880. RenderTargetTexture.prototype.scale = function (ratio) {
  47881. var newSize = this._size * ratio;
  47882. this.resize(newSize);
  47883. };
  47884. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  47885. if (this.isCube) {
  47886. return this._textureMatrix;
  47887. }
  47888. return _super.prototype.getReflectionTextureMatrix.call(this);
  47889. };
  47890. RenderTargetTexture.prototype.resize = function (size) {
  47891. this.releaseInternalTexture();
  47892. if (this.isCube) {
  47893. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  47894. }
  47895. else {
  47896. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  47897. }
  47898. this._size = size;
  47899. };
  47900. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  47901. var scene = this.getScene();
  47902. var engine = scene.getEngine();
  47903. if (this.useCameraPostProcesses !== undefined) {
  47904. useCameraPostProcess = this.useCameraPostProcesses;
  47905. }
  47906. if (this._waitingRenderList) {
  47907. this.renderList = [];
  47908. for (var index = 0; index < this._waitingRenderList.length; index++) {
  47909. var id = this._waitingRenderList[index];
  47910. this.renderList.push(scene.getMeshByID(id));
  47911. }
  47912. delete this._waitingRenderList;
  47913. }
  47914. // Is predicate defined?
  47915. if (this.renderListPredicate) {
  47916. this.renderList.splice(0); // Clear previous renderList
  47917. var sceneMeshes = this.getScene().meshes;
  47918. for (var index = 0; index < sceneMeshes.length; index++) {
  47919. var mesh = sceneMeshes[index];
  47920. if (this.renderListPredicate(mesh)) {
  47921. this.renderList.push(mesh);
  47922. }
  47923. }
  47924. }
  47925. if (this.renderList && this.renderList.length === 0) {
  47926. return;
  47927. }
  47928. this.onBeforeBindObservable.notifyObservers(this);
  47929. // Set custom projection.
  47930. // Needs to be before binding to prevent changing the aspect ratio.
  47931. var camera;
  47932. if (this.activeCamera) {
  47933. camera = this.activeCamera;
  47934. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  47935. if (this.activeCamera !== scene.activeCamera) {
  47936. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  47937. }
  47938. }
  47939. else {
  47940. camera = scene.activeCamera;
  47941. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  47942. }
  47943. // Prepare renderingManager
  47944. this._renderingManager.reset();
  47945. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  47946. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  47947. var sceneRenderId = scene.getRenderId();
  47948. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  47949. var mesh = currentRenderList[meshIndex];
  47950. if (mesh) {
  47951. if (!mesh.isReady()) {
  47952. // Reset _currentRefreshId
  47953. this.resetRefreshCounter();
  47954. continue;
  47955. }
  47956. mesh._preActivateForIntermediateRendering(sceneRenderId);
  47957. var isMasked = void 0;
  47958. if (!this.renderList) {
  47959. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  47960. }
  47961. else {
  47962. isMasked = false;
  47963. }
  47964. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  47965. mesh._activate(sceneRenderId);
  47966. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  47967. var subMesh = mesh.subMeshes[subIndex];
  47968. scene._activeIndices.addCount(subMesh.indexCount, false);
  47969. this._renderingManager.dispatch(subMesh);
  47970. }
  47971. }
  47972. }
  47973. }
  47974. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  47975. var particleSystem = scene.particleSystems[particleIndex];
  47976. var emitter = particleSystem.emitter;
  47977. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  47978. continue;
  47979. }
  47980. if (currentRenderList.indexOf(emitter) >= 0) {
  47981. this._renderingManager.dispatchParticles(particleSystem);
  47982. }
  47983. }
  47984. if (this.isCube) {
  47985. for (var face = 0; face < 6; face++) {
  47986. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  47987. scene.incrementRenderId();
  47988. scene.resetCachedMaterial();
  47989. }
  47990. }
  47991. else {
  47992. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  47993. }
  47994. this.onAfterUnbindObservable.notifyObservers(this);
  47995. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  47996. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  47997. }
  47998. engine.setViewport(scene.activeCamera.viewport);
  47999. scene.resetCachedMaterial();
  48000. };
  48001. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  48002. var _this = this;
  48003. var scene = this.getScene();
  48004. var engine = scene.getEngine();
  48005. // Bind
  48006. if (this._postProcessManager) {
  48007. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  48008. }
  48009. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  48010. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  48011. }
  48012. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  48013. // Clear
  48014. if (this.onClearObservable.hasObservers()) {
  48015. this.onClearObservable.notifyObservers(engine);
  48016. }
  48017. else {
  48018. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  48019. }
  48020. if (!this._doNotChangeAspectRatio) {
  48021. scene.updateTransformMatrix(true);
  48022. }
  48023. // Render
  48024. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  48025. if (this._postProcessManager) {
  48026. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  48027. }
  48028. else if (useCameraPostProcess) {
  48029. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  48030. }
  48031. if (!this._doNotChangeAspectRatio) {
  48032. scene.updateTransformMatrix(true);
  48033. }
  48034. // Dump ?
  48035. if (dumpForDebug) {
  48036. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  48037. }
  48038. // Unbind
  48039. if (!this.isCube || faceIndex === 5) {
  48040. if (this.isCube) {
  48041. if (faceIndex === 5) {
  48042. engine.generateMipMapsForCubemap(this._texture);
  48043. }
  48044. }
  48045. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  48046. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  48047. });
  48048. }
  48049. else {
  48050. this.onAfterRenderObservable.notifyObservers(faceIndex);
  48051. }
  48052. };
  48053. /**
  48054. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  48055. * This allowed control for front to back rendering or reversly depending of the special needs.
  48056. *
  48057. * @param renderingGroupId The rendering group id corresponding to its index
  48058. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  48059. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  48060. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  48061. */
  48062. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  48063. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  48064. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  48065. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  48066. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  48067. };
  48068. /**
  48069. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  48070. *
  48071. * @param renderingGroupId The rendering group id corresponding to its index
  48072. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  48073. */
  48074. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  48075. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  48076. };
  48077. RenderTargetTexture.prototype.clone = function () {
  48078. var textureSize = this.getSize();
  48079. 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);
  48080. // Base texture
  48081. newTexture.hasAlpha = this.hasAlpha;
  48082. newTexture.level = this.level;
  48083. // RenderTarget Texture
  48084. newTexture.coordinatesMode = this.coordinatesMode;
  48085. newTexture.renderList = this.renderList.slice(0);
  48086. return newTexture;
  48087. };
  48088. RenderTargetTexture.prototype.serialize = function () {
  48089. if (!this.name) {
  48090. return null;
  48091. }
  48092. var serializationObject = _super.prototype.serialize.call(this);
  48093. serializationObject.renderTargetSize = this.getRenderSize();
  48094. serializationObject.renderList = [];
  48095. for (var index = 0; index < this.renderList.length; index++) {
  48096. serializationObject.renderList.push(this.renderList[index].id);
  48097. }
  48098. return serializationObject;
  48099. };
  48100. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  48101. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  48102. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  48103. };
  48104. RenderTargetTexture.prototype.dispose = function () {
  48105. if (this._postProcessManager) {
  48106. this._postProcessManager.dispose();
  48107. this._postProcessManager = null;
  48108. }
  48109. this.clearPostProcesses(true);
  48110. this.renderList = null;
  48111. // Remove from custom render targets
  48112. var scene = this.getScene();
  48113. var index = scene.customRenderTargets.indexOf(this);
  48114. if (index >= 0) {
  48115. scene.customRenderTargets.splice(index, 1);
  48116. }
  48117. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  48118. var camera = _a[_i];
  48119. index = camera.customRenderTargets.indexOf(this);
  48120. if (index >= 0) {
  48121. camera.customRenderTargets.splice(index, 1);
  48122. }
  48123. }
  48124. _super.prototype.dispose.call(this);
  48125. };
  48126. RenderTargetTexture.prototype._rebuild = function () {
  48127. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  48128. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  48129. }
  48130. if (this._postProcessManager) {
  48131. this._postProcessManager._rebuild();
  48132. }
  48133. };
  48134. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  48135. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  48136. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  48137. return RenderTargetTexture;
  48138. }(BABYLON.Texture));
  48139. BABYLON.RenderTargetTexture = RenderTargetTexture;
  48140. })(BABYLON || (BABYLON = {}));
  48141. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  48142. var BABYLON;
  48143. (function (BABYLON) {
  48144. ;
  48145. var MultiRenderTarget = (function (_super) {
  48146. __extends(MultiRenderTarget, _super);
  48147. function MultiRenderTarget(name, size, count, scene, options) {
  48148. var _this = this;
  48149. options = options || {};
  48150. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  48151. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  48152. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  48153. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  48154. if (!_this.isSupported) {
  48155. _this.dispose();
  48156. return;
  48157. }
  48158. var types = [];
  48159. var samplingModes = [];
  48160. for (var i = 0; i < count; i++) {
  48161. if (options.types && options.types[i]) {
  48162. types.push(options.types[i]);
  48163. }
  48164. else {
  48165. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  48166. }
  48167. if (options.samplingModes && options.samplingModes[i]) {
  48168. samplingModes.push(options.samplingModes[i]);
  48169. }
  48170. else {
  48171. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48172. }
  48173. }
  48174. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  48175. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  48176. _this._count = count;
  48177. _this._size = size;
  48178. _this._multiRenderTargetOptions = {
  48179. samplingModes: samplingModes,
  48180. generateMipMaps: generateMipMaps,
  48181. generateDepthBuffer: generateDepthBuffer,
  48182. generateStencilBuffer: generateStencilBuffer,
  48183. generateDepthTexture: generateDepthTexture,
  48184. types: types,
  48185. textureCount: count
  48186. };
  48187. _this._createInternalTextures();
  48188. _this._createTextures();
  48189. return _this;
  48190. }
  48191. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  48192. get: function () {
  48193. var engine = this.getScene().getEngine();
  48194. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  48195. },
  48196. enumerable: true,
  48197. configurable: true
  48198. });
  48199. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  48200. get: function () {
  48201. return this._textures;
  48202. },
  48203. enumerable: true,
  48204. configurable: true
  48205. });
  48206. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  48207. get: function () {
  48208. return this._textures[this._textures.length - 1];
  48209. },
  48210. enumerable: true,
  48211. configurable: true
  48212. });
  48213. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  48214. set: function (wrap) {
  48215. if (this._textures) {
  48216. for (var i = 0; i < this._textures.length; i++) {
  48217. this._textures[i].wrapU = wrap;
  48218. }
  48219. }
  48220. },
  48221. enumerable: true,
  48222. configurable: true
  48223. });
  48224. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  48225. set: function (wrap) {
  48226. if (this._textures) {
  48227. for (var i = 0; i < this._textures.length; i++) {
  48228. this._textures[i].wrapV = wrap;
  48229. }
  48230. }
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. MultiRenderTarget.prototype._rebuild = function () {
  48236. this.releaseInternalTextures();
  48237. this._createInternalTextures();
  48238. for (var i = 0; i < this._internalTextures.length; i++) {
  48239. var texture = this._textures[i];
  48240. texture._texture = this._internalTextures[i];
  48241. }
  48242. // Keeps references to frame buffer and stencil/depth buffer
  48243. this._texture = this._internalTextures[0];
  48244. };
  48245. MultiRenderTarget.prototype._createInternalTextures = function () {
  48246. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  48247. };
  48248. MultiRenderTarget.prototype._createTextures = function () {
  48249. this._textures = [];
  48250. for (var i = 0; i < this._internalTextures.length; i++) {
  48251. var texture = new BABYLON.Texture(null, this.getScene());
  48252. texture._texture = this._internalTextures[i];
  48253. this._textures.push(texture);
  48254. }
  48255. // Keeps references to frame buffer and stencil/depth buffer
  48256. this._texture = this._internalTextures[0];
  48257. };
  48258. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  48259. get: function () {
  48260. return this._samples;
  48261. },
  48262. set: function (value) {
  48263. if (this._samples === value) {
  48264. return;
  48265. }
  48266. for (var i = 0; i < this._internalTextures.length; i++) {
  48267. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  48268. }
  48269. },
  48270. enumerable: true,
  48271. configurable: true
  48272. });
  48273. MultiRenderTarget.prototype.resize = function (size) {
  48274. this.releaseInternalTextures();
  48275. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  48276. this._createInternalTextures();
  48277. };
  48278. MultiRenderTarget.prototype.dispose = function () {
  48279. this.releaseInternalTextures();
  48280. _super.prototype.dispose.call(this);
  48281. };
  48282. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  48283. if (!this._internalTextures) {
  48284. return;
  48285. }
  48286. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  48287. if (this._internalTextures[i] !== undefined) {
  48288. this._internalTextures[i].dispose();
  48289. this._internalTextures.splice(i, 1);
  48290. }
  48291. }
  48292. };
  48293. return MultiRenderTarget;
  48294. }(BABYLON.RenderTargetTexture));
  48295. BABYLON.MultiRenderTarget = MultiRenderTarget;
  48296. })(BABYLON || (BABYLON = {}));
  48297. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  48298. /// <reference path="babylon.renderTargetTexture.ts" />
  48299. var BABYLON;
  48300. (function (BABYLON) {
  48301. var MirrorTexture = (function (_super) {
  48302. __extends(MirrorTexture, _super);
  48303. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  48304. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48306. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  48307. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  48308. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  48309. _this._transformMatrix = BABYLON.Matrix.Zero();
  48310. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  48311. _this._blurKernelX = 0;
  48312. _this._blurKernelY = 0;
  48313. _this._blurRatio = 1.0;
  48314. _this.ignoreCameraViewport = true;
  48315. _this.onBeforeRenderObservable.add(function () {
  48316. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  48317. _this._savedViewMatrix = scene.getViewMatrix();
  48318. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  48319. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  48320. scene.clipPlane = _this.mirrorPlane;
  48321. scene.getEngine().cullBackFaces = false;
  48322. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  48323. });
  48324. _this.onAfterRenderObservable.add(function () {
  48325. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  48326. scene.getEngine().cullBackFaces = true;
  48327. scene._mirroredCameraPosition = null;
  48328. delete scene.clipPlane;
  48329. });
  48330. return _this;
  48331. }
  48332. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  48333. get: function () {
  48334. return this._blurRatio;
  48335. },
  48336. set: function (value) {
  48337. if (this._blurRatio === value) {
  48338. return;
  48339. }
  48340. this._blurRatio = value;
  48341. this._preparePostProcesses();
  48342. },
  48343. enumerable: true,
  48344. configurable: true
  48345. });
  48346. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  48347. set: function (value) {
  48348. this.blurKernelX = value;
  48349. this.blurKernelY = value;
  48350. },
  48351. enumerable: true,
  48352. configurable: true
  48353. });
  48354. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  48355. get: function () {
  48356. return this._blurKernelX;
  48357. },
  48358. set: function (value) {
  48359. if (this._blurKernelX === value) {
  48360. return;
  48361. }
  48362. this._blurKernelX = value;
  48363. this._preparePostProcesses();
  48364. },
  48365. enumerable: true,
  48366. configurable: true
  48367. });
  48368. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  48369. get: function () {
  48370. return this._blurKernelY;
  48371. },
  48372. set: function (value) {
  48373. if (this._blurKernelY === value) {
  48374. return;
  48375. }
  48376. this._blurKernelY = value;
  48377. this._preparePostProcesses();
  48378. },
  48379. enumerable: true,
  48380. configurable: true
  48381. });
  48382. MirrorTexture.prototype._preparePostProcesses = function () {
  48383. this.clearPostProcesses(true);
  48384. if (this._blurKernelX && this._blurKernelY) {
  48385. var engine = this.getScene().getEngine();
  48386. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  48387. 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);
  48388. this._blurX.autoClear = false;
  48389. if (this._blurRatio === 1 && this.samples < 2) {
  48390. this._blurX.outputTexture = this._texture;
  48391. }
  48392. else {
  48393. this._blurX.alwaysForcePOT = true;
  48394. }
  48395. 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);
  48396. this._blurY.autoClear = false;
  48397. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  48398. this.addPostProcess(this._blurX);
  48399. this.addPostProcess(this._blurY);
  48400. }
  48401. };
  48402. MirrorTexture.prototype.clone = function () {
  48403. var textureSize = this.getSize();
  48404. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  48405. // Base texture
  48406. newTexture.hasAlpha = this.hasAlpha;
  48407. newTexture.level = this.level;
  48408. // Mirror Texture
  48409. newTexture.mirrorPlane = this.mirrorPlane.clone();
  48410. newTexture.renderList = this.renderList.slice(0);
  48411. return newTexture;
  48412. };
  48413. MirrorTexture.prototype.serialize = function () {
  48414. if (!this.name) {
  48415. return null;
  48416. }
  48417. var serializationObject = _super.prototype.serialize.call(this);
  48418. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  48419. return serializationObject;
  48420. };
  48421. return MirrorTexture;
  48422. }(BABYLON.RenderTargetTexture));
  48423. BABYLON.MirrorTexture = MirrorTexture;
  48424. })(BABYLON || (BABYLON = {}));
  48425. //# sourceMappingURL=babylon.mirrorTexture.js.map
  48426. /// <reference path="babylon.renderTargetTexture.ts" />
  48427. var BABYLON;
  48428. (function (BABYLON) {
  48429. /**
  48430. * Creates a refraction texture used by refraction channel of the standard material.
  48431. * @param name the texture name
  48432. * @param size size of the underlying texture
  48433. * @param scene root scene
  48434. */
  48435. var RefractionTexture = (function (_super) {
  48436. __extends(RefractionTexture, _super);
  48437. function RefractionTexture(name, size, scene, generateMipMaps) {
  48438. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  48439. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  48440. _this.depth = 2.0;
  48441. _this.onBeforeRenderObservable.add(function () {
  48442. scene.clipPlane = _this.refractionPlane;
  48443. });
  48444. _this.onAfterRenderObservable.add(function () {
  48445. delete scene.clipPlane;
  48446. });
  48447. return _this;
  48448. }
  48449. RefractionTexture.prototype.clone = function () {
  48450. var textureSize = this.getSize();
  48451. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  48452. // Base texture
  48453. newTexture.hasAlpha = this.hasAlpha;
  48454. newTexture.level = this.level;
  48455. // Refraction Texture
  48456. newTexture.refractionPlane = this.refractionPlane.clone();
  48457. newTexture.renderList = this.renderList.slice(0);
  48458. newTexture.depth = this.depth;
  48459. return newTexture;
  48460. };
  48461. RefractionTexture.prototype.serialize = function () {
  48462. if (!this.name) {
  48463. return null;
  48464. }
  48465. var serializationObject = _super.prototype.serialize.call(this);
  48466. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  48467. serializationObject.depth = this.depth;
  48468. return serializationObject;
  48469. };
  48470. return RefractionTexture;
  48471. }(BABYLON.RenderTargetTexture));
  48472. BABYLON.RefractionTexture = RefractionTexture;
  48473. })(BABYLON || (BABYLON = {}));
  48474. //# sourceMappingURL=babylon.refractionTexture.js.map
  48475. /// <reference path="babylon.texture.ts" />
  48476. var BABYLON;
  48477. (function (BABYLON) {
  48478. var DynamicTexture = (function (_super) {
  48479. __extends(DynamicTexture, _super);
  48480. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  48481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48482. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48483. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  48484. _this.name = name;
  48485. var engine = _this.getScene().getEngine();
  48486. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48487. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48488. _this._generateMipMaps = generateMipMaps;
  48489. if (options.getContext) {
  48490. _this._canvas = options;
  48491. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48492. }
  48493. else {
  48494. _this._canvas = document.createElement("canvas");
  48495. if (options.width) {
  48496. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48497. }
  48498. else {
  48499. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  48500. }
  48501. }
  48502. var textureSize = _this.getSize();
  48503. _this._canvas.width = textureSize.width;
  48504. _this._canvas.height = textureSize.height;
  48505. _this._context = _this._canvas.getContext("2d");
  48506. return _this;
  48507. }
  48508. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  48509. get: function () {
  48510. return true;
  48511. },
  48512. enumerable: true,
  48513. configurable: true
  48514. });
  48515. DynamicTexture.prototype._recreate = function (textureSize) {
  48516. this._canvas.width = textureSize.width;
  48517. this._canvas.height = textureSize.height;
  48518. this.releaseInternalTexture();
  48519. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  48520. };
  48521. DynamicTexture.prototype.scale = function (ratio) {
  48522. var textureSize = this.getSize();
  48523. textureSize.width *= ratio;
  48524. textureSize.height *= ratio;
  48525. this._recreate(textureSize);
  48526. };
  48527. DynamicTexture.prototype.scaleTo = function (width, height) {
  48528. var textureSize = this.getSize();
  48529. textureSize.width = width;
  48530. textureSize.height = height;
  48531. this._recreate(textureSize);
  48532. };
  48533. DynamicTexture.prototype.getContext = function () {
  48534. return this._context;
  48535. };
  48536. DynamicTexture.prototype.clear = function () {
  48537. var size = this.getSize();
  48538. this._context.fillRect(0, 0, size.width, size.height);
  48539. };
  48540. DynamicTexture.prototype.update = function (invertY) {
  48541. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  48542. };
  48543. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  48544. if (update === void 0) { update = true; }
  48545. var size = this.getSize();
  48546. if (clearColor) {
  48547. this._context.fillStyle = clearColor;
  48548. this._context.fillRect(0, 0, size.width, size.height);
  48549. }
  48550. this._context.font = font;
  48551. if (x === null || x === undefined) {
  48552. var textSize = this._context.measureText(text);
  48553. x = (size.width - textSize.width) / 2;
  48554. }
  48555. if (y === null || y === undefined) {
  48556. var fontSize = parseInt((font.replace(/\D/g, '')));
  48557. ;
  48558. y = (size.height / 2) + (fontSize / 3.65);
  48559. }
  48560. this._context.fillStyle = color;
  48561. this._context.fillText(text, x, y);
  48562. if (update) {
  48563. this.update(invertY);
  48564. }
  48565. };
  48566. DynamicTexture.prototype.clone = function () {
  48567. var textureSize = this.getSize();
  48568. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  48569. // Base texture
  48570. newTexture.hasAlpha = this.hasAlpha;
  48571. newTexture.level = this.level;
  48572. // Dynamic Texture
  48573. newTexture.wrapU = this.wrapU;
  48574. newTexture.wrapV = this.wrapV;
  48575. return newTexture;
  48576. };
  48577. DynamicTexture.prototype._rebuild = function () {
  48578. this.update();
  48579. };
  48580. return DynamicTexture;
  48581. }(BABYLON.Texture));
  48582. BABYLON.DynamicTexture = DynamicTexture;
  48583. })(BABYLON || (BABYLON = {}));
  48584. //# sourceMappingURL=babylon.dynamicTexture.js.map
  48585. var BABYLON;
  48586. (function (BABYLON) {
  48587. var VideoTexture = (function (_super) {
  48588. __extends(VideoTexture, _super);
  48589. /**
  48590. * Creates a video texture.
  48591. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  48592. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  48593. * @param {BABYLON.Scene} scene is obviously the current scene.
  48594. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  48595. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  48596. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  48597. */
  48598. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  48599. if (generateMipMaps === void 0) { generateMipMaps = false; }
  48600. if (invertY === void 0) { invertY = false; }
  48601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48602. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48603. _this._autoLaunch = true;
  48604. var urls;
  48605. _this.name = name;
  48606. if (urlsOrVideo instanceof HTMLVideoElement) {
  48607. _this.video = urlsOrVideo;
  48608. }
  48609. else {
  48610. urls = urlsOrVideo;
  48611. _this.video = document.createElement("video");
  48612. _this.video.autoplay = false;
  48613. _this.video.loop = true;
  48614. }
  48615. _this._generateMipMaps = generateMipMaps;
  48616. _this._samplingMode = samplingMode;
  48617. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  48618. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48619. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48620. }
  48621. else {
  48622. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48623. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48624. _this._generateMipMaps = false;
  48625. }
  48626. if (urls) {
  48627. _this.video.addEventListener("canplay", function () {
  48628. _this._createTexture();
  48629. });
  48630. urls.forEach(function (url) {
  48631. var source = document.createElement("source");
  48632. source.src = url;
  48633. _this.video.appendChild(source);
  48634. });
  48635. }
  48636. else {
  48637. _this._createTexture();
  48638. }
  48639. _this._lastUpdate = BABYLON.Tools.Now;
  48640. return _this;
  48641. }
  48642. VideoTexture.prototype.__setTextureReady = function () {
  48643. this._texture.isReady = true;
  48644. };
  48645. VideoTexture.prototype._createTexture = function () {
  48646. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  48647. if (this._autoLaunch) {
  48648. this._autoLaunch = false;
  48649. this.video.play();
  48650. }
  48651. this._setTextureReady = this.__setTextureReady.bind(this);
  48652. this.video.addEventListener("playing", this._setTextureReady);
  48653. };
  48654. VideoTexture.prototype._rebuild = function () {
  48655. this.update();
  48656. };
  48657. VideoTexture.prototype.update = function () {
  48658. var now = BABYLON.Tools.Now;
  48659. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  48660. return false;
  48661. }
  48662. this._lastUpdate = now;
  48663. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  48664. return true;
  48665. };
  48666. VideoTexture.prototype.dispose = function () {
  48667. _super.prototype.dispose.call(this);
  48668. this.video.removeEventListener("playing", this._setTextureReady);
  48669. };
  48670. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  48671. var video = document.createElement("video");
  48672. var constraintsDeviceId;
  48673. if (constraints && constraints.deviceId) {
  48674. constraintsDeviceId = {
  48675. exact: constraints.deviceId
  48676. };
  48677. }
  48678. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  48679. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  48680. if (navigator.getUserMedia) {
  48681. navigator.getUserMedia({
  48682. video: {
  48683. deviceId: constraintsDeviceId,
  48684. width: {
  48685. min: (constraints && constraints.minWidth) || 256,
  48686. max: (constraints && constraints.maxWidth) || 640
  48687. },
  48688. height: {
  48689. min: (constraints && constraints.minHeight) || 256,
  48690. max: (constraints && constraints.maxHeight) || 480
  48691. }
  48692. }
  48693. }, function (stream) {
  48694. if (video.mozSrcObject !== undefined) {
  48695. video.mozSrcObject = stream;
  48696. }
  48697. else {
  48698. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  48699. }
  48700. video.play();
  48701. if (onReady) {
  48702. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  48703. }
  48704. }, function (e) {
  48705. BABYLON.Tools.Error(e.name);
  48706. });
  48707. }
  48708. };
  48709. return VideoTexture;
  48710. }(BABYLON.Texture));
  48711. BABYLON.VideoTexture = VideoTexture;
  48712. })(BABYLON || (BABYLON = {}));
  48713. //# sourceMappingURL=babylon.videoTexture.js.map
  48714. var BABYLON;
  48715. (function (BABYLON) {
  48716. var RawTexture = (function (_super) {
  48717. __extends(RawTexture, _super);
  48718. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48719. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48720. if (invertY === void 0) { invertY = false; }
  48721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48722. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48723. _this.format = format;
  48724. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48725. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48726. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48727. return _this;
  48728. }
  48729. RawTexture.prototype.update = function (data) {
  48730. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48731. };
  48732. // Statics
  48733. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48734. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48735. if (invertY === void 0) { invertY = false; }
  48736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48737. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48738. };
  48739. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48740. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48741. if (invertY === void 0) { invertY = false; }
  48742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48743. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48744. };
  48745. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48746. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48747. if (invertY === void 0) { invertY = false; }
  48748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48749. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48750. };
  48751. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48752. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48753. if (invertY === void 0) { invertY = false; }
  48754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48755. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  48756. };
  48757. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48758. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48759. if (invertY === void 0) { invertY = false; }
  48760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48761. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  48762. };
  48763. return RawTexture;
  48764. }(BABYLON.Texture));
  48765. BABYLON.RawTexture = RawTexture;
  48766. })(BABYLON || (BABYLON = {}));
  48767. //# sourceMappingURL=babylon.rawTexture.js.map
  48768. var BABYLON;
  48769. (function (BABYLON) {
  48770. var PostProcess = (function () {
  48771. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  48772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  48773. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48774. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  48775. if (blockCompilation === void 0) { blockCompilation = false; }
  48776. this.name = name;
  48777. this.width = -1;
  48778. this.height = -1;
  48779. this.autoClear = true;
  48780. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  48781. /*
  48782. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  48783. Can only be used on a single postprocess or on the last one of a chain.
  48784. */
  48785. this.enablePixelPerfectMode = false;
  48786. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  48787. this.alwaysForcePOT = false;
  48788. this.samples = 1;
  48789. this.adaptScaleToCurrentViewport = false;
  48790. this._reusable = false;
  48791. this._textures = new BABYLON.SmartArray(2);
  48792. this._currentRenderTextureInd = 0;
  48793. this._scaleRatio = new BABYLON.Vector2(1, 1);
  48794. this._texelSize = BABYLON.Vector2.Zero();
  48795. // Events
  48796. /**
  48797. * An event triggered when the postprocess is activated.
  48798. * @type {BABYLON.Observable}
  48799. */
  48800. this.onActivateObservable = new BABYLON.Observable();
  48801. /**
  48802. * An event triggered when the postprocess changes its size.
  48803. * @type {BABYLON.Observable}
  48804. */
  48805. this.onSizeChangedObservable = new BABYLON.Observable();
  48806. /**
  48807. * An event triggered when the postprocess applies its effect.
  48808. * @type {BABYLON.Observable}
  48809. */
  48810. this.onApplyObservable = new BABYLON.Observable();
  48811. /**
  48812. * An event triggered before rendering the postprocess
  48813. * @type {BABYLON.Observable}
  48814. */
  48815. this.onBeforeRenderObservable = new BABYLON.Observable();
  48816. /**
  48817. * An event triggered after rendering the postprocess
  48818. * @type {BABYLON.Observable}
  48819. */
  48820. this.onAfterRenderObservable = new BABYLON.Observable();
  48821. if (camera != null) {
  48822. this._camera = camera;
  48823. this._scene = camera.getScene();
  48824. camera.attachPostProcess(this);
  48825. this._engine = this._scene.getEngine();
  48826. this._scene.postProcesses.push(this);
  48827. }
  48828. else {
  48829. this._engine = engine;
  48830. this._engine.postProcesses.push(this);
  48831. }
  48832. this._options = options;
  48833. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  48834. this._reusable = reusable || false;
  48835. this._textureType = textureType;
  48836. this._samplers = samplers || [];
  48837. this._samplers.push("textureSampler");
  48838. this._fragmentUrl = fragmentUrl;
  48839. this._vertexUrl = vertexUrl;
  48840. this._parameters = parameters || [];
  48841. this._parameters.push("scale");
  48842. this._indexParameters = indexParameters;
  48843. if (!blockCompilation) {
  48844. this.updateEffect(defines);
  48845. }
  48846. }
  48847. Object.defineProperty(PostProcess.prototype, "onActivate", {
  48848. set: function (callback) {
  48849. if (this._onActivateObserver) {
  48850. this.onActivateObservable.remove(this._onActivateObserver);
  48851. }
  48852. this._onActivateObserver = this.onActivateObservable.add(callback);
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  48858. set: function (callback) {
  48859. if (this._onSizeChangedObserver) {
  48860. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  48861. }
  48862. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  48863. },
  48864. enumerable: true,
  48865. configurable: true
  48866. });
  48867. Object.defineProperty(PostProcess.prototype, "onApply", {
  48868. set: function (callback) {
  48869. if (this._onApplyObserver) {
  48870. this.onApplyObservable.remove(this._onApplyObserver);
  48871. }
  48872. this._onApplyObserver = this.onApplyObservable.add(callback);
  48873. },
  48874. enumerable: true,
  48875. configurable: true
  48876. });
  48877. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  48878. set: function (callback) {
  48879. if (this._onBeforeRenderObserver) {
  48880. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48881. }
  48882. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  48883. },
  48884. enumerable: true,
  48885. configurable: true
  48886. });
  48887. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  48888. set: function (callback) {
  48889. if (this._onAfterRenderObserver) {
  48890. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  48891. }
  48892. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  48893. },
  48894. enumerable: true,
  48895. configurable: true
  48896. });
  48897. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  48898. get: function () {
  48899. return this._textures.data[this._currentRenderTextureInd];
  48900. },
  48901. set: function (value) {
  48902. this._forcedOutputTexture = value;
  48903. },
  48904. enumerable: true,
  48905. configurable: true
  48906. });
  48907. PostProcess.prototype.getCamera = function () {
  48908. return this._camera;
  48909. };
  48910. Object.defineProperty(PostProcess.prototype, "texelSize", {
  48911. get: function () {
  48912. if (this._shareOutputWithPostProcess) {
  48913. return this._shareOutputWithPostProcess.texelSize;
  48914. }
  48915. if (this._forcedOutputTexture) {
  48916. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  48917. }
  48918. return this._texelSize;
  48919. },
  48920. enumerable: true,
  48921. configurable: true
  48922. });
  48923. PostProcess.prototype.getEngine = function () {
  48924. return this._engine;
  48925. };
  48926. PostProcess.prototype.getEffect = function () {
  48927. return this._effect;
  48928. };
  48929. PostProcess.prototype.shareOutputWith = function (postProcess) {
  48930. this._disposeTextures();
  48931. this._shareOutputWithPostProcess = postProcess;
  48932. return this;
  48933. };
  48934. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  48935. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  48936. };
  48937. PostProcess.prototype.isReusable = function () {
  48938. return this._reusable;
  48939. };
  48940. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  48941. PostProcess.prototype.markTextureDirty = function () {
  48942. this.width = -1;
  48943. };
  48944. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  48945. var _this = this;
  48946. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  48947. camera = camera || this._camera;
  48948. var scene = camera.getScene();
  48949. var engine = scene.getEngine();
  48950. var maxSize = engine.getCaps().maxTextureSize;
  48951. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  48952. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  48953. var desiredWidth = (this._options.width || requiredWidth);
  48954. var desiredHeight = this._options.height || requiredHeight;
  48955. if (this.adaptScaleToCurrentViewport) {
  48956. var currentViewport = engine.currentViewport;
  48957. if (currentViewport) {
  48958. desiredWidth *= currentViewport.width;
  48959. desiredHeight *= currentViewport.height;
  48960. }
  48961. }
  48962. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  48963. if (!this._options.width) {
  48964. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  48965. }
  48966. if (!this._options.height) {
  48967. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  48968. }
  48969. }
  48970. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  48971. if (this._textures.length > 0) {
  48972. for (var i = 0; i < this._textures.length; i++) {
  48973. this._engine._releaseTexture(this._textures.data[i]);
  48974. }
  48975. this._textures.reset();
  48976. }
  48977. this.width = desiredWidth;
  48978. this.height = desiredHeight;
  48979. var textureSize = { width: this.width, height: this.height };
  48980. var textureOptions = {
  48981. generateMipMaps: false,
  48982. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  48983. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  48984. samplingMode: this.renderTargetSamplingMode,
  48985. type: this._textureType
  48986. };
  48987. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  48988. if (this._reusable) {
  48989. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  48990. }
  48991. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  48992. this.onSizeChangedObservable.notifyObservers(this);
  48993. }
  48994. this._textures.forEach(function (texture) {
  48995. if (texture.samples !== _this.samples) {
  48996. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  48997. }
  48998. });
  48999. }
  49000. var target;
  49001. if (this._shareOutputWithPostProcess) {
  49002. target = this._shareOutputWithPostProcess.outputTexture;
  49003. }
  49004. else if (this._forcedOutputTexture) {
  49005. target = this._forcedOutputTexture;
  49006. this.width = this._forcedOutputTexture.width;
  49007. this.height = this._forcedOutputTexture.height;
  49008. }
  49009. else {
  49010. target = this.outputTexture;
  49011. }
  49012. if (this.enablePixelPerfectMode) {
  49013. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  49014. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  49015. }
  49016. else {
  49017. this._scaleRatio.copyFromFloats(1, 1);
  49018. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  49019. }
  49020. this.onActivateObservable.notifyObservers(camera);
  49021. // Clear
  49022. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  49023. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  49024. }
  49025. if (this._reusable) {
  49026. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  49027. }
  49028. };
  49029. Object.defineProperty(PostProcess.prototype, "isSupported", {
  49030. get: function () {
  49031. return this._effect.isSupported;
  49032. },
  49033. enumerable: true,
  49034. configurable: true
  49035. });
  49036. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  49037. get: function () {
  49038. if (this._shareOutputWithPostProcess) {
  49039. return this._shareOutputWithPostProcess.aspectRatio;
  49040. }
  49041. if (this._forcedOutputTexture) {
  49042. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  49043. }
  49044. return this.width / this.height;
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. PostProcess.prototype.apply = function () {
  49050. // Check
  49051. if (!this._effect || !this._effect.isReady())
  49052. return null;
  49053. // States
  49054. this._engine.enableEffect(this._effect);
  49055. this._engine.setState(false);
  49056. this._engine.setDepthBuffer(false);
  49057. this._engine.setDepthWrite(false);
  49058. // Alpha
  49059. this._engine.setAlphaMode(this.alphaMode);
  49060. if (this.alphaConstants) {
  49061. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  49062. }
  49063. // Texture
  49064. var source;
  49065. if (this._shareOutputWithPostProcess) {
  49066. source = this._shareOutputWithPostProcess.outputTexture;
  49067. }
  49068. else if (this._forcedOutputTexture) {
  49069. source = this._forcedOutputTexture;
  49070. }
  49071. else {
  49072. source = this.outputTexture;
  49073. }
  49074. this._effect._bindTexture("textureSampler", source);
  49075. // Parameters
  49076. this._effect.setVector2("scale", this._scaleRatio);
  49077. this.onApplyObservable.notifyObservers(this._effect);
  49078. return this._effect;
  49079. };
  49080. PostProcess.prototype._disposeTextures = function () {
  49081. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  49082. return;
  49083. }
  49084. if (this._textures.length > 0) {
  49085. for (var i = 0; i < this._textures.length; i++) {
  49086. this._engine._releaseTexture(this._textures.data[i]);
  49087. }
  49088. }
  49089. this._textures.dispose();
  49090. };
  49091. PostProcess.prototype.dispose = function (camera) {
  49092. camera = camera || this._camera;
  49093. this._disposeTextures();
  49094. if (this._scene) {
  49095. var index_1 = this._scene.postProcesses.indexOf(this);
  49096. if (index_1 !== -1) {
  49097. this._scene.postProcesses.splice(index_1, 1);
  49098. }
  49099. }
  49100. else {
  49101. var index_2 = this._engine.postProcesses.indexOf(this);
  49102. if (index_2 !== -1) {
  49103. this._engine.postProcesses.splice(index_2, 1);
  49104. }
  49105. }
  49106. if (!camera) {
  49107. return;
  49108. }
  49109. camera.detachPostProcess(this);
  49110. var index = camera._postProcesses.indexOf(this);
  49111. if (index === 0 && camera._postProcesses.length > 0) {
  49112. this._camera._postProcesses[0].markTextureDirty();
  49113. }
  49114. this.onActivateObservable.clear();
  49115. this.onAfterRenderObservable.clear();
  49116. this.onApplyObservable.clear();
  49117. this.onBeforeRenderObservable.clear();
  49118. this.onSizeChangedObservable.clear();
  49119. };
  49120. return PostProcess;
  49121. }());
  49122. BABYLON.PostProcess = PostProcess;
  49123. })(BABYLON || (BABYLON = {}));
  49124. //# sourceMappingURL=babylon.postProcess.js.map
  49125. var BABYLON;
  49126. (function (BABYLON) {
  49127. var PassPostProcess = (function (_super) {
  49128. __extends(PassPostProcess, _super);
  49129. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  49130. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49131. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  49132. }
  49133. return PassPostProcess;
  49134. }(BABYLON.PostProcess));
  49135. BABYLON.PassPostProcess = PassPostProcess;
  49136. })(BABYLON || (BABYLON = {}));
  49137. //# sourceMappingURL=babylon.passPostProcess.js.map
  49138. var BABYLON;
  49139. (function (BABYLON) {
  49140. var ShadowGenerator = (function () {
  49141. /**
  49142. * Creates a ShadowGenerator object.
  49143. * A ShadowGenerator is the required tool to use the shadows.
  49144. * Each light casting shadows needs to use its own ShadowGenerator.
  49145. * Required parameters :
  49146. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  49147. * - `light`: the light object generating the shadows.
  49148. * - `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.
  49149. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  49150. */
  49151. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  49152. // Members
  49153. this._bias = 0.00005;
  49154. this._blurBoxOffset = 1;
  49155. this._blurScale = 2;
  49156. this._blurKernel = 1;
  49157. this._useKernelBlur = false;
  49158. this._filter = ShadowGenerator.FILTER_NONE;
  49159. this._darkness = 0;
  49160. this._transparencyShadow = false;
  49161. /**
  49162. * Controls the extent to which the shadows fade out at the edge of the frustum
  49163. * Used only by directionals and spots
  49164. */
  49165. this.frustumEdgeFalloff = 0;
  49166. this.forceBackFacesOnly = false;
  49167. this._lightDirection = BABYLON.Vector3.Zero();
  49168. this._viewMatrix = BABYLON.Matrix.Zero();
  49169. this._projectionMatrix = BABYLON.Matrix.Zero();
  49170. this._transformMatrix = BABYLON.Matrix.Zero();
  49171. this._worldViewProjection = BABYLON.Matrix.Zero();
  49172. this._currentFaceIndex = 0;
  49173. this._currentFaceIndexCache = 0;
  49174. this._isCube = false;
  49175. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  49176. this._mapSize = mapSize;
  49177. this._light = light;
  49178. this._scene = light.getScene();
  49179. light._shadowGenerator = this;
  49180. // Texture type fallback from float to int if not supported.
  49181. var caps = this._scene.getEngine().getCaps();
  49182. if (!useFullFloatFirst) {
  49183. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49184. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49185. }
  49186. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49187. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49188. }
  49189. else {
  49190. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49191. }
  49192. }
  49193. else {
  49194. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49195. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49196. }
  49197. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49198. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49199. }
  49200. else {
  49201. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49202. }
  49203. }
  49204. this._initializeGenerator();
  49205. }
  49206. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  49207. // Static
  49208. get: function () {
  49209. return ShadowGenerator._FILTER_NONE;
  49210. },
  49211. enumerable: true,
  49212. configurable: true
  49213. });
  49214. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  49215. get: function () {
  49216. return ShadowGenerator._FILTER_POISSONSAMPLING;
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  49222. get: function () {
  49223. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  49224. },
  49225. enumerable: true,
  49226. configurable: true
  49227. });
  49228. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  49229. get: function () {
  49230. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  49231. },
  49232. enumerable: true,
  49233. configurable: true
  49234. });
  49235. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  49236. get: function () {
  49237. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49238. },
  49239. enumerable: true,
  49240. configurable: true
  49241. });
  49242. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  49243. get: function () {
  49244. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49245. },
  49246. enumerable: true,
  49247. configurable: true
  49248. });
  49249. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  49250. get: function () {
  49251. return this._bias;
  49252. },
  49253. set: function (bias) {
  49254. this._bias = bias;
  49255. },
  49256. enumerable: true,
  49257. configurable: true
  49258. });
  49259. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  49260. get: function () {
  49261. return this._blurBoxOffset;
  49262. },
  49263. set: function (value) {
  49264. if (this._blurBoxOffset === value) {
  49265. return;
  49266. }
  49267. this._blurBoxOffset = value;
  49268. this._disposeBlurPostProcesses();
  49269. },
  49270. enumerable: true,
  49271. configurable: true
  49272. });
  49273. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  49274. get: function () {
  49275. return this._blurScale;
  49276. },
  49277. set: function (value) {
  49278. if (this._blurScale === value) {
  49279. return;
  49280. }
  49281. this._blurScale = value;
  49282. this._disposeBlurPostProcesses();
  49283. },
  49284. enumerable: true,
  49285. configurable: true
  49286. });
  49287. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  49288. get: function () {
  49289. return this._blurKernel;
  49290. },
  49291. set: function (value) {
  49292. if (this._blurKernel === value) {
  49293. return;
  49294. }
  49295. this._blurKernel = value;
  49296. this._disposeBlurPostProcesses();
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  49302. get: function () {
  49303. return this._useKernelBlur;
  49304. },
  49305. set: function (value) {
  49306. if (this._useKernelBlur === value) {
  49307. return;
  49308. }
  49309. this._useKernelBlur = value;
  49310. this._disposeBlurPostProcesses();
  49311. },
  49312. enumerable: true,
  49313. configurable: true
  49314. });
  49315. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  49316. get: function () {
  49317. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  49318. },
  49319. set: function (value) {
  49320. this._depthScale = value;
  49321. },
  49322. enumerable: true,
  49323. configurable: true
  49324. });
  49325. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  49326. get: function () {
  49327. return this._filter;
  49328. },
  49329. set: function (value) {
  49330. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  49331. if (this._light.needCube()) {
  49332. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49333. this.useExponentialShadowMap = true;
  49334. return;
  49335. }
  49336. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49337. this.useCloseExponentialShadowMap = true;
  49338. return;
  49339. }
  49340. }
  49341. if (this._filter === value) {
  49342. return;
  49343. }
  49344. this._filter = value;
  49345. this._disposeBlurPostProcesses();
  49346. this._applyFilterValues();
  49347. this._light._markMeshesAsLightDirty();
  49348. },
  49349. enumerable: true,
  49350. configurable: true
  49351. });
  49352. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  49353. get: function () {
  49354. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  49355. },
  49356. set: function (value) {
  49357. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  49358. return;
  49359. }
  49360. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  49361. },
  49362. enumerable: true,
  49363. configurable: true
  49364. });
  49365. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  49366. get: function () {
  49367. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49368. return this.useExponentialShadowMap;
  49369. },
  49370. set: function (value) {
  49371. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49372. this.useExponentialShadowMap = value;
  49373. },
  49374. enumerable: true,
  49375. configurable: true
  49376. });
  49377. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  49378. get: function () {
  49379. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49380. return this.useBlurExponentialShadowMap;
  49381. },
  49382. set: function (value) {
  49383. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49384. this.useBlurExponentialShadowMap = value;
  49385. },
  49386. enumerable: true,
  49387. configurable: true
  49388. });
  49389. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  49390. get: function () {
  49391. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  49392. },
  49393. set: function (value) {
  49394. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  49395. return;
  49396. }
  49397. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49398. },
  49399. enumerable: true,
  49400. configurable: true
  49401. });
  49402. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  49403. get: function () {
  49404. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  49405. },
  49406. set: function (value) {
  49407. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49408. return;
  49409. }
  49410. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  49416. get: function () {
  49417. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49418. },
  49419. set: function (value) {
  49420. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  49421. return;
  49422. }
  49423. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49424. },
  49425. enumerable: true,
  49426. configurable: true
  49427. });
  49428. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  49429. get: function () {
  49430. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49431. },
  49432. set: function (value) {
  49433. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49434. return;
  49435. }
  49436. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49437. },
  49438. enumerable: true,
  49439. configurable: true
  49440. });
  49441. /**
  49442. * Returns the darkness value (float).
  49443. */
  49444. ShadowGenerator.prototype.getDarkness = function () {
  49445. return this._darkness;
  49446. };
  49447. /**
  49448. * Sets the ShadowGenerator darkness value (float <= 1.0).
  49449. * Returns the ShadowGenerator.
  49450. */
  49451. ShadowGenerator.prototype.setDarkness = function (darkness) {
  49452. if (darkness >= 1.0)
  49453. this._darkness = 1.0;
  49454. else if (darkness <= 0.0)
  49455. this._darkness = 0.0;
  49456. else
  49457. this._darkness = darkness;
  49458. return this;
  49459. };
  49460. /**
  49461. * Sets the ability to have transparent shadow (boolean).
  49462. * Returns the ShadowGenerator.
  49463. */
  49464. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  49465. this._transparencyShadow = hasShadow;
  49466. return this;
  49467. };
  49468. /**
  49469. * Returns a RenderTargetTexture object : the shadow map texture.
  49470. */
  49471. ShadowGenerator.prototype.getShadowMap = function () {
  49472. return this._shadowMap;
  49473. };
  49474. /**
  49475. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  49476. */
  49477. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  49478. if (this._shadowMap2) {
  49479. return this._shadowMap2;
  49480. }
  49481. return this._shadowMap;
  49482. };
  49483. /**
  49484. * Helper function to add a mesh and its descendants to the list of shadow casters
  49485. * @param mesh Mesh to add
  49486. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  49487. */
  49488. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  49489. if (includeDescendants === void 0) { includeDescendants = true; }
  49490. this._shadowMap.renderList.push(mesh);
  49491. if (includeDescendants) {
  49492. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  49493. }
  49494. return this;
  49495. var _a;
  49496. };
  49497. /**
  49498. * Helper function to remove a mesh and its descendants from the list of shadow casters
  49499. * @param mesh Mesh to remove
  49500. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  49501. */
  49502. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  49503. if (includeDescendants === void 0) { includeDescendants = true; }
  49504. var index = this._shadowMap.renderList.indexOf(mesh);
  49505. if (index !== -1) {
  49506. this._shadowMap.renderList.splice(index, 1);
  49507. }
  49508. if (includeDescendants) {
  49509. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  49510. var child = _a[_i];
  49511. this.removeShadowCaster(child);
  49512. }
  49513. }
  49514. return this;
  49515. };
  49516. /**
  49517. * Returns the associated light object.
  49518. */
  49519. ShadowGenerator.prototype.getLight = function () {
  49520. return this._light;
  49521. };
  49522. ShadowGenerator.prototype._initializeGenerator = function () {
  49523. this._light._markMeshesAsLightDirty();
  49524. this._initializeShadowMap();
  49525. };
  49526. ShadowGenerator.prototype._initializeShadowMap = function () {
  49527. var _this = this;
  49528. // Render target
  49529. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  49530. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49531. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49532. this._shadowMap.anisotropicFilteringLevel = 1;
  49533. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49534. this._shadowMap.renderParticles = false;
  49535. this._shadowMap.ignoreCameraViewport = true;
  49536. // Record Face Index before render.
  49537. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  49538. _this._currentFaceIndex = faceIndex;
  49539. });
  49540. // Custom render function.
  49541. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  49542. // Blur if required afer render.
  49543. this._shadowMap.onAfterUnbindObservable.add(function () {
  49544. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  49545. return;
  49546. }
  49547. if (!_this._blurPostProcesses) {
  49548. _this._initializeBlurRTTAndPostProcesses();
  49549. }
  49550. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  49551. });
  49552. // Clear according to the chosen filter.
  49553. this._shadowMap.onClearObservable.add(function (engine) {
  49554. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  49555. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  49556. }
  49557. else {
  49558. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49559. }
  49560. });
  49561. };
  49562. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  49563. var _this = this;
  49564. var engine = this._scene.getEngine();
  49565. var targetSize = this._mapSize / this.blurScale;
  49566. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  49567. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  49568. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49569. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49570. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49571. }
  49572. if (this.useKernelBlur) {
  49573. 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);
  49574. this._kernelBlurXPostprocess.width = targetSize;
  49575. this._kernelBlurXPostprocess.height = targetSize;
  49576. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  49577. effect.setTexture("textureSampler", _this._shadowMap);
  49578. });
  49579. 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);
  49580. this._kernelBlurXPostprocess.autoClear = false;
  49581. this._kernelBlurYPostprocess.autoClear = false;
  49582. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49583. this._kernelBlurXPostprocess.packedFloat = true;
  49584. this._kernelBlurYPostprocess.packedFloat = true;
  49585. }
  49586. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  49587. }
  49588. else {
  49589. 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);
  49590. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  49591. effect.setFloat2("screenSize", targetSize, targetSize);
  49592. effect.setTexture("textureSampler", _this._shadowMap);
  49593. });
  49594. this._boxBlurPostprocess.autoClear = false;
  49595. this._blurPostProcesses = [this._boxBlurPostprocess];
  49596. }
  49597. };
  49598. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  49599. var index;
  49600. var engine = this._scene.getEngine();
  49601. if (depthOnlySubMeshes.length) {
  49602. engine.setColorWrite(false);
  49603. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  49604. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  49605. }
  49606. engine.setColorWrite(true);
  49607. }
  49608. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49609. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  49610. }
  49611. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49612. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  49613. }
  49614. if (this._transparencyShadow) {
  49615. for (index = 0; index < transparentSubMeshes.length; index++) {
  49616. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  49617. }
  49618. }
  49619. };
  49620. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  49621. var _this = this;
  49622. var mesh = subMesh.getRenderingMesh();
  49623. var scene = this._scene;
  49624. var engine = scene.getEngine();
  49625. // Culling
  49626. engine.setState(subMesh.getMaterial().backFaceCulling);
  49627. // Managing instances
  49628. var batch = mesh._getInstancesRenderList(subMesh._id);
  49629. if (batch.mustReturn) {
  49630. return;
  49631. }
  49632. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49633. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  49634. engine.enableEffect(this._effect);
  49635. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49636. var material = subMesh.getMaterial();
  49637. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  49638. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  49639. this._effect.setVector3("lightPosition", this.getLight().position);
  49640. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  49641. // Alpha test
  49642. if (material && material.needAlphaTesting()) {
  49643. var alphaTexture = material.getAlphaTestTexture();
  49644. if (alphaTexture) {
  49645. this._effect.setTexture("diffuseSampler", alphaTexture);
  49646. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  49647. }
  49648. }
  49649. // Bones
  49650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49651. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49652. }
  49653. if (this.forceBackFacesOnly) {
  49654. engine.setState(true, 0, false, true);
  49655. }
  49656. // Draw
  49657. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49658. if (this.forceBackFacesOnly) {
  49659. engine.setState(true, 0, false, false);
  49660. }
  49661. }
  49662. else {
  49663. // Need to reset refresh rate of the shadowMap
  49664. this._shadowMap.resetRefreshCounter();
  49665. }
  49666. };
  49667. ShadowGenerator.prototype._applyFilterValues = function () {
  49668. if (this.filter === ShadowGenerator.FILTER_NONE) {
  49669. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  49670. }
  49671. else {
  49672. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49673. }
  49674. };
  49675. /**
  49676. * Force shader compilation including textures ready check
  49677. */
  49678. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  49679. var _this = this;
  49680. var scene = this._scene;
  49681. var engine = scene.getEngine();
  49682. var subMeshes = new Array();
  49683. var currentIndex = 0;
  49684. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  49685. var mesh = _a[_i];
  49686. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  49687. }
  49688. var checkReady = function () {
  49689. if (!_this._scene || !_this._scene.getEngine()) {
  49690. return;
  49691. }
  49692. var subMesh = subMeshes[currentIndex];
  49693. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  49694. currentIndex++;
  49695. if (currentIndex >= subMeshes.length) {
  49696. if (onCompiled) {
  49697. onCompiled(_this);
  49698. }
  49699. return;
  49700. }
  49701. }
  49702. setTimeout(checkReady, 16);
  49703. };
  49704. if (subMeshes.length > 0) {
  49705. checkReady();
  49706. }
  49707. };
  49708. /**
  49709. * Boolean : true when the ShadowGenerator is finally computed.
  49710. */
  49711. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  49712. var defines = [];
  49713. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49714. defines.push("#define FLOAT");
  49715. }
  49716. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  49717. defines.push("#define ESM");
  49718. }
  49719. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49720. var mesh = subMesh.getMesh();
  49721. var material = subMesh.getMaterial();
  49722. // Alpha test
  49723. if (material && material.needAlphaTesting()) {
  49724. var alphaTexture = material.getAlphaTestTexture();
  49725. if (alphaTexture) {
  49726. defines.push("#define ALPHATEST");
  49727. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49728. attribs.push(BABYLON.VertexBuffer.UVKind);
  49729. defines.push("#define UV1");
  49730. }
  49731. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49732. if (alphaTexture.coordinatesIndex === 1) {
  49733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49734. defines.push("#define UV2");
  49735. }
  49736. }
  49737. }
  49738. }
  49739. // Bones
  49740. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49741. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49742. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49743. if (mesh.numBoneInfluencers > 4) {
  49744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49746. }
  49747. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49748. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49749. }
  49750. else {
  49751. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49752. }
  49753. // Instances
  49754. if (useInstances) {
  49755. defines.push("#define INSTANCES");
  49756. attribs.push("world0");
  49757. attribs.push("world1");
  49758. attribs.push("world2");
  49759. attribs.push("world3");
  49760. }
  49761. // Get correct effect
  49762. var join = defines.join("\n");
  49763. if (this._cachedDefines !== join) {
  49764. this._cachedDefines = join;
  49765. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  49766. }
  49767. return this._effect.isReady();
  49768. };
  49769. /**
  49770. * This creates the defines related to the standard BJS materials.
  49771. */
  49772. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  49773. var scene = this._scene;
  49774. var light = this._light;
  49775. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  49776. return;
  49777. }
  49778. defines["SHADOW" + lightIndex] = true;
  49779. if (this.usePoissonSampling) {
  49780. defines["SHADOWPCF" + lightIndex] = true;
  49781. }
  49782. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  49783. defines["SHADOWESM" + lightIndex] = true;
  49784. }
  49785. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  49786. defines["SHADOWCLOSEESM" + lightIndex] = true;
  49787. }
  49788. if (light.needCube()) {
  49789. defines["SHADOWCUBE" + lightIndex] = true;
  49790. }
  49791. };
  49792. /**
  49793. * This binds shadow lights related to the standard BJS materials.
  49794. * It implies the unifroms available on the materials are the standard BJS ones.
  49795. */
  49796. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  49797. var light = this._light;
  49798. var scene = this._scene;
  49799. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  49800. return;
  49801. }
  49802. if (!light.needCube()) {
  49803. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  49804. }
  49805. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  49806. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  49807. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  49808. };
  49809. // Methods
  49810. /**
  49811. * Returns a Matrix object : the updated transformation matrix.
  49812. */
  49813. ShadowGenerator.prototype.getTransformMatrix = function () {
  49814. var scene = this._scene;
  49815. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  49816. return this._transformMatrix;
  49817. }
  49818. this._currentRenderID = scene.getRenderId();
  49819. this._currentFaceIndexCache = this._currentFaceIndex;
  49820. var lightPosition = this._light.position;
  49821. if (this._light.computeTransformedInformation()) {
  49822. lightPosition = this._light.transformedPosition;
  49823. }
  49824. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  49825. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  49826. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  49827. }
  49828. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  49829. this._cachedPosition = lightPosition.clone();
  49830. this._cachedDirection = this._lightDirection.clone();
  49831. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  49832. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  49833. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  49834. }
  49835. return this._transformMatrix;
  49836. };
  49837. ShadowGenerator.prototype.recreateShadowMap = function () {
  49838. // Track render list.
  49839. var renderList = this._shadowMap.renderList;
  49840. // Clean up existing data.
  49841. this._disposeRTTandPostProcesses();
  49842. // Reinitializes.
  49843. this._initializeGenerator();
  49844. // Reaffect the filter to ensure a correct fallback if necessary.
  49845. this.filter = this.filter;
  49846. // Reaffect the filter.
  49847. this._applyFilterValues();
  49848. // Reaffect Render List.
  49849. this._shadowMap.renderList = renderList;
  49850. };
  49851. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  49852. if (this._shadowMap2) {
  49853. this._shadowMap2.dispose();
  49854. this._shadowMap2 = null;
  49855. }
  49856. if (this._downSamplePostprocess) {
  49857. this._downSamplePostprocess.dispose();
  49858. this._downSamplePostprocess = null;
  49859. }
  49860. if (this._boxBlurPostprocess) {
  49861. this._boxBlurPostprocess.dispose();
  49862. this._boxBlurPostprocess = null;
  49863. }
  49864. if (this._kernelBlurXPostprocess) {
  49865. this._kernelBlurXPostprocess.dispose();
  49866. this._kernelBlurXPostprocess = null;
  49867. }
  49868. if (this._kernelBlurYPostprocess) {
  49869. this._kernelBlurYPostprocess.dispose();
  49870. this._kernelBlurYPostprocess = null;
  49871. }
  49872. this._blurPostProcesses = null;
  49873. };
  49874. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  49875. if (this._shadowMap) {
  49876. this._shadowMap.dispose();
  49877. this._shadowMap = null;
  49878. }
  49879. this._disposeBlurPostProcesses();
  49880. };
  49881. /**
  49882. * Disposes the ShadowGenerator.
  49883. * Returns nothing.
  49884. */
  49885. ShadowGenerator.prototype.dispose = function () {
  49886. this._disposeRTTandPostProcesses();
  49887. this._light._shadowGenerator = null;
  49888. this._light._markMeshesAsLightDirty();
  49889. };
  49890. /**
  49891. * Serializes the ShadowGenerator and returns a serializationObject.
  49892. */
  49893. ShadowGenerator.prototype.serialize = function () {
  49894. var serializationObject = {};
  49895. var shadowMap = this.getShadowMap();
  49896. serializationObject.lightId = this._light.id;
  49897. serializationObject.mapSize = shadowMap.getRenderSize();
  49898. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  49899. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  49900. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  49901. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  49902. serializationObject.usePoissonSampling = this.usePoissonSampling;
  49903. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  49904. serializationObject.depthScale = this.depthScale;
  49905. serializationObject.darkness = this.getDarkness();
  49906. serializationObject.blurBoxOffset = this.blurBoxOffset;
  49907. serializationObject.blurKernel = this.blurKernel;
  49908. serializationObject.blurScale = this.blurScale;
  49909. serializationObject.useKernelBlur = this.useKernelBlur;
  49910. serializationObject.transparencyShadow = this._transparencyShadow;
  49911. serializationObject.renderList = [];
  49912. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  49913. var mesh = shadowMap.renderList[meshIndex];
  49914. serializationObject.renderList.push(mesh.id);
  49915. }
  49916. return serializationObject;
  49917. };
  49918. /**
  49919. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  49920. */
  49921. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  49922. //casting to point light, as light is missing the position attr and typescript complains.
  49923. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  49924. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  49925. var shadowMap = shadowGenerator.getShadowMap();
  49926. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  49927. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  49928. meshes.forEach(function (mesh) {
  49929. shadowMap.renderList.push(mesh);
  49930. });
  49931. }
  49932. if (parsedShadowGenerator.usePoissonSampling) {
  49933. shadowGenerator.usePoissonSampling = true;
  49934. }
  49935. else if (parsedShadowGenerator.useExponentialShadowMap) {
  49936. shadowGenerator.useExponentialShadowMap = true;
  49937. }
  49938. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  49939. shadowGenerator.useBlurExponentialShadowMap = true;
  49940. }
  49941. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  49942. shadowGenerator.useCloseExponentialShadowMap = true;
  49943. }
  49944. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  49945. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  49946. }
  49947. else if (parsedShadowGenerator.useVarianceShadowMap) {
  49948. shadowGenerator.useExponentialShadowMap = true;
  49949. }
  49950. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  49951. shadowGenerator.useBlurExponentialShadowMap = true;
  49952. }
  49953. if (parsedShadowGenerator.depthScale) {
  49954. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  49955. }
  49956. if (parsedShadowGenerator.blurScale) {
  49957. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  49958. }
  49959. if (parsedShadowGenerator.blurBoxOffset) {
  49960. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  49961. }
  49962. if (parsedShadowGenerator.useKernelBlur) {
  49963. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  49964. }
  49965. if (parsedShadowGenerator.blurKernel) {
  49966. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  49967. }
  49968. if (parsedShadowGenerator.bias !== undefined) {
  49969. shadowGenerator.bias = parsedShadowGenerator.bias;
  49970. }
  49971. if (parsedShadowGenerator.darkness) {
  49972. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  49973. }
  49974. if (parsedShadowGenerator.transparencyShadow) {
  49975. shadowGenerator.setTransparencyShadow(true);
  49976. }
  49977. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  49978. return shadowGenerator;
  49979. };
  49980. ShadowGenerator._FILTER_NONE = 0;
  49981. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  49982. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  49983. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  49984. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  49985. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  49986. return ShadowGenerator;
  49987. }());
  49988. BABYLON.ShadowGenerator = ShadowGenerator;
  49989. })(BABYLON || (BABYLON = {}));
  49990. //# sourceMappingURL=babylon.shadowGenerator.js.map
  49991. var BABYLON;
  49992. (function (BABYLON) {
  49993. var DefaultLoadingScreen = (function () {
  49994. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  49995. if (_loadingText === void 0) { _loadingText = ""; }
  49996. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49997. var _this = this;
  49998. this._renderingCanvas = _renderingCanvas;
  49999. this._loadingText = _loadingText;
  50000. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  50001. // Resize
  50002. this._resizeLoadingUI = function () {
  50003. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  50004. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  50005. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  50006. _this._loadingDiv.style.left = canvasRect.left + "px";
  50007. _this._loadingDiv.style.top = canvasRect.top + "px";
  50008. _this._loadingDiv.style.width = canvasRect.width + "px";
  50009. _this._loadingDiv.style.height = canvasRect.height + "px";
  50010. };
  50011. }
  50012. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  50013. if (this._loadingDiv) {
  50014. // Do not add a loading screen if there is already one
  50015. return;
  50016. }
  50017. this._loadingDiv = document.createElement("div");
  50018. this._loadingDiv.id = "babylonjsLoadingDiv";
  50019. this._loadingDiv.style.opacity = "0";
  50020. this._loadingDiv.style.transition = "opacity 1.5s ease";
  50021. this._loadingDiv.style.pointerEvents = "none";
  50022. // Loading text
  50023. this._loadingTextDiv = document.createElement("div");
  50024. this._loadingTextDiv.style.position = "absolute";
  50025. this._loadingTextDiv.style.left = "0";
  50026. this._loadingTextDiv.style.top = "50%";
  50027. this._loadingTextDiv.style.marginTop = "80px";
  50028. this._loadingTextDiv.style.width = "100%";
  50029. this._loadingTextDiv.style.height = "20px";
  50030. this._loadingTextDiv.style.fontFamily = "Arial";
  50031. this._loadingTextDiv.style.fontSize = "14px";
  50032. this._loadingTextDiv.style.color = "white";
  50033. this._loadingTextDiv.style.textAlign = "center";
  50034. this._loadingTextDiv.innerHTML = "Loading";
  50035. this._loadingDiv.appendChild(this._loadingTextDiv);
  50036. //set the predefined text
  50037. this._loadingTextDiv.innerHTML = this._loadingText;
  50038. // Generating keyframes
  50039. var style = document.createElement('style');
  50040. style.type = 'text/css';
  50041. 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 }";
  50042. style.innerHTML = keyFrames;
  50043. document.getElementsByTagName('head')[0].appendChild(style);
  50044. // Loading img
  50045. var imgBack = new Image();
  50046. 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";
  50047. imgBack.style.position = "absolute";
  50048. imgBack.style.left = "50%";
  50049. imgBack.style.top = "50%";
  50050. imgBack.style.marginLeft = "-60px";
  50051. imgBack.style.marginTop = "-60px";
  50052. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  50053. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  50054. imgBack.style.transformOrigin = "50% 50%";
  50055. imgBack.style.webkitTransformOrigin = "50% 50%";
  50056. this._loadingDiv.appendChild(imgBack);
  50057. this._resizeLoadingUI();
  50058. window.addEventListener("resize", this._resizeLoadingUI);
  50059. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50060. document.body.appendChild(this._loadingDiv);
  50061. this._loadingDiv.style.opacity = "1";
  50062. };
  50063. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  50064. var _this = this;
  50065. if (!this._loadingDiv) {
  50066. return;
  50067. }
  50068. var onTransitionEnd = function () {
  50069. if (!_this._loadingDiv) {
  50070. return;
  50071. }
  50072. document.body.removeChild(_this._loadingDiv);
  50073. window.removeEventListener("resize", _this._resizeLoadingUI);
  50074. _this._loadingDiv = null;
  50075. };
  50076. this._loadingDiv.style.opacity = "0";
  50077. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  50078. };
  50079. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  50080. set: function (text) {
  50081. this._loadingText = text;
  50082. if (this._loadingTextDiv) {
  50083. this._loadingTextDiv.innerHTML = this._loadingText;
  50084. }
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  50090. get: function () {
  50091. return this._loadingDivBackgroundColor;
  50092. },
  50093. set: function (color) {
  50094. this._loadingDivBackgroundColor = color;
  50095. if (!this._loadingDiv) {
  50096. return;
  50097. }
  50098. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. return DefaultLoadingScreen;
  50104. }());
  50105. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  50106. })(BABYLON || (BABYLON = {}));
  50107. //# sourceMappingURL=babylon.loadingScreen.js.map
  50108. var BABYLON;
  50109. (function (BABYLON) {
  50110. var SceneLoader = (function () {
  50111. function SceneLoader() {
  50112. }
  50113. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  50114. get: function () {
  50115. return 0;
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  50121. get: function () {
  50122. return 1;
  50123. },
  50124. enumerable: true,
  50125. configurable: true
  50126. });
  50127. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  50128. get: function () {
  50129. return 2;
  50130. },
  50131. enumerable: true,
  50132. configurable: true
  50133. });
  50134. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  50135. get: function () {
  50136. return 3;
  50137. },
  50138. enumerable: true,
  50139. configurable: true
  50140. });
  50141. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  50142. get: function () {
  50143. return SceneLoader._ForceFullSceneLoadingForIncremental;
  50144. },
  50145. set: function (value) {
  50146. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  50147. },
  50148. enumerable: true,
  50149. configurable: true
  50150. });
  50151. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  50152. get: function () {
  50153. return SceneLoader._ShowLoadingScreen;
  50154. },
  50155. set: function (value) {
  50156. SceneLoader._ShowLoadingScreen = value;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(SceneLoader, "loggingLevel", {
  50162. get: function () {
  50163. return SceneLoader._loggingLevel;
  50164. },
  50165. set: function (value) {
  50166. SceneLoader._loggingLevel = value;
  50167. },
  50168. enumerable: true,
  50169. configurable: true
  50170. });
  50171. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  50172. get: function () {
  50173. return SceneLoader._CleanBoneMatrixWeights;
  50174. },
  50175. set: function (value) {
  50176. SceneLoader._CleanBoneMatrixWeights = value;
  50177. },
  50178. enumerable: true,
  50179. configurable: true
  50180. });
  50181. SceneLoader._getDefaultPlugin = function () {
  50182. return SceneLoader._registeredPlugins[".babylon"];
  50183. };
  50184. SceneLoader._getPluginForExtension = function (extension) {
  50185. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  50186. if (registeredPlugin) {
  50187. return registeredPlugin;
  50188. }
  50189. return SceneLoader._getDefaultPlugin();
  50190. };
  50191. SceneLoader._getPluginForDirectLoad = function (data) {
  50192. for (var extension in SceneLoader._registeredPlugins) {
  50193. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  50194. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  50195. return SceneLoader._registeredPlugins[extension];
  50196. }
  50197. }
  50198. return SceneLoader._getDefaultPlugin();
  50199. };
  50200. SceneLoader._getPluginForFilename = function (sceneFilename) {
  50201. if (sceneFilename.name) {
  50202. sceneFilename = sceneFilename.name;
  50203. }
  50204. var dotPosition = sceneFilename.lastIndexOf(".");
  50205. var queryStringPosition = sceneFilename.indexOf("?");
  50206. if (queryStringPosition === -1) {
  50207. queryStringPosition = sceneFilename.length;
  50208. }
  50209. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  50210. return SceneLoader._getPluginForExtension(extension);
  50211. };
  50212. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  50213. SceneLoader._getDirectLoad = function (sceneFilename) {
  50214. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  50215. return sceneFilename.substr(5);
  50216. }
  50217. return null;
  50218. };
  50219. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50220. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  50221. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  50222. var plugin = registeredPlugin.plugin;
  50223. var useArrayBuffer = registeredPlugin.isBinary;
  50224. var database;
  50225. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  50226. var dataCallback = function (data) {
  50227. if (scene.isDisposed) {
  50228. onError("Scene has been disposed");
  50229. return;
  50230. }
  50231. scene.database = database;
  50232. try {
  50233. onSuccess(plugin, data);
  50234. }
  50235. catch (e) {
  50236. onError(null, e);
  50237. }
  50238. };
  50239. var manifestChecked = function (success) {
  50240. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  50241. onError(request.status + " " + request.statusText);
  50242. });
  50243. };
  50244. if (directLoad) {
  50245. dataCallback(directLoad);
  50246. return;
  50247. }
  50248. if (rootUrl.indexOf("file:") === -1) {
  50249. if (scene.getEngine().enableOfflineSupport) {
  50250. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  50251. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  50252. }
  50253. else {
  50254. manifestChecked(true);
  50255. }
  50256. }
  50257. else {
  50258. var fileOrString = sceneFilename;
  50259. if (fileOrString.name) {
  50260. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  50261. }
  50262. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  50263. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  50264. }
  50265. else {
  50266. onError("Unable to find file named " + sceneFilename);
  50267. return;
  50268. }
  50269. }
  50270. };
  50271. // Public functions
  50272. SceneLoader.GetPluginForExtension = function (extension) {
  50273. return SceneLoader._getPluginForExtension(extension).plugin;
  50274. };
  50275. SceneLoader.RegisterPlugin = function (plugin) {
  50276. if (typeof plugin.extensions === "string") {
  50277. var extension = plugin.extensions;
  50278. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50279. plugin: plugin,
  50280. isBinary: false
  50281. };
  50282. }
  50283. else {
  50284. var extensions = plugin.extensions;
  50285. Object.keys(extensions).forEach(function (extension) {
  50286. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50287. plugin: plugin,
  50288. isBinary: extensions[extension].isBinary
  50289. };
  50290. });
  50291. }
  50292. };
  50293. /**
  50294. * Import meshes into a scene
  50295. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  50296. * @param rootUrl a string that defines the root url for scene and resources
  50297. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50298. * @param scene the instance of BABYLON.Scene to append to
  50299. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  50300. * @param onProgress a callback with a progress event for each file being loaded
  50301. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50302. */
  50303. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50304. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50305. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50306. return;
  50307. }
  50308. var loadingToken = {};
  50309. scene._addPendingData(loadingToken);
  50310. var errorHandler = function (message, exception) {
  50311. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50312. if (onError) {
  50313. onError(scene, errorMessage, exception);
  50314. }
  50315. else {
  50316. BABYLON.Tools.Error(errorMessage);
  50317. // should the exception be thrown?
  50318. }
  50319. scene._removePendingData(loadingToken);
  50320. };
  50321. var progressHandler = function (event) {
  50322. if (onProgress) {
  50323. onProgress(event);
  50324. }
  50325. };
  50326. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50327. if (plugin.importMesh) {
  50328. var syncedPlugin = plugin;
  50329. var meshes = new Array();
  50330. var particleSystems = new Array();
  50331. var skeletons = new Array();
  50332. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  50333. return;
  50334. }
  50335. if (onSuccess) {
  50336. // wrap onSuccess with try-catch to know if something went wrong.
  50337. try {
  50338. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50339. onSuccess(meshes, particleSystems, skeletons);
  50340. scene._removePendingData(loadingToken);
  50341. }
  50342. catch (e) {
  50343. var message = 'Error in onSuccess callback.';
  50344. errorHandler(message, e);
  50345. }
  50346. }
  50347. }
  50348. else {
  50349. var asyncedPlugin = plugin;
  50350. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  50351. if (onSuccess) {
  50352. try {
  50353. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50354. onSuccess(meshes, particleSystems, skeletons);
  50355. scene._removePendingData(loadingToken);
  50356. }
  50357. catch (e) {
  50358. var message = 'Error in onSuccess callback.';
  50359. errorHandler(message, e);
  50360. }
  50361. }
  50362. }, progressHandler, errorHandler);
  50363. }
  50364. }, progressHandler, errorHandler);
  50365. };
  50366. /**
  50367. * Load a scene
  50368. * @param rootUrl a string that defines the root url for scene and resources
  50369. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50370. * @param engine is the instance of BABYLON.Engine to use to create the scene
  50371. * @param onSuccess a callback with the scene when import succeeds
  50372. * @param onProgress a callback with a progress event for each file being loaded
  50373. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50374. */
  50375. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  50376. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  50377. };
  50378. /**
  50379. * Append a scene
  50380. * @param rootUrl a string that defines the root url for scene and resources
  50381. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50382. * @param scene is the instance of BABYLON.Scene to append to
  50383. * @param onSuccess a callback with the scene when import succeeds
  50384. * @param onProgress a callback with a progress event for each file being loaded
  50385. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50386. */
  50387. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50388. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50389. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50390. return;
  50391. }
  50392. if (SceneLoader.ShowLoadingScreen) {
  50393. scene.getEngine().displayLoadingUI();
  50394. }
  50395. var loadingToken = {};
  50396. scene._addPendingData(loadingToken);
  50397. var errorHandler = function (message, exception) {
  50398. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50399. if (onError) {
  50400. onError(scene, errorMessage, exception);
  50401. }
  50402. else {
  50403. BABYLON.Tools.Error(errorMessage);
  50404. // should the exception be thrown?
  50405. }
  50406. scene._removePendingData(loadingToken);
  50407. scene.getEngine().hideLoadingUI();
  50408. };
  50409. var progressHandler = function (event) {
  50410. if (onProgress) {
  50411. onProgress(event);
  50412. }
  50413. };
  50414. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50415. if (plugin.load) {
  50416. var syncedPlugin = plugin;
  50417. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  50418. return;
  50419. }
  50420. if (onSuccess) {
  50421. try {
  50422. onSuccess(scene);
  50423. }
  50424. catch (e) {
  50425. errorHandler("Error in onSuccess callback", e);
  50426. }
  50427. }
  50428. scene.loadingPluginName = plugin.name;
  50429. scene._removePendingData(loadingToken);
  50430. }
  50431. else {
  50432. var asyncedPlugin = plugin;
  50433. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  50434. if (onSuccess) {
  50435. onSuccess(scene);
  50436. }
  50437. scene.loadingPluginName = plugin.name;
  50438. scene._removePendingData(loadingToken);
  50439. }, progressHandler, errorHandler);
  50440. }
  50441. if (SceneLoader.ShowLoadingScreen) {
  50442. scene.executeWhenReady(function () {
  50443. scene.getEngine().hideLoadingUI();
  50444. });
  50445. }
  50446. }, progressHandler, errorHandler);
  50447. };
  50448. // Flags
  50449. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  50450. SceneLoader._ShowLoadingScreen = true;
  50451. SceneLoader._CleanBoneMatrixWeights = false;
  50452. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  50453. // Members
  50454. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  50455. SceneLoader._registeredPlugins = {};
  50456. return SceneLoader;
  50457. }());
  50458. BABYLON.SceneLoader = SceneLoader;
  50459. ;
  50460. })(BABYLON || (BABYLON = {}));
  50461. //# sourceMappingURL=babylon.sceneLoader.js.map
  50462. var BABYLON;
  50463. (function (BABYLON) {
  50464. var Internals;
  50465. (function (Internals) {
  50466. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  50467. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  50468. var parsedMaterial = parsedData.materials[index];
  50469. if (parsedMaterial.id === id) {
  50470. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  50471. }
  50472. }
  50473. return null;
  50474. };
  50475. var isDescendantOf = function (mesh, names, hierarchyIds) {
  50476. for (var i in names) {
  50477. if (mesh.name === names[i]) {
  50478. hierarchyIds.push(mesh.id);
  50479. return true;
  50480. }
  50481. }
  50482. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  50483. hierarchyIds.push(mesh.id);
  50484. return true;
  50485. }
  50486. return false;
  50487. };
  50488. var logOperation = function (operation, producer) {
  50489. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  50490. };
  50491. BABYLON.SceneLoader.RegisterPlugin({
  50492. name: "babylon.js",
  50493. extensions: ".babylon",
  50494. canDirectLoad: function (data) {
  50495. if (data.indexOf("babylon") !== -1) {
  50496. return true;
  50497. }
  50498. return false;
  50499. },
  50500. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  50501. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50502. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50503. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50504. // and avoid problems with multiple concurrent .babylon loads.
  50505. var log = "importMesh has failed JSON parse";
  50506. try {
  50507. var parsedData = JSON.parse(data);
  50508. log = "";
  50509. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50510. if (!meshesNames) {
  50511. meshesNames = null;
  50512. }
  50513. else if (!Array.isArray(meshesNames)) {
  50514. meshesNames = [meshesNames];
  50515. }
  50516. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  50517. var loadedSkeletonsIds = [];
  50518. var loadedMaterialsIds = [];
  50519. var hierarchyIds = new Array();
  50520. var index;
  50521. var cache;
  50522. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  50523. var parsedMesh = parsedData.meshes[index];
  50524. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  50525. if (meshesNames !== null) {
  50526. // Remove found mesh name from list.
  50527. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  50528. }
  50529. //Geometry?
  50530. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  50531. //does the file contain geometries?
  50532. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  50533. //find the correct geometry and add it to the scene
  50534. var found = false;
  50535. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  50536. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  50537. return;
  50538. }
  50539. else {
  50540. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  50541. if (parsedGeometryData.id === parsedMesh.geometryId) {
  50542. switch (geometryType) {
  50543. case "boxes":
  50544. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  50545. break;
  50546. case "spheres":
  50547. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  50548. break;
  50549. case "cylinders":
  50550. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  50551. break;
  50552. case "toruses":
  50553. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  50554. break;
  50555. case "grounds":
  50556. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  50557. break;
  50558. case "planes":
  50559. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  50560. break;
  50561. case "torusKnots":
  50562. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  50563. break;
  50564. case "vertexData":
  50565. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  50566. break;
  50567. }
  50568. found = true;
  50569. }
  50570. });
  50571. }
  50572. });
  50573. if (found === false) {
  50574. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  50575. }
  50576. }
  50577. }
  50578. // Material ?
  50579. if (parsedMesh.materialId) {
  50580. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  50581. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  50582. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  50583. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  50584. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  50585. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  50586. var subMatId = parsedMultiMaterial.materials[matIndex];
  50587. loadedMaterialsIds.push(subMatId);
  50588. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  50589. log += "\n\tMaterial " + mat.toString(fullDetails);
  50590. }
  50591. loadedMaterialsIds.push(parsedMultiMaterial.id);
  50592. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  50593. materialFound = true;
  50594. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  50595. break;
  50596. }
  50597. }
  50598. }
  50599. if (materialFound === false) {
  50600. loadedMaterialsIds.push(parsedMesh.materialId);
  50601. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  50602. if (!mat) {
  50603. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  50604. }
  50605. else {
  50606. log += "\n\tMaterial " + mat.toString(fullDetails);
  50607. }
  50608. }
  50609. }
  50610. // Skeleton ?
  50611. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  50612. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  50613. if (skeletonAlreadyLoaded === false) {
  50614. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  50615. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  50616. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  50617. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  50618. skeletons.push(skeleton);
  50619. loadedSkeletonsIds.push(parsedSkeleton.id);
  50620. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  50621. }
  50622. }
  50623. }
  50624. }
  50625. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  50626. meshes.push(mesh);
  50627. log += "\n\tMesh " + mesh.toString(fullDetails);
  50628. }
  50629. }
  50630. // Connecting parents
  50631. var currentMesh;
  50632. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50633. currentMesh = scene.meshes[index];
  50634. if (currentMesh._waitingParentId) {
  50635. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  50636. currentMesh._waitingParentId = undefined;
  50637. }
  50638. }
  50639. // freeze and compute world matrix application
  50640. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50641. currentMesh = scene.meshes[index];
  50642. if (currentMesh._waitingFreezeWorldMatrix) {
  50643. currentMesh.freezeWorldMatrix();
  50644. currentMesh._waitingFreezeWorldMatrix = undefined;
  50645. }
  50646. else {
  50647. currentMesh.computeWorldMatrix(true);
  50648. }
  50649. }
  50650. }
  50651. // Particles
  50652. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50653. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50654. var parsedParticleSystem = parsedData.particleSystems[index];
  50655. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  50656. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  50657. }
  50658. }
  50659. }
  50660. return true;
  50661. }
  50662. catch (err) {
  50663. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  50664. if (onError) {
  50665. onError(msg, err);
  50666. }
  50667. else {
  50668. BABYLON.Tools.Log(msg);
  50669. log = null;
  50670. throw err;
  50671. }
  50672. }
  50673. finally {
  50674. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50675. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50676. }
  50677. }
  50678. },
  50679. load: function (scene, data, rootUrl, onError) {
  50680. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50681. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50682. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50683. // and avoid problems with multiple concurrent .babylon loads.
  50684. var log = "importScene has failed JSON parse";
  50685. try {
  50686. var parsedData = JSON.parse(data);
  50687. log = "";
  50688. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50689. // Scene
  50690. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  50691. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  50692. }
  50693. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  50694. scene.autoClear = parsedData.autoClear;
  50695. }
  50696. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  50697. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  50698. }
  50699. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  50700. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  50701. }
  50702. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  50703. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  50704. }
  50705. // Fog
  50706. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  50707. scene.fogMode = parsedData.fogMode;
  50708. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  50709. scene.fogStart = parsedData.fogStart;
  50710. scene.fogEnd = parsedData.fogEnd;
  50711. scene.fogDensity = parsedData.fogDensity;
  50712. log += "\tFog mode for scene: ";
  50713. switch (scene.fogMode) {
  50714. // getters not compiling, so using hardcoded
  50715. case 1:
  50716. log += "exp\n";
  50717. break;
  50718. case 2:
  50719. log += "exp2\n";
  50720. break;
  50721. case 3:
  50722. log += "linear\n";
  50723. break;
  50724. }
  50725. }
  50726. //Physics
  50727. if (parsedData.physicsEnabled) {
  50728. var physicsPlugin;
  50729. if (parsedData.physicsEngine === "cannon") {
  50730. physicsPlugin = new BABYLON.CannonJSPlugin();
  50731. }
  50732. else if (parsedData.physicsEngine === "oimo") {
  50733. physicsPlugin = new BABYLON.OimoJSPlugin();
  50734. }
  50735. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  50736. //else - default engine, which is currently oimo
  50737. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  50738. scene.enablePhysics(physicsGravity, physicsPlugin);
  50739. }
  50740. // Metadata
  50741. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  50742. scene.metadata = parsedData.metadata;
  50743. }
  50744. //collisions, if defined. otherwise, default is true
  50745. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  50746. scene.collisionsEnabled = parsedData.collisionsEnabled;
  50747. }
  50748. scene.workerCollisions = !!parsedData.workerCollisions;
  50749. var index;
  50750. var cache;
  50751. // Lights
  50752. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  50753. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  50754. var parsedLight = parsedData.lights[index];
  50755. var light = BABYLON.Light.Parse(parsedLight, scene);
  50756. log += (index === 0 ? "\n\tLights:" : "");
  50757. log += "\n\t\t" + light.toString(fullDetails);
  50758. }
  50759. }
  50760. // Animations
  50761. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  50762. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  50763. var parsedAnimation = parsedData.animations[index];
  50764. var animation = BABYLON.Animation.Parse(parsedAnimation);
  50765. scene.animations.push(animation);
  50766. log += (index === 0 ? "\n\tAnimations:" : "");
  50767. log += "\n\t\t" + animation.toString(fullDetails);
  50768. }
  50769. }
  50770. if (parsedData.autoAnimate) {
  50771. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  50772. }
  50773. // Materials
  50774. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  50775. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  50776. var parsedMaterial = parsedData.materials[index];
  50777. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  50778. log += (index === 0 ? "\n\tMaterials:" : "");
  50779. log += "\n\t\t" + mat.toString(fullDetails);
  50780. }
  50781. }
  50782. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  50783. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  50784. var parsedMultiMaterial = parsedData.multiMaterials[index];
  50785. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  50786. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  50787. log += "\n\t\t" + mmat.toString(fullDetails);
  50788. }
  50789. }
  50790. // Morph targets
  50791. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  50792. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  50793. var managerData = _a[_i];
  50794. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  50795. }
  50796. }
  50797. // Skeletons
  50798. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  50799. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  50800. var parsedSkeleton = parsedData.skeletons[index];
  50801. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  50802. log += (index === 0 ? "\n\tSkeletons:" : "");
  50803. log += "\n\t\t" + skeleton.toString(fullDetails);
  50804. }
  50805. }
  50806. // Geometries
  50807. var geometries = parsedData.geometries;
  50808. if (geometries !== undefined && geometries !== null) {
  50809. // Boxes
  50810. var boxes = geometries.boxes;
  50811. if (boxes !== undefined && boxes !== null) {
  50812. for (index = 0, cache = boxes.length; index < cache; index++) {
  50813. var parsedBox = boxes[index];
  50814. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  50815. }
  50816. }
  50817. // Spheres
  50818. var spheres = geometries.spheres;
  50819. if (spheres !== undefined && spheres !== null) {
  50820. for (index = 0, cache = spheres.length; index < cache; index++) {
  50821. var parsedSphere = spheres[index];
  50822. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  50823. }
  50824. }
  50825. // Cylinders
  50826. var cylinders = geometries.cylinders;
  50827. if (cylinders !== undefined && cylinders !== null) {
  50828. for (index = 0, cache = cylinders.length; index < cache; index++) {
  50829. var parsedCylinder = cylinders[index];
  50830. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  50831. }
  50832. }
  50833. // Toruses
  50834. var toruses = geometries.toruses;
  50835. if (toruses !== undefined && toruses !== null) {
  50836. for (index = 0, cache = toruses.length; index < cache; index++) {
  50837. var parsedTorus = toruses[index];
  50838. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  50839. }
  50840. }
  50841. // Grounds
  50842. var grounds = geometries.grounds;
  50843. if (grounds !== undefined && grounds !== null) {
  50844. for (index = 0, cache = grounds.length; index < cache; index++) {
  50845. var parsedGround = grounds[index];
  50846. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  50847. }
  50848. }
  50849. // Planes
  50850. var planes = geometries.planes;
  50851. if (planes !== undefined && planes !== null) {
  50852. for (index = 0, cache = planes.length; index < cache; index++) {
  50853. var parsedPlane = planes[index];
  50854. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  50855. }
  50856. }
  50857. // TorusKnots
  50858. var torusKnots = geometries.torusKnots;
  50859. if (torusKnots !== undefined && torusKnots !== null) {
  50860. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  50861. var parsedTorusKnot = torusKnots[index];
  50862. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  50863. }
  50864. }
  50865. // VertexData
  50866. var vertexData = geometries.vertexData;
  50867. if (vertexData !== undefined && vertexData !== null) {
  50868. for (index = 0, cache = vertexData.length; index < cache; index++) {
  50869. var parsedVertexData = vertexData[index];
  50870. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  50871. }
  50872. }
  50873. }
  50874. // Meshes
  50875. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  50876. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  50877. var parsedMesh = parsedData.meshes[index];
  50878. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  50879. log += (index === 0 ? "\n\tMeshes:" : "");
  50880. log += "\n\t\t" + mesh.toString(fullDetails);
  50881. }
  50882. }
  50883. // Cameras
  50884. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  50885. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  50886. var parsedCamera = parsedData.cameras[index];
  50887. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  50888. log += (index === 0 ? "\n\tCameras:" : "");
  50889. log += "\n\t\t" + camera.toString(fullDetails);
  50890. }
  50891. }
  50892. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  50893. scene.setActiveCameraByID(parsedData.activeCameraID);
  50894. }
  50895. // Browsing all the graph to connect the dots
  50896. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  50897. var camera = scene.cameras[index];
  50898. if (camera._waitingParentId) {
  50899. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  50900. camera._waitingParentId = undefined;
  50901. }
  50902. }
  50903. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50904. var light = scene.lights[index];
  50905. if (light._waitingParentId) {
  50906. light.parent = scene.getLastEntryByID(light._waitingParentId);
  50907. light._waitingParentId = undefined;
  50908. }
  50909. }
  50910. // Sounds
  50911. var loadedSounds = [];
  50912. var loadedSound;
  50913. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  50914. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  50915. var parsedSound = parsedData.sounds[index];
  50916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50917. if (!parsedSound.url)
  50918. parsedSound.url = parsedSound.name;
  50919. if (!loadedSounds[parsedSound.url]) {
  50920. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  50921. loadedSounds[parsedSound.url] = loadedSound;
  50922. }
  50923. else {
  50924. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  50925. }
  50926. }
  50927. else {
  50928. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  50929. }
  50930. }
  50931. }
  50932. loadedSounds = [];
  50933. // Connect parents & children and parse actions
  50934. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50935. var mesh = scene.meshes[index];
  50936. if (mesh._waitingParentId) {
  50937. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  50938. mesh._waitingParentId = undefined;
  50939. }
  50940. if (mesh._waitingActions) {
  50941. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  50942. mesh._waitingActions = undefined;
  50943. }
  50944. }
  50945. // freeze world matrix application
  50946. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50947. var currentMesh = scene.meshes[index];
  50948. if (currentMesh._waitingFreezeWorldMatrix) {
  50949. currentMesh.freezeWorldMatrix();
  50950. currentMesh._waitingFreezeWorldMatrix = undefined;
  50951. }
  50952. else {
  50953. currentMesh.computeWorldMatrix(true);
  50954. }
  50955. }
  50956. // Particles Systems
  50957. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50958. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50959. var parsedParticleSystem = parsedData.particleSystems[index];
  50960. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  50961. }
  50962. }
  50963. // Lens flares
  50964. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  50965. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  50966. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  50967. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  50968. }
  50969. }
  50970. // Shadows
  50971. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  50972. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  50973. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  50974. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  50975. }
  50976. }
  50977. // Lights exclusions / inclusions
  50978. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50979. var light = scene.lights[index];
  50980. // Excluded check
  50981. if (light._excludedMeshesIds.length > 0) {
  50982. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  50983. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  50984. if (excludedMesh) {
  50985. light.excludedMeshes.push(excludedMesh);
  50986. }
  50987. }
  50988. light._excludedMeshesIds = [];
  50989. }
  50990. // Included check
  50991. if (light._includedOnlyMeshesIds.length > 0) {
  50992. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  50993. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  50994. if (includedOnlyMesh) {
  50995. light.includedOnlyMeshes.push(includedOnlyMesh);
  50996. }
  50997. }
  50998. light._includedOnlyMeshesIds = [];
  50999. }
  51000. }
  51001. // Actions (scene)
  51002. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  51003. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  51004. }
  51005. // Finish
  51006. return true;
  51007. }
  51008. catch (err) {
  51009. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  51010. if (onError) {
  51011. onError(msg, err);
  51012. }
  51013. else {
  51014. BABYLON.Tools.Log(msg);
  51015. log = null;
  51016. throw err;
  51017. }
  51018. }
  51019. finally {
  51020. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  51021. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  51022. }
  51023. }
  51024. }
  51025. });
  51026. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51027. })(BABYLON || (BABYLON = {}));
  51028. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  51029. var BABYLON;
  51030. (function (BABYLON) {
  51031. var FilesInput = (function () {
  51032. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  51033. this.onProcessFileCallback = function () { return true; };
  51034. this._engine = engine;
  51035. this._currentScene = scene;
  51036. this._sceneLoadedCallback = sceneLoadedCallback;
  51037. this._progressCallback = progressCallback;
  51038. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  51039. this._textureLoadingCallback = textureLoadingCallback;
  51040. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  51041. this._onReloadCallback = onReloadCallback;
  51042. this._errorCallback = errorCallback;
  51043. }
  51044. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  51045. var _this = this;
  51046. if (elementToMonitor) {
  51047. this._elementToMonitor = elementToMonitor;
  51048. this._dragEnterHandler = function (e) { _this.drag(e); };
  51049. this._dragOverHandler = function (e) { _this.drag(e); };
  51050. this._dropHandler = function (e) { _this.drop(e); };
  51051. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  51052. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  51053. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  51054. }
  51055. };
  51056. FilesInput.prototype.dispose = function () {
  51057. if (!this._elementToMonitor) {
  51058. return;
  51059. }
  51060. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  51061. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  51062. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  51063. };
  51064. FilesInput.prototype.renderFunction = function () {
  51065. if (this._additionalRenderLoopLogicCallback) {
  51066. this._additionalRenderLoopLogicCallback();
  51067. }
  51068. if (this._currentScene) {
  51069. if (this._textureLoadingCallback) {
  51070. var remaining = this._currentScene.getWaitingItemsCount();
  51071. if (remaining > 0) {
  51072. this._textureLoadingCallback(remaining);
  51073. }
  51074. }
  51075. this._currentScene.render();
  51076. }
  51077. };
  51078. FilesInput.prototype.drag = function (e) {
  51079. e.stopPropagation();
  51080. e.preventDefault();
  51081. };
  51082. FilesInput.prototype.drop = function (eventDrop) {
  51083. eventDrop.stopPropagation();
  51084. eventDrop.preventDefault();
  51085. this.loadFiles(eventDrop);
  51086. };
  51087. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  51088. var _this = this;
  51089. var reader = folder.createReader();
  51090. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  51091. reader.readEntries(function (entries) {
  51092. remaining.count += entries.length;
  51093. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  51094. var entry = entries_1[_i];
  51095. if (entry.isFile) {
  51096. entry.file(function (file) {
  51097. file.correctName = relativePath + file.name;
  51098. files.push(file);
  51099. if (--remaining.count === 0) {
  51100. callback();
  51101. }
  51102. });
  51103. }
  51104. else if (entry.isDirectory) {
  51105. _this._traverseFolder(entry, files, remaining, callback);
  51106. }
  51107. }
  51108. if (--remaining.count) {
  51109. callback();
  51110. }
  51111. });
  51112. };
  51113. FilesInput.prototype._processFiles = function (files) {
  51114. var skippedFiles = 0;
  51115. for (var i = 0; i < files.length; i++) {
  51116. var name = files[i].correctName.toLowerCase();
  51117. var extension = name.split('.').pop();
  51118. if (!this.onProcessFileCallback(files[i], name, extension)) {
  51119. skippedFiles++;
  51120. continue;
  51121. }
  51122. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  51123. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  51124. this._sceneFileToLoad = files[i];
  51125. }
  51126. else {
  51127. FilesInput.FilesToLoad[name] = files[i];
  51128. }
  51129. }
  51130. if (this._onReloadCallback) {
  51131. this._onReloadCallback(this._sceneFileToLoad);
  51132. }
  51133. else if (skippedFiles < files.length) {
  51134. this.reload();
  51135. }
  51136. };
  51137. FilesInput.prototype.loadFiles = function (event) {
  51138. var _this = this;
  51139. if (this._startingProcessingFilesCallback)
  51140. this._startingProcessingFilesCallback();
  51141. // Handling data transfer via drag'n'drop
  51142. if (event && event.dataTransfer && event.dataTransfer.files) {
  51143. this._filesToLoad = event.dataTransfer.files;
  51144. }
  51145. // Handling files from input files
  51146. if (event && event.target && event.target.files) {
  51147. this._filesToLoad = event.target.files;
  51148. }
  51149. if (this._filesToLoad && this._filesToLoad.length > 0) {
  51150. var files_1 = new Array();
  51151. var folders = [];
  51152. var items = event.dataTransfer ? event.dataTransfer.items : null;
  51153. for (var i = 0; i < this._filesToLoad.length; i++) {
  51154. var fileToLoad = this._filesToLoad[i];
  51155. var name_1 = fileToLoad.name.toLowerCase();
  51156. var type = fileToLoad.type;
  51157. var entry = void 0;
  51158. fileToLoad.correctName = name_1;
  51159. if (items) {
  51160. var item = items[i];
  51161. if (item.getAsEntry) {
  51162. entry = item.getAsEntry();
  51163. }
  51164. else if (item.webkitGetAsEntry) {
  51165. entry = item.webkitGetAsEntry();
  51166. }
  51167. }
  51168. if (!entry) {
  51169. files_1.push(fileToLoad);
  51170. }
  51171. else {
  51172. if (entry.isDirectory) {
  51173. folders.push(entry);
  51174. }
  51175. else {
  51176. files_1.push(fileToLoad);
  51177. }
  51178. }
  51179. }
  51180. if (folders.length === 0) {
  51181. this._processFiles(files_1);
  51182. }
  51183. else {
  51184. var remaining = { count: folders.length };
  51185. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  51186. var folder = folders_1[_i];
  51187. this._traverseFolder(folder, files_1, remaining, function () {
  51188. _this._processFiles(files_1);
  51189. });
  51190. }
  51191. }
  51192. }
  51193. };
  51194. FilesInput.prototype.reload = function () {
  51195. var _this = this;
  51196. // If a ".babylon" file has been provided
  51197. if (this._sceneFileToLoad) {
  51198. if (this._currentScene) {
  51199. if (BABYLON.Tools.errorsCount > 0) {
  51200. BABYLON.Tools.ClearLogCache();
  51201. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  51202. }
  51203. this._engine.stopRenderLoop();
  51204. this._currentScene.dispose();
  51205. }
  51206. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  51207. _this._currentScene = newScene;
  51208. if (_this._sceneLoadedCallback) {
  51209. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  51210. }
  51211. // Wait for textures and shaders to be ready
  51212. _this._currentScene.executeWhenReady(function () {
  51213. _this._engine.runRenderLoop(function () {
  51214. _this.renderFunction();
  51215. });
  51216. });
  51217. }, function (progress) {
  51218. if (_this._progressCallback) {
  51219. _this._progressCallback(progress);
  51220. }
  51221. }, function (scene, message) {
  51222. _this._currentScene = scene;
  51223. if (_this._errorCallback) {
  51224. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  51225. }
  51226. });
  51227. }
  51228. else {
  51229. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  51230. }
  51231. };
  51232. FilesInput.FilesToLoad = {};
  51233. return FilesInput;
  51234. }());
  51235. BABYLON.FilesInput = FilesInput;
  51236. })(BABYLON || (BABYLON = {}));
  51237. //# sourceMappingURL=babylon.filesInput.js.map
  51238. var BABYLON;
  51239. (function (BABYLON) {
  51240. /**
  51241. * This class implement a typical dictionary using a string as key and the generic type T as value.
  51242. * The underlying implementation relies on an associative array to ensure the best performances.
  51243. * The value can be anything including 'null' but except 'undefined'
  51244. */
  51245. var StringDictionary = (function () {
  51246. function StringDictionary() {
  51247. this._count = 0;
  51248. this._data = {};
  51249. }
  51250. /**
  51251. * This will clear this dictionary and copy the content from the 'source' one.
  51252. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  51253. * @param source the dictionary to take the content from and copy to this dictionary
  51254. */
  51255. StringDictionary.prototype.copyFrom = function (source) {
  51256. var _this = this;
  51257. this.clear();
  51258. source.forEach(function (t, v) { return _this.add(t, v); });
  51259. };
  51260. /**
  51261. * Get a value based from its key
  51262. * @param key the given key to get the matching value from
  51263. * @return the value if found, otherwise undefined is returned
  51264. */
  51265. StringDictionary.prototype.get = function (key) {
  51266. var val = this._data[key];
  51267. if (val !== undefined) {
  51268. return val;
  51269. }
  51270. return undefined;
  51271. };
  51272. /**
  51273. * Get a value from its key or add it if it doesn't exist.
  51274. * This method will ensure you that a given key/data will be present in the dictionary.
  51275. * @param key the given key to get the matching value from
  51276. * @param factory the factory that will create the value if the key is not present in the dictionary.
  51277. * The factory will only be invoked if there's no data for the given key.
  51278. * @return the value corresponding to the key.
  51279. */
  51280. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  51281. var val = this.get(key);
  51282. if (val !== undefined) {
  51283. return val;
  51284. }
  51285. val = factory(key);
  51286. if (val) {
  51287. this.add(key, val);
  51288. }
  51289. return val;
  51290. };
  51291. /**
  51292. * Get a value from its key if present in the dictionary otherwise add it
  51293. * @param key the key to get the value from
  51294. * @param val if there's no such key/value pair in the dictionary add it with this value
  51295. * @return the value corresponding to the key
  51296. */
  51297. StringDictionary.prototype.getOrAdd = function (key, val) {
  51298. var curVal = this.get(key);
  51299. if (curVal !== undefined) {
  51300. return curVal;
  51301. }
  51302. this.add(key, val);
  51303. return val;
  51304. };
  51305. /**
  51306. * Check if there's a given key in the dictionary
  51307. * @param key the key to check for
  51308. * @return true if the key is present, false otherwise
  51309. */
  51310. StringDictionary.prototype.contains = function (key) {
  51311. return this._data[key] !== undefined;
  51312. };
  51313. /**
  51314. * Add a new key and its corresponding value
  51315. * @param key the key to add
  51316. * @param value the value corresponding to the key
  51317. * @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
  51318. */
  51319. StringDictionary.prototype.add = function (key, value) {
  51320. if (this._data[key] !== undefined) {
  51321. return false;
  51322. }
  51323. this._data[key] = value;
  51324. ++this._count;
  51325. return true;
  51326. };
  51327. StringDictionary.prototype.set = function (key, value) {
  51328. if (this._data[key] === undefined) {
  51329. return false;
  51330. }
  51331. this._data[key] = value;
  51332. return true;
  51333. };
  51334. /**
  51335. * Get the element of the given key and remove it from the dictionary
  51336. * @param key
  51337. */
  51338. StringDictionary.prototype.getAndRemove = function (key) {
  51339. var val = this.get(key);
  51340. if (val !== undefined) {
  51341. delete this._data[key];
  51342. --this._count;
  51343. return val;
  51344. }
  51345. return null;
  51346. };
  51347. /**
  51348. * Remove a key/value from the dictionary.
  51349. * @param key the key to remove
  51350. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  51351. */
  51352. StringDictionary.prototype.remove = function (key) {
  51353. if (this.contains(key)) {
  51354. delete this._data[key];
  51355. --this._count;
  51356. return true;
  51357. }
  51358. return false;
  51359. };
  51360. /**
  51361. * Clear the whole content of the dictionary
  51362. */
  51363. StringDictionary.prototype.clear = function () {
  51364. this._data = {};
  51365. this._count = 0;
  51366. };
  51367. Object.defineProperty(StringDictionary.prototype, "count", {
  51368. get: function () {
  51369. return this._count;
  51370. },
  51371. enumerable: true,
  51372. configurable: true
  51373. });
  51374. /**
  51375. * Execute a callback on each key/val of the dictionary.
  51376. * Note that you can remove any element in this dictionary in the callback implementation
  51377. * @param callback the callback to execute on a given key/value pair
  51378. */
  51379. StringDictionary.prototype.forEach = function (callback) {
  51380. for (var cur in this._data) {
  51381. var val = this._data[cur];
  51382. callback(cur, val);
  51383. }
  51384. };
  51385. /**
  51386. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  51387. * If the callback returns null or undefined the method will iterate to the next key/value pair
  51388. * Note that you can remove any element in this dictionary in the callback implementation
  51389. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  51390. */
  51391. StringDictionary.prototype.first = function (callback) {
  51392. for (var cur in this._data) {
  51393. var val = this._data[cur];
  51394. var res = callback(cur, val);
  51395. if (res) {
  51396. return res;
  51397. }
  51398. }
  51399. return null;
  51400. };
  51401. return StringDictionary;
  51402. }());
  51403. BABYLON.StringDictionary = StringDictionary;
  51404. })(BABYLON || (BABYLON = {}));
  51405. //# sourceMappingURL=babylon.stringDictionary.js.map
  51406. var BABYLON;
  51407. (function (BABYLON) {
  51408. var Tags = (function () {
  51409. function Tags() {
  51410. }
  51411. Tags.EnableFor = function (obj) {
  51412. obj._tags = obj._tags || {};
  51413. obj.hasTags = function () {
  51414. return Tags.HasTags(obj);
  51415. };
  51416. obj.addTags = function (tagsString) {
  51417. return Tags.AddTagsTo(obj, tagsString);
  51418. };
  51419. obj.removeTags = function (tagsString) {
  51420. return Tags.RemoveTagsFrom(obj, tagsString);
  51421. };
  51422. obj.matchesTagsQuery = function (tagsQuery) {
  51423. return Tags.MatchesQuery(obj, tagsQuery);
  51424. };
  51425. };
  51426. Tags.DisableFor = function (obj) {
  51427. delete obj._tags;
  51428. delete obj.hasTags;
  51429. delete obj.addTags;
  51430. delete obj.removeTags;
  51431. delete obj.matchesTagsQuery;
  51432. };
  51433. Tags.HasTags = function (obj) {
  51434. if (!obj._tags) {
  51435. return false;
  51436. }
  51437. return !BABYLON.Tools.IsEmpty(obj._tags);
  51438. };
  51439. Tags.GetTags = function (obj, asString) {
  51440. if (asString === void 0) { asString = true; }
  51441. if (!obj._tags) {
  51442. return null;
  51443. }
  51444. if (asString) {
  51445. var tagsArray = [];
  51446. for (var tag in obj._tags) {
  51447. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  51448. tagsArray.push(tag);
  51449. }
  51450. }
  51451. return tagsArray.join(" ");
  51452. }
  51453. else {
  51454. return obj._tags;
  51455. }
  51456. };
  51457. // the tags 'true' and 'false' are reserved and cannot be used as tags
  51458. // a tag cannot start with '||', '&&', and '!'
  51459. // it cannot contain whitespaces
  51460. Tags.AddTagsTo = function (obj, tagsString) {
  51461. if (!tagsString) {
  51462. return;
  51463. }
  51464. if (typeof tagsString !== "string") {
  51465. return;
  51466. }
  51467. var tags = tagsString.split(" ");
  51468. tags.forEach(function (tag, index, array) {
  51469. Tags._AddTagTo(obj, tag);
  51470. });
  51471. };
  51472. Tags._AddTagTo = function (obj, tag) {
  51473. tag = tag.trim();
  51474. if (tag === "" || tag === "true" || tag === "false") {
  51475. return;
  51476. }
  51477. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  51478. return;
  51479. }
  51480. Tags.EnableFor(obj);
  51481. obj._tags[tag] = true;
  51482. };
  51483. Tags.RemoveTagsFrom = function (obj, tagsString) {
  51484. if (!Tags.HasTags(obj)) {
  51485. return;
  51486. }
  51487. var tags = tagsString.split(" ");
  51488. for (var t in tags) {
  51489. Tags._RemoveTagFrom(obj, tags[t]);
  51490. }
  51491. };
  51492. Tags._RemoveTagFrom = function (obj, tag) {
  51493. delete obj._tags[tag];
  51494. };
  51495. Tags.MatchesQuery = function (obj, tagsQuery) {
  51496. if (tagsQuery === undefined) {
  51497. return true;
  51498. }
  51499. if (tagsQuery === "") {
  51500. return Tags.HasTags(obj);
  51501. }
  51502. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  51503. };
  51504. return Tags;
  51505. }());
  51506. BABYLON.Tags = Tags;
  51507. })(BABYLON || (BABYLON = {}));
  51508. //# sourceMappingURL=babylon.tags.js.map
  51509. var BABYLON;
  51510. (function (BABYLON) {
  51511. var Internals;
  51512. (function (Internals) {
  51513. var AndOrNotEvaluator = (function () {
  51514. function AndOrNotEvaluator() {
  51515. }
  51516. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  51517. if (!query.match(/\([^\(\)]*\)/g)) {
  51518. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  51519. }
  51520. else {
  51521. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  51522. // remove parenthesis
  51523. r = r.slice(1, r.length - 1);
  51524. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  51525. });
  51526. }
  51527. if (query === "true") {
  51528. return true;
  51529. }
  51530. if (query === "false") {
  51531. return false;
  51532. }
  51533. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  51534. };
  51535. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  51536. evaluateCallback = evaluateCallback || (function (r) {
  51537. return r === "true" ? true : false;
  51538. });
  51539. var result;
  51540. var or = parenthesisContent.split("||");
  51541. for (var i in or) {
  51542. if (or.hasOwnProperty(i)) {
  51543. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  51544. var and = ori.split("&&");
  51545. if (and.length > 1) {
  51546. for (var j = 0; j < and.length; ++j) {
  51547. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  51548. if (andj !== "true" && andj !== "false") {
  51549. if (andj[0] === "!") {
  51550. result = !evaluateCallback(andj.substring(1));
  51551. }
  51552. else {
  51553. result = evaluateCallback(andj);
  51554. }
  51555. }
  51556. else {
  51557. result = andj === "true" ? true : false;
  51558. }
  51559. if (!result) {
  51560. ori = "false";
  51561. break;
  51562. }
  51563. }
  51564. }
  51565. if (result || ori === "true") {
  51566. result = true;
  51567. break;
  51568. }
  51569. // result equals false (or undefined)
  51570. if (ori !== "true" && ori !== "false") {
  51571. if (ori[0] === "!") {
  51572. result = !evaluateCallback(ori.substring(1));
  51573. }
  51574. else {
  51575. result = evaluateCallback(ori);
  51576. }
  51577. }
  51578. else {
  51579. result = ori === "true" ? true : false;
  51580. }
  51581. }
  51582. }
  51583. // the whole parenthesis scope is replaced by 'true' or 'false'
  51584. return result ? "true" : "false";
  51585. };
  51586. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  51587. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  51588. // remove whitespaces
  51589. r = r.replace(/[\s]/g, function () { return ""; });
  51590. return r.length % 2 ? "!" : "";
  51591. });
  51592. booleanString = booleanString.trim();
  51593. if (booleanString === "!true") {
  51594. booleanString = "false";
  51595. }
  51596. else if (booleanString === "!false") {
  51597. booleanString = "true";
  51598. }
  51599. return booleanString;
  51600. };
  51601. return AndOrNotEvaluator;
  51602. }());
  51603. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  51604. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51605. })(BABYLON || (BABYLON = {}));
  51606. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  51607. var BABYLON;
  51608. (function (BABYLON) {
  51609. var Database = (function () {
  51610. function Database(urlToScene, callbackManifestChecked) {
  51611. // Handling various flavors of prefixed version of IndexedDB
  51612. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  51613. this.callbackManifestChecked = callbackManifestChecked;
  51614. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  51615. this.db = null;
  51616. this.enableSceneOffline = false;
  51617. this.enableTexturesOffline = false;
  51618. this.manifestVersionFound = 0;
  51619. this.mustUpdateRessources = false;
  51620. this.hasReachedQuota = false;
  51621. if (!Database.IDBStorageEnabled) {
  51622. this.callbackManifestChecked(true);
  51623. }
  51624. else {
  51625. this.checkManifestFile();
  51626. }
  51627. }
  51628. Database.prototype.checkManifestFile = function () {
  51629. var _this = this;
  51630. function noManifestFile() {
  51631. that.enableSceneOffline = false;
  51632. that.enableTexturesOffline = false;
  51633. that.callbackManifestChecked(false);
  51634. }
  51635. var that = this;
  51636. var timeStampUsed = false;
  51637. var manifestURL = this.currentSceneUrl + ".manifest";
  51638. var xhr = new XMLHttpRequest();
  51639. if (navigator.onLine) {
  51640. // Adding a timestamp to by-pass browsers' cache
  51641. timeStampUsed = true;
  51642. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  51643. }
  51644. xhr.open("GET", manifestURL, true);
  51645. xhr.addEventListener("load", function () {
  51646. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51647. try {
  51648. var manifestFile = JSON.parse(xhr.response);
  51649. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  51650. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  51651. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  51652. _this.manifestVersionFound = manifestFile.version;
  51653. }
  51654. if (_this.callbackManifestChecked) {
  51655. _this.callbackManifestChecked(true);
  51656. }
  51657. }
  51658. catch (ex) {
  51659. noManifestFile();
  51660. }
  51661. }
  51662. else {
  51663. noManifestFile();
  51664. }
  51665. }, false);
  51666. xhr.addEventListener("error", function (event) {
  51667. if (timeStampUsed) {
  51668. timeStampUsed = false;
  51669. // Let's retry without the timeStamp
  51670. // It could fail when coupled with HTML5 Offline API
  51671. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  51672. xhr.open("GET", retryManifestURL, true);
  51673. xhr.send();
  51674. }
  51675. else {
  51676. noManifestFile();
  51677. }
  51678. }, false);
  51679. try {
  51680. xhr.send();
  51681. }
  51682. catch (ex) {
  51683. BABYLON.Tools.Error("Error on XHR send request.");
  51684. that.callbackManifestChecked(false);
  51685. }
  51686. };
  51687. Database.prototype.openAsync = function (successCallback, errorCallback) {
  51688. var _this = this;
  51689. function handleError() {
  51690. that.isSupported = false;
  51691. if (errorCallback)
  51692. errorCallback();
  51693. }
  51694. var that = this;
  51695. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  51696. // Your browser doesn't support IndexedDB
  51697. this.isSupported = false;
  51698. if (errorCallback)
  51699. errorCallback();
  51700. }
  51701. else {
  51702. // If the DB hasn't been opened or created yet
  51703. if (!this.db) {
  51704. this.hasReachedQuota = false;
  51705. this.isSupported = true;
  51706. var request = this.idbFactory.open("babylonjs", 1);
  51707. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  51708. request.onerror = function (event) {
  51709. handleError();
  51710. };
  51711. // executes when a version change transaction cannot complete due to other active transactions
  51712. request.onblocked = function (event) {
  51713. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  51714. handleError();
  51715. };
  51716. // DB has been opened successfully
  51717. request.onsuccess = function (event) {
  51718. _this.db = request.result;
  51719. successCallback();
  51720. };
  51721. // Initialization of the DB. Creating Scenes & Textures stores
  51722. request.onupgradeneeded = function (event) {
  51723. _this.db = (event.target).result;
  51724. try {
  51725. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  51726. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  51727. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  51728. }
  51729. catch (ex) {
  51730. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  51731. handleError();
  51732. }
  51733. };
  51734. }
  51735. else {
  51736. if (successCallback)
  51737. successCallback();
  51738. }
  51739. }
  51740. };
  51741. Database.prototype.loadImageFromDB = function (url, image) {
  51742. var _this = this;
  51743. var completeURL = Database.ReturnFullUrlLocation(url);
  51744. var saveAndLoadImage = function () {
  51745. if (!_this.hasReachedQuota && _this.db !== null) {
  51746. // the texture is not yet in the DB, let's try to save it
  51747. _this._saveImageIntoDBAsync(completeURL, image);
  51748. }
  51749. else {
  51750. image.src = url;
  51751. }
  51752. };
  51753. if (!this.mustUpdateRessources) {
  51754. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  51755. }
  51756. else {
  51757. saveAndLoadImage();
  51758. }
  51759. };
  51760. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  51761. if (this.isSupported && this.db !== null) {
  51762. var texture;
  51763. var transaction = this.db.transaction(["textures"]);
  51764. transaction.onabort = function (event) {
  51765. image.src = url;
  51766. };
  51767. transaction.oncomplete = function (event) {
  51768. var blobTextureURL;
  51769. if (texture) {
  51770. var URL = window.URL || window.webkitURL;
  51771. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  51772. image.onerror = function () {
  51773. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  51774. image.src = url;
  51775. };
  51776. image.src = blobTextureURL;
  51777. }
  51778. else {
  51779. notInDBCallback();
  51780. }
  51781. };
  51782. var getRequest = transaction.objectStore("textures").get(url);
  51783. getRequest.onsuccess = function (event) {
  51784. texture = (event.target).result;
  51785. };
  51786. getRequest.onerror = function (event) {
  51787. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  51788. image.src = url;
  51789. };
  51790. }
  51791. else {
  51792. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51793. image.src = url;
  51794. }
  51795. };
  51796. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  51797. var _this = this;
  51798. if (this.isSupported) {
  51799. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  51800. var generateBlobUrl = function () {
  51801. var blobTextureURL;
  51802. if (blob) {
  51803. var URL = window.URL || window.webkitURL;
  51804. try {
  51805. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  51806. }
  51807. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  51808. catch (ex) {
  51809. blobTextureURL = URL.createObjectURL(blob);
  51810. }
  51811. }
  51812. image.src = blobTextureURL;
  51813. };
  51814. if (Database.IsUASupportingBlobStorage) {
  51815. var xhr = new XMLHttpRequest(), blob;
  51816. xhr.open("GET", url, true);
  51817. xhr.responseType = "blob";
  51818. xhr.addEventListener("load", function () {
  51819. if (xhr.status === 200) {
  51820. // Blob as response (XHR2)
  51821. blob = xhr.response;
  51822. var transaction = _this.db.transaction(["textures"], "readwrite");
  51823. // the transaction could abort because of a QuotaExceededError error
  51824. transaction.onabort = function (event) {
  51825. try {
  51826. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  51827. var error = event.srcElement['error'];
  51828. if (error && error.name === "QuotaExceededError") {
  51829. _this.hasReachedQuota = true;
  51830. }
  51831. }
  51832. catch (ex) { }
  51833. generateBlobUrl();
  51834. };
  51835. transaction.oncomplete = function (event) {
  51836. generateBlobUrl();
  51837. };
  51838. var newTexture = { textureUrl: url, data: blob };
  51839. try {
  51840. // Put the blob into the dabase
  51841. var addRequest = transaction.objectStore("textures").put(newTexture);
  51842. addRequest.onsuccess = function (event) {
  51843. };
  51844. addRequest.onerror = function (event) {
  51845. generateBlobUrl();
  51846. };
  51847. }
  51848. catch (ex) {
  51849. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  51850. if (ex.code === 25) {
  51851. Database.IsUASupportingBlobStorage = false;
  51852. }
  51853. image.src = url;
  51854. }
  51855. }
  51856. else {
  51857. image.src = url;
  51858. }
  51859. }, false);
  51860. xhr.addEventListener("error", function (event) {
  51861. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  51862. image.src = url;
  51863. }, false);
  51864. xhr.send();
  51865. }
  51866. else {
  51867. image.src = url;
  51868. }
  51869. }
  51870. else {
  51871. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51872. image.src = url;
  51873. }
  51874. };
  51875. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  51876. var _this = this;
  51877. var updateVersion = function () {
  51878. // the version is not yet in the DB or we need to update it
  51879. _this._saveVersionIntoDBAsync(url, versionLoaded);
  51880. };
  51881. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  51882. };
  51883. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  51884. var _this = this;
  51885. if (this.isSupported) {
  51886. var version;
  51887. try {
  51888. var transaction = this.db.transaction(["versions"]);
  51889. transaction.oncomplete = function (event) {
  51890. if (version) {
  51891. // If the version in the JSON file is > than the version in DB
  51892. if (_this.manifestVersionFound > version.data) {
  51893. _this.mustUpdateRessources = true;
  51894. updateInDBCallback();
  51895. }
  51896. else {
  51897. callback(version.data);
  51898. }
  51899. }
  51900. else {
  51901. _this.mustUpdateRessources = true;
  51902. updateInDBCallback();
  51903. }
  51904. };
  51905. transaction.onabort = function (event) {
  51906. callback(-1);
  51907. };
  51908. var getRequest = transaction.objectStore("versions").get(url);
  51909. getRequest.onsuccess = function (event) {
  51910. version = (event.target).result;
  51911. };
  51912. getRequest.onerror = function (event) {
  51913. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  51914. callback(-1);
  51915. };
  51916. }
  51917. catch (ex) {
  51918. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  51919. callback(-1);
  51920. }
  51921. }
  51922. else {
  51923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51924. callback(-1);
  51925. }
  51926. };
  51927. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  51928. var _this = this;
  51929. if (this.isSupported && !this.hasReachedQuota) {
  51930. try {
  51931. // Open a transaction to the database
  51932. var transaction = this.db.transaction(["versions"], "readwrite");
  51933. // the transaction could abort because of a QuotaExceededError error
  51934. transaction.onabort = function (event) {
  51935. try {
  51936. var error = event.srcElement['error'];
  51937. if (error && error.name === "QuotaExceededError") {
  51938. _this.hasReachedQuota = true;
  51939. }
  51940. }
  51941. catch (ex) { }
  51942. callback(-1);
  51943. };
  51944. transaction.oncomplete = function (event) {
  51945. callback(_this.manifestVersionFound);
  51946. };
  51947. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  51948. // Put the scene into the database
  51949. var addRequest = transaction.objectStore("versions").put(newVersion);
  51950. addRequest.onsuccess = function (event) {
  51951. };
  51952. addRequest.onerror = function (event) {
  51953. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  51954. };
  51955. }
  51956. catch (ex) {
  51957. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  51958. callback(-1);
  51959. }
  51960. }
  51961. else {
  51962. callback(-1);
  51963. }
  51964. };
  51965. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  51966. var _this = this;
  51967. var completeUrl = Database.ReturnFullUrlLocation(url);
  51968. var saveAndLoadFile = function () {
  51969. // the scene is not yet in the DB, let's try to save it
  51970. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  51971. };
  51972. this._checkVersionFromDB(completeUrl, function (version) {
  51973. if (version !== -1) {
  51974. if (!_this.mustUpdateRessources) {
  51975. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  51976. }
  51977. else {
  51978. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  51979. }
  51980. }
  51981. else {
  51982. errorCallback();
  51983. }
  51984. });
  51985. };
  51986. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  51987. if (this.isSupported) {
  51988. var targetStore;
  51989. if (url.indexOf(".babylon") !== -1) {
  51990. targetStore = "scenes";
  51991. }
  51992. else {
  51993. targetStore = "textures";
  51994. }
  51995. var file;
  51996. var transaction = this.db.transaction([targetStore]);
  51997. transaction.oncomplete = function (event) {
  51998. if (file) {
  51999. callback(file.data);
  52000. }
  52001. else {
  52002. notInDBCallback();
  52003. }
  52004. };
  52005. transaction.onabort = function (event) {
  52006. notInDBCallback();
  52007. };
  52008. var getRequest = transaction.objectStore(targetStore).get(url);
  52009. getRequest.onsuccess = function (event) {
  52010. file = (event.target).result;
  52011. };
  52012. getRequest.onerror = function (event) {
  52013. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  52014. notInDBCallback();
  52015. };
  52016. }
  52017. else {
  52018. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52019. callback();
  52020. }
  52021. };
  52022. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  52023. var _this = this;
  52024. if (this.isSupported) {
  52025. var targetStore;
  52026. if (url.indexOf(".babylon") !== -1) {
  52027. targetStore = "scenes";
  52028. }
  52029. else {
  52030. targetStore = "textures";
  52031. }
  52032. // Create XHR
  52033. var xhr = new XMLHttpRequest();
  52034. var fileData;
  52035. xhr.open("GET", url, true);
  52036. if (useArrayBuffer) {
  52037. xhr.responseType = "arraybuffer";
  52038. }
  52039. xhr.onprogress = progressCallback;
  52040. xhr.addEventListener("load", function () {
  52041. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  52042. // Blob as response (XHR2)
  52043. //fileData = xhr.responseText;
  52044. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  52045. if (!_this.hasReachedQuota) {
  52046. // Open a transaction to the database
  52047. var transaction = _this.db.transaction([targetStore], "readwrite");
  52048. // the transaction could abort because of a QuotaExceededError error
  52049. transaction.onabort = function (event) {
  52050. try {
  52051. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52052. var error = event.srcElement['error'];
  52053. if (error && error.name === "QuotaExceededError") {
  52054. _this.hasReachedQuota = true;
  52055. }
  52056. }
  52057. catch (ex) { }
  52058. callback(fileData);
  52059. };
  52060. transaction.oncomplete = function (event) {
  52061. callback(fileData);
  52062. };
  52063. var newFile;
  52064. if (targetStore === "scenes") {
  52065. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  52066. }
  52067. else {
  52068. newFile = { textureUrl: url, data: fileData };
  52069. }
  52070. try {
  52071. // Put the scene into the database
  52072. var addRequest = transaction.objectStore(targetStore).put(newFile);
  52073. addRequest.onsuccess = function (event) {
  52074. };
  52075. addRequest.onerror = function (event) {
  52076. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  52077. };
  52078. }
  52079. catch (ex) {
  52080. callback(fileData);
  52081. }
  52082. }
  52083. else {
  52084. callback(fileData);
  52085. }
  52086. }
  52087. else {
  52088. callback();
  52089. }
  52090. }, false);
  52091. xhr.addEventListener("error", function (event) {
  52092. BABYLON.Tools.Error("error on XHR request.");
  52093. callback();
  52094. }, false);
  52095. xhr.send();
  52096. }
  52097. else {
  52098. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52099. callback();
  52100. }
  52101. };
  52102. Database.IsUASupportingBlobStorage = true;
  52103. Database.IDBStorageEnabled = true;
  52104. Database.parseURL = function (url) {
  52105. var a = document.createElement('a');
  52106. a.href = url;
  52107. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  52108. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  52109. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  52110. return absLocation;
  52111. };
  52112. Database.ReturnFullUrlLocation = function (url) {
  52113. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  52114. return (Database.parseURL(window.location.href) + url);
  52115. }
  52116. else {
  52117. return url;
  52118. }
  52119. };
  52120. return Database;
  52121. }());
  52122. BABYLON.Database = Database;
  52123. })(BABYLON || (BABYLON = {}));
  52124. //# sourceMappingURL=babylon.database.js.map
  52125. var BABYLON;
  52126. (function (BABYLON) {
  52127. var FresnelParameters = (function () {
  52128. function FresnelParameters() {
  52129. this._isEnabled = true;
  52130. this.leftColor = BABYLON.Color3.White();
  52131. this.rightColor = BABYLON.Color3.Black();
  52132. this.bias = 0;
  52133. this.power = 1;
  52134. }
  52135. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  52136. get: function () {
  52137. return this._isEnabled;
  52138. },
  52139. set: function (value) {
  52140. if (this._isEnabled === value) {
  52141. return;
  52142. }
  52143. this._isEnabled = value;
  52144. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  52145. },
  52146. enumerable: true,
  52147. configurable: true
  52148. });
  52149. FresnelParameters.prototype.clone = function () {
  52150. var newFresnelParameters = new FresnelParameters();
  52151. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  52152. return newFresnelParameters;
  52153. };
  52154. FresnelParameters.prototype.serialize = function () {
  52155. var serializationObject = {};
  52156. serializationObject.isEnabled = this.isEnabled;
  52157. serializationObject.leftColor = this.leftColor;
  52158. serializationObject.rightColor = this.rightColor;
  52159. serializationObject.bias = this.bias;
  52160. serializationObject.power = this.power;
  52161. return serializationObject;
  52162. };
  52163. FresnelParameters.Parse = function (parsedFresnelParameters) {
  52164. var fresnelParameters = new FresnelParameters();
  52165. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  52166. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  52167. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  52168. fresnelParameters.bias = parsedFresnelParameters.bias;
  52169. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  52170. return fresnelParameters;
  52171. };
  52172. return FresnelParameters;
  52173. }());
  52174. BABYLON.FresnelParameters = FresnelParameters;
  52175. })(BABYLON || (BABYLON = {}));
  52176. //# sourceMappingURL=babylon.fresnelParameters.js.map
  52177. var BABYLON;
  52178. (function (BABYLON) {
  52179. var MultiMaterial = (function (_super) {
  52180. __extends(MultiMaterial, _super);
  52181. function MultiMaterial(name, scene) {
  52182. var _this = _super.call(this, name, scene, true) || this;
  52183. scene.multiMaterials.push(_this);
  52184. _this.subMaterials = new Array();
  52185. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  52186. return _this;
  52187. }
  52188. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  52189. get: function () {
  52190. return this._subMaterials;
  52191. },
  52192. set: function (value) {
  52193. this._subMaterials = value;
  52194. this._hookArray(value);
  52195. },
  52196. enumerable: true,
  52197. configurable: true
  52198. });
  52199. MultiMaterial.prototype._hookArray = function (array) {
  52200. var _this = this;
  52201. var oldPush = array.push;
  52202. array.push = function () {
  52203. var items = [];
  52204. for (var _i = 0; _i < arguments.length; _i++) {
  52205. items[_i] = arguments[_i];
  52206. }
  52207. var result = oldPush.apply(array, items);
  52208. _this._markAllSubMeshesAsTexturesDirty();
  52209. return result;
  52210. };
  52211. var oldSplice = array.splice;
  52212. array.splice = function (index, deleteCount) {
  52213. var deleted = oldSplice.apply(array, [index, deleteCount]);
  52214. _this._markAllSubMeshesAsTexturesDirty();
  52215. return deleted;
  52216. };
  52217. };
  52218. // Properties
  52219. MultiMaterial.prototype.getSubMaterial = function (index) {
  52220. if (index < 0 || index >= this.subMaterials.length) {
  52221. return this.getScene().defaultMaterial;
  52222. }
  52223. return this.subMaterials[index];
  52224. };
  52225. MultiMaterial.prototype.getActiveTextures = function () {
  52226. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  52227. var _a;
  52228. };
  52229. // Methods
  52230. MultiMaterial.prototype.getClassName = function () {
  52231. return "MultiMaterial";
  52232. };
  52233. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  52234. for (var index = 0; index < this.subMaterials.length; index++) {
  52235. var subMaterial = this.subMaterials[index];
  52236. if (subMaterial) {
  52237. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  52238. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  52239. return false;
  52240. }
  52241. continue;
  52242. }
  52243. if (!this.subMaterials[index].isReady(mesh)) {
  52244. return false;
  52245. }
  52246. }
  52247. }
  52248. return true;
  52249. };
  52250. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  52251. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  52252. for (var index = 0; index < this.subMaterials.length; index++) {
  52253. var subMaterial = null;
  52254. if (cloneChildren) {
  52255. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  52256. }
  52257. else {
  52258. subMaterial = this.subMaterials[index];
  52259. }
  52260. newMultiMaterial.subMaterials.push(subMaterial);
  52261. }
  52262. return newMultiMaterial;
  52263. };
  52264. MultiMaterial.prototype.serialize = function () {
  52265. var serializationObject = {};
  52266. serializationObject.name = this.name;
  52267. serializationObject.id = this.id;
  52268. serializationObject.tags = BABYLON.Tags.GetTags(this);
  52269. serializationObject.materials = [];
  52270. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  52271. var subMat = this.subMaterials[matIndex];
  52272. if (subMat) {
  52273. serializationObject.materials.push(subMat.id);
  52274. }
  52275. else {
  52276. serializationObject.materials.push(null);
  52277. }
  52278. }
  52279. return serializationObject;
  52280. };
  52281. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52282. var scene = this.getScene();
  52283. if (!scene) {
  52284. return;
  52285. }
  52286. var index = scene.multiMaterials.indexOf(this);
  52287. if (index >= 0) {
  52288. scene.multiMaterials.splice(index, 1);
  52289. }
  52290. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52291. };
  52292. return MultiMaterial;
  52293. }(BABYLON.Material));
  52294. BABYLON.MultiMaterial = MultiMaterial;
  52295. })(BABYLON || (BABYLON = {}));
  52296. //# sourceMappingURL=babylon.multiMaterial.js.map
  52297. var BABYLON;
  52298. (function (BABYLON) {
  52299. var FreeCameraTouchInput = (function () {
  52300. function FreeCameraTouchInput() {
  52301. this._offsetX = null;
  52302. this._offsetY = null;
  52303. this._pointerCount = 0;
  52304. this._pointerPressed = new Array();
  52305. this.touchAngularSensibility = 200000.0;
  52306. this.touchMoveSensibility = 250.0;
  52307. }
  52308. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  52309. var _this = this;
  52310. var previousPosition;
  52311. if (this._pointerInput === undefined) {
  52312. this._onLostFocus = function (evt) {
  52313. _this._offsetX = null;
  52314. _this._offsetY = null;
  52315. };
  52316. this._pointerInput = function (p, s) {
  52317. var evt = p.event;
  52318. if (evt.pointerType === "mouse") {
  52319. return;
  52320. }
  52321. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  52322. if (!noPreventDefault) {
  52323. evt.preventDefault();
  52324. }
  52325. _this._pointerPressed.push(evt.pointerId);
  52326. if (_this._pointerPressed.length !== 1) {
  52327. return;
  52328. }
  52329. previousPosition = {
  52330. x: evt.clientX,
  52331. y: evt.clientY
  52332. };
  52333. }
  52334. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  52335. if (!noPreventDefault) {
  52336. evt.preventDefault();
  52337. }
  52338. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52339. if (index === -1) {
  52340. return;
  52341. }
  52342. _this._pointerPressed.splice(index, 1);
  52343. if (index != 0) {
  52344. return;
  52345. }
  52346. previousPosition = null;
  52347. _this._offsetX = null;
  52348. _this._offsetY = null;
  52349. }
  52350. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  52351. if (!noPreventDefault) {
  52352. evt.preventDefault();
  52353. }
  52354. if (!previousPosition) {
  52355. return;
  52356. }
  52357. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52358. if (index != 0) {
  52359. return;
  52360. }
  52361. _this._offsetX = evt.clientX - previousPosition.x;
  52362. _this._offsetY = -(evt.clientY - previousPosition.y);
  52363. }
  52364. };
  52365. }
  52366. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  52367. element.addEventListener("blur", this._onLostFocus);
  52368. };
  52369. FreeCameraTouchInput.prototype.detachControl = function (element) {
  52370. if (this._pointerInput && element) {
  52371. this.camera.getScene().onPointerObservable.remove(this._observer);
  52372. this._observer = null;
  52373. element.removeEventListener("blur", this._onLostFocus);
  52374. this._onLostFocus = null;
  52375. this._pointerPressed = [];
  52376. this._offsetX = null;
  52377. this._offsetY = null;
  52378. this._pointerCount = 0;
  52379. }
  52380. };
  52381. FreeCameraTouchInput.prototype.checkInputs = function () {
  52382. if (this._offsetX) {
  52383. var camera = this.camera;
  52384. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  52385. if (this._pointerPressed.length > 1) {
  52386. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  52387. }
  52388. else {
  52389. var speed = camera._computeLocalCameraSpeed();
  52390. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  52391. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  52392. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  52393. }
  52394. }
  52395. };
  52396. FreeCameraTouchInput.prototype.getClassName = function () {
  52397. return "FreeCameraTouchInput";
  52398. };
  52399. FreeCameraTouchInput.prototype.getSimpleName = function () {
  52400. return "touch";
  52401. };
  52402. __decorate([
  52403. BABYLON.serialize()
  52404. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  52405. __decorate([
  52406. BABYLON.serialize()
  52407. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  52408. return FreeCameraTouchInput;
  52409. }());
  52410. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  52411. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  52412. })(BABYLON || (BABYLON = {}));
  52413. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  52414. /// <reference path="babylon.freeCamera.ts" />
  52415. var BABYLON;
  52416. (function (BABYLON) {
  52417. // We're mainly based on the logic defined into the FreeCamera code
  52418. var TouchCamera = (function (_super) {
  52419. __extends(TouchCamera, _super);
  52420. //-- end properties for backward compatibility for inputs
  52421. function TouchCamera(name, position, scene) {
  52422. var _this = _super.call(this, name, position, scene) || this;
  52423. _this.inputs.addTouch();
  52424. _this._setupInputs();
  52425. return _this;
  52426. }
  52427. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  52428. //-- Begin properties for backward compatibility for inputs
  52429. get: function () {
  52430. var touch = this.inputs.attached["touch"];
  52431. if (touch)
  52432. return touch.touchAngularSensibility;
  52433. },
  52434. set: function (value) {
  52435. var touch = this.inputs.attached["touch"];
  52436. if (touch)
  52437. touch.touchAngularSensibility = value;
  52438. },
  52439. enumerable: true,
  52440. configurable: true
  52441. });
  52442. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  52443. get: function () {
  52444. var touch = this.inputs.attached["touch"];
  52445. if (touch)
  52446. return touch.touchMoveSensibility;
  52447. },
  52448. set: function (value) {
  52449. var touch = this.inputs.attached["touch"];
  52450. if (touch)
  52451. touch.touchMoveSensibility = value;
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. TouchCamera.prototype.getClassName = function () {
  52457. return "TouchCamera";
  52458. };
  52459. TouchCamera.prototype._setupInputs = function () {
  52460. var mouse = this.inputs.attached["mouse"];
  52461. if (mouse) {
  52462. mouse.touchEnabled = false;
  52463. }
  52464. };
  52465. return TouchCamera;
  52466. }(BABYLON.FreeCamera));
  52467. BABYLON.TouchCamera = TouchCamera;
  52468. })(BABYLON || (BABYLON = {}));
  52469. //# sourceMappingURL=babylon.touchCamera.js.map
  52470. var BABYLON;
  52471. (function (BABYLON) {
  52472. var ProceduralTexture = (function (_super) {
  52473. __extends(ProceduralTexture, _super);
  52474. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  52475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52476. if (isCube === void 0) { isCube = false; }
  52477. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  52478. _this.isCube = isCube;
  52479. _this.isEnabled = true;
  52480. _this._currentRefreshId = -1;
  52481. _this._refreshRate = 1;
  52482. _this._vertexBuffers = {};
  52483. _this._uniforms = new Array();
  52484. _this._samplers = new Array();
  52485. _this._textures = {};
  52486. _this._floats = {};
  52487. _this._floatsArrays = {};
  52488. _this._colors3 = {};
  52489. _this._colors4 = {};
  52490. _this._vectors2 = {};
  52491. _this._vectors3 = {};
  52492. _this._matrices = {};
  52493. _this._fallbackTextureUsed = false;
  52494. scene._proceduralTextures.push(_this);
  52495. _this.name = name;
  52496. _this.isRenderTarget = true;
  52497. _this._size = size;
  52498. _this._generateMipMaps = generateMipMaps;
  52499. _this.setFragment(fragment);
  52500. _this._fallbackTexture = fallbackTexture;
  52501. var engine = scene.getEngine();
  52502. if (isCube) {
  52503. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  52504. _this.setFloat("face", 0);
  52505. }
  52506. else {
  52507. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  52508. }
  52509. // VBO
  52510. var vertices = [];
  52511. vertices.push(1, 1);
  52512. vertices.push(-1, 1);
  52513. vertices.push(-1, -1);
  52514. vertices.push(1, -1);
  52515. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52516. _this._createIndexBuffer();
  52517. return _this;
  52518. }
  52519. ProceduralTexture.prototype._createIndexBuffer = function () {
  52520. var engine = this.getScene().getEngine();
  52521. // Indices
  52522. var indices = [];
  52523. indices.push(0);
  52524. indices.push(1);
  52525. indices.push(2);
  52526. indices.push(0);
  52527. indices.push(2);
  52528. indices.push(3);
  52529. this._indexBuffer = engine.createIndexBuffer(indices);
  52530. };
  52531. ProceduralTexture.prototype._rebuild = function () {
  52532. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  52533. this._createIndexBuffer();
  52534. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52535. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52536. }
  52537. };
  52538. ProceduralTexture.prototype.reset = function () {
  52539. if (this._effect === undefined) {
  52540. return;
  52541. }
  52542. var engine = this.getScene().getEngine();
  52543. engine._releaseEffect(this._effect);
  52544. };
  52545. ProceduralTexture.prototype.isReady = function () {
  52546. var _this = this;
  52547. var engine = this.getScene().getEngine();
  52548. var shaders;
  52549. if (!this._fragment) {
  52550. return false;
  52551. }
  52552. if (this._fallbackTextureUsed) {
  52553. return true;
  52554. }
  52555. if (this._fragment.fragmentElement !== undefined) {
  52556. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  52557. }
  52558. else {
  52559. shaders = { vertex: "procedural", fragment: this._fragment };
  52560. }
  52561. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  52562. _this.releaseInternalTexture();
  52563. if (_this._fallbackTexture) {
  52564. _this._texture = _this._fallbackTexture._texture;
  52565. _this._texture.incrementReferences();
  52566. }
  52567. _this._fallbackTextureUsed = true;
  52568. });
  52569. return this._effect.isReady();
  52570. };
  52571. ProceduralTexture.prototype.resetRefreshCounter = function () {
  52572. this._currentRefreshId = -1;
  52573. };
  52574. ProceduralTexture.prototype.setFragment = function (fragment) {
  52575. this._fragment = fragment;
  52576. };
  52577. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  52578. get: function () {
  52579. return this._refreshRate;
  52580. },
  52581. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  52582. set: function (value) {
  52583. this._refreshRate = value;
  52584. this.resetRefreshCounter();
  52585. },
  52586. enumerable: true,
  52587. configurable: true
  52588. });
  52589. ProceduralTexture.prototype._shouldRender = function () {
  52590. if (!this.isEnabled || !this.isReady() || !this._texture) {
  52591. return false;
  52592. }
  52593. if (this._fallbackTextureUsed) {
  52594. return false;
  52595. }
  52596. if (this._currentRefreshId === -1) {
  52597. this._currentRefreshId = 1;
  52598. return true;
  52599. }
  52600. if (this.refreshRate === this._currentRefreshId) {
  52601. this._currentRefreshId = 1;
  52602. return true;
  52603. }
  52604. this._currentRefreshId++;
  52605. return false;
  52606. };
  52607. ProceduralTexture.prototype.getRenderSize = function () {
  52608. return this._size;
  52609. };
  52610. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  52611. if (this._fallbackTextureUsed) {
  52612. return;
  52613. }
  52614. this.releaseInternalTexture();
  52615. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  52616. };
  52617. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  52618. if (this._uniforms.indexOf(uniformName) === -1) {
  52619. this._uniforms.push(uniformName);
  52620. }
  52621. };
  52622. ProceduralTexture.prototype.setTexture = function (name, texture) {
  52623. if (this._samplers.indexOf(name) === -1) {
  52624. this._samplers.push(name);
  52625. }
  52626. this._textures[name] = texture;
  52627. return this;
  52628. };
  52629. ProceduralTexture.prototype.setFloat = function (name, value) {
  52630. this._checkUniform(name);
  52631. this._floats[name] = value;
  52632. return this;
  52633. };
  52634. ProceduralTexture.prototype.setFloats = function (name, value) {
  52635. this._checkUniform(name);
  52636. this._floatsArrays[name] = value;
  52637. return this;
  52638. };
  52639. ProceduralTexture.prototype.setColor3 = function (name, value) {
  52640. this._checkUniform(name);
  52641. this._colors3[name] = value;
  52642. return this;
  52643. };
  52644. ProceduralTexture.prototype.setColor4 = function (name, value) {
  52645. this._checkUniform(name);
  52646. this._colors4[name] = value;
  52647. return this;
  52648. };
  52649. ProceduralTexture.prototype.setVector2 = function (name, value) {
  52650. this._checkUniform(name);
  52651. this._vectors2[name] = value;
  52652. return this;
  52653. };
  52654. ProceduralTexture.prototype.setVector3 = function (name, value) {
  52655. this._checkUniform(name);
  52656. this._vectors3[name] = value;
  52657. return this;
  52658. };
  52659. ProceduralTexture.prototype.setMatrix = function (name, value) {
  52660. this._checkUniform(name);
  52661. this._matrices[name] = value;
  52662. return this;
  52663. };
  52664. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  52665. var scene = this.getScene();
  52666. var engine = scene.getEngine();
  52667. // Render
  52668. engine.enableEffect(this._effect);
  52669. engine.setState(false);
  52670. // Texture
  52671. for (var name in this._textures) {
  52672. this._effect.setTexture(name, this._textures[name]);
  52673. }
  52674. // Float
  52675. for (name in this._floats) {
  52676. this._effect.setFloat(name, this._floats[name]);
  52677. }
  52678. // Floats
  52679. for (name in this._floatsArrays) {
  52680. this._effect.setArray(name, this._floatsArrays[name]);
  52681. }
  52682. // Color3
  52683. for (name in this._colors3) {
  52684. this._effect.setColor3(name, this._colors3[name]);
  52685. }
  52686. // Color4
  52687. for (name in this._colors4) {
  52688. var color = this._colors4[name];
  52689. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52690. }
  52691. // Vector2
  52692. for (name in this._vectors2) {
  52693. this._effect.setVector2(name, this._vectors2[name]);
  52694. }
  52695. // Vector3
  52696. for (name in this._vectors3) {
  52697. this._effect.setVector3(name, this._vectors3[name]);
  52698. }
  52699. // Matrix
  52700. for (name in this._matrices) {
  52701. this._effect.setMatrix(name, this._matrices[name]);
  52702. }
  52703. if (this.isCube) {
  52704. for (var face = 0; face < 6; face++) {
  52705. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  52706. // VBOs
  52707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52708. this._effect.setFloat("face", face);
  52709. // Clear
  52710. engine.clear(scene.clearColor, true, true, true);
  52711. // Draw order
  52712. engine.draw(true, 0, 6);
  52713. // Mipmaps
  52714. if (face === 5) {
  52715. engine.generateMipMapsForCubemap(this._texture);
  52716. }
  52717. }
  52718. }
  52719. else {
  52720. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  52721. // VBOs
  52722. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52723. // Clear
  52724. engine.clear(scene.clearColor, true, true, true);
  52725. // Draw order
  52726. engine.draw(true, 0, 6);
  52727. }
  52728. // Unbind
  52729. engine.unBindFramebuffer(this._texture, this.isCube);
  52730. if (this.onGenerated) {
  52731. this.onGenerated();
  52732. }
  52733. };
  52734. ProceduralTexture.prototype.clone = function () {
  52735. var textureSize = this.getSize();
  52736. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  52737. // Base texture
  52738. newTexture.hasAlpha = this.hasAlpha;
  52739. newTexture.level = this.level;
  52740. // RenderTarget Texture
  52741. newTexture.coordinatesMode = this.coordinatesMode;
  52742. return newTexture;
  52743. };
  52744. ProceduralTexture.prototype.dispose = function () {
  52745. var index = this.getScene()._proceduralTextures.indexOf(this);
  52746. if (index >= 0) {
  52747. this.getScene()._proceduralTextures.splice(index, 1);
  52748. }
  52749. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52750. if (vertexBuffer) {
  52751. vertexBuffer.dispose();
  52752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52753. }
  52754. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  52755. this._indexBuffer = null;
  52756. }
  52757. _super.prototype.dispose.call(this);
  52758. };
  52759. return ProceduralTexture;
  52760. }(BABYLON.Texture));
  52761. BABYLON.ProceduralTexture = ProceduralTexture;
  52762. })(BABYLON || (BABYLON = {}));
  52763. //# sourceMappingURL=babylon.proceduralTexture.js.map
  52764. /// <reference path="babylon.proceduralTexture.ts" />
  52765. var BABYLON;
  52766. (function (BABYLON) {
  52767. var CustomProceduralTexture = (function (_super) {
  52768. __extends(CustomProceduralTexture, _super);
  52769. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  52770. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  52771. _this._animate = true;
  52772. _this._time = 0;
  52773. _this._texturePath = texturePath;
  52774. //Try to load json
  52775. _this.loadJson(texturePath);
  52776. _this.refreshRate = 1;
  52777. return _this;
  52778. }
  52779. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  52780. var _this = this;
  52781. var that = this;
  52782. function noConfigFile() {
  52783. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  52784. try {
  52785. that.setFragment(that._texturePath);
  52786. }
  52787. catch (ex) {
  52788. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  52789. }
  52790. }
  52791. var configFileUrl = jsonUrl + "/config.json";
  52792. var xhr = new XMLHttpRequest();
  52793. xhr.open("GET", configFileUrl, true);
  52794. xhr.addEventListener("load", function () {
  52795. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  52796. try {
  52797. _this._config = JSON.parse(xhr.response);
  52798. _this.updateShaderUniforms();
  52799. _this.updateTextures();
  52800. _this.setFragment(_this._texturePath + "/custom");
  52801. _this._animate = _this._config.animate;
  52802. _this.refreshRate = _this._config.refreshrate;
  52803. }
  52804. catch (ex) {
  52805. noConfigFile();
  52806. }
  52807. }
  52808. else {
  52809. noConfigFile();
  52810. }
  52811. }, false);
  52812. xhr.addEventListener("error", function () {
  52813. noConfigFile();
  52814. }, false);
  52815. try {
  52816. xhr.send();
  52817. }
  52818. catch (ex) {
  52819. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  52820. }
  52821. };
  52822. CustomProceduralTexture.prototype.isReady = function () {
  52823. if (!_super.prototype.isReady.call(this)) {
  52824. return false;
  52825. }
  52826. for (var name in this._textures) {
  52827. var texture = this._textures[name];
  52828. if (!texture.isReady()) {
  52829. return false;
  52830. }
  52831. }
  52832. return true;
  52833. };
  52834. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  52835. if (this._animate) {
  52836. this._time += this.getScene().getAnimationRatio() * 0.03;
  52837. this.updateShaderUniforms();
  52838. }
  52839. _super.prototype.render.call(this, useCameraPostProcess);
  52840. };
  52841. CustomProceduralTexture.prototype.updateTextures = function () {
  52842. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  52843. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  52844. }
  52845. };
  52846. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  52847. if (this._config) {
  52848. for (var j = 0; j < this._config.uniforms.length; j++) {
  52849. var uniform = this._config.uniforms[j];
  52850. switch (uniform.type) {
  52851. case "float":
  52852. this.setFloat(uniform.name, uniform.value);
  52853. break;
  52854. case "color3":
  52855. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  52856. break;
  52857. case "color4":
  52858. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  52859. break;
  52860. case "vector2":
  52861. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  52862. break;
  52863. case "vector3":
  52864. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  52865. break;
  52866. }
  52867. }
  52868. }
  52869. this.setFloat("time", this._time);
  52870. };
  52871. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  52872. get: function () {
  52873. return this._animate;
  52874. },
  52875. set: function (value) {
  52876. this._animate = value;
  52877. },
  52878. enumerable: true,
  52879. configurable: true
  52880. });
  52881. return CustomProceduralTexture;
  52882. }(BABYLON.ProceduralTexture));
  52883. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  52884. })(BABYLON || (BABYLON = {}));
  52885. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  52886. var BABYLON;
  52887. (function (BABYLON) {
  52888. var FreeCameraGamepadInput = (function () {
  52889. function FreeCameraGamepadInput() {
  52890. this.gamepadAngularSensibility = 200;
  52891. this.gamepadMoveSensibility = 40;
  52892. // private members
  52893. this._cameraTransform = BABYLON.Matrix.Identity();
  52894. this._deltaTransform = BABYLON.Vector3.Zero();
  52895. this._vector3 = BABYLON.Vector3.Zero();
  52896. this._vector2 = BABYLON.Vector2.Zero();
  52897. }
  52898. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  52899. var _this = this;
  52900. var manager = this.camera.getScene().gamepadManager;
  52901. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  52902. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  52903. // prioritize XBOX gamepads.
  52904. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  52905. _this.gamepad = gamepad;
  52906. }
  52907. }
  52908. });
  52909. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  52910. if (_this.gamepad === gamepad) {
  52911. _this.gamepad = null;
  52912. }
  52913. });
  52914. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  52915. };
  52916. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  52917. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  52918. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  52919. this.gamepad = null;
  52920. };
  52921. FreeCameraGamepadInput.prototype.checkInputs = function () {
  52922. if (this.gamepad && this.gamepad.leftStick) {
  52923. var camera = this.camera;
  52924. var LSValues = this.gamepad.leftStick;
  52925. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  52926. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  52927. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  52928. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  52929. var RSValues = this.gamepad.rightStick;
  52930. if (RSValues) {
  52931. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  52932. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  52933. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  52934. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  52935. }
  52936. else {
  52937. RSValues = { x: 0, y: 0 };
  52938. }
  52939. if (!camera.rotationQuaternion) {
  52940. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  52941. }
  52942. else {
  52943. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  52944. }
  52945. var speed = camera._computeLocalCameraSpeed() * 50.0;
  52946. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  52947. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  52948. camera.cameraDirection.addInPlace(this._deltaTransform);
  52949. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  52950. camera.cameraRotation.addInPlace(this._vector2);
  52951. }
  52952. };
  52953. FreeCameraGamepadInput.prototype.getClassName = function () {
  52954. return "FreeCameraGamepadInput";
  52955. };
  52956. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  52957. return "gamepad";
  52958. };
  52959. __decorate([
  52960. BABYLON.serialize()
  52961. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  52962. __decorate([
  52963. BABYLON.serialize()
  52964. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  52965. return FreeCameraGamepadInput;
  52966. }());
  52967. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  52968. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  52969. })(BABYLON || (BABYLON = {}));
  52970. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  52971. var BABYLON;
  52972. (function (BABYLON) {
  52973. var ArcRotateCameraGamepadInput = (function () {
  52974. function ArcRotateCameraGamepadInput() {
  52975. this.gamepadRotationSensibility = 80;
  52976. this.gamepadMoveSensibility = 40;
  52977. }
  52978. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  52979. var _this = this;
  52980. var manager = this.camera.getScene().gamepadManager;
  52981. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  52982. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  52983. // prioritize XBOX gamepads.
  52984. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  52985. _this.gamepad = gamepad;
  52986. }
  52987. }
  52988. });
  52989. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  52990. if (_this.gamepad === gamepad) {
  52991. _this.gamepad = null;
  52992. }
  52993. });
  52994. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  52995. };
  52996. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  52997. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  52998. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  52999. this.gamepad = null;
  53000. };
  53001. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  53002. if (this.gamepad) {
  53003. var camera = this.camera;
  53004. var RSValues = this.gamepad.rightStick;
  53005. if (RSValues) {
  53006. if (RSValues.x != 0) {
  53007. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  53008. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  53009. camera.inertialAlphaOffset += normalizedRX;
  53010. }
  53011. }
  53012. if (RSValues.y != 0) {
  53013. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  53014. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  53015. camera.inertialBetaOffset += normalizedRY;
  53016. }
  53017. }
  53018. }
  53019. var LSValues = this.gamepad.leftStick;
  53020. if (LSValues && LSValues.y != 0) {
  53021. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  53022. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  53023. this.camera.inertialRadiusOffset -= normalizedLY;
  53024. }
  53025. }
  53026. }
  53027. };
  53028. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  53029. return "ArcRotateCameraGamepadInput";
  53030. };
  53031. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  53032. return "gamepad";
  53033. };
  53034. __decorate([
  53035. BABYLON.serialize()
  53036. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  53037. __decorate([
  53038. BABYLON.serialize()
  53039. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53040. return ArcRotateCameraGamepadInput;
  53041. }());
  53042. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  53043. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  53044. })(BABYLON || (BABYLON = {}));
  53045. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  53046. var BABYLON;
  53047. (function (BABYLON) {
  53048. var GamepadManager = (function () {
  53049. function GamepadManager() {
  53050. var _this = this;
  53051. this._babylonGamepads = [];
  53052. this._oneGamepadConnected = false;
  53053. this._isMonitoring = false;
  53054. this._gamepadEventSupported = 'GamepadEvent' in window;
  53055. this._gamepadSupport = (navigator.getGamepads ||
  53056. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  53057. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  53058. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  53059. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  53060. for (var i in _this._babylonGamepads) {
  53061. var gamepad = _this._babylonGamepads[i];
  53062. if (gamepad && gamepad._isConnected) {
  53063. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  53064. }
  53065. }
  53066. });
  53067. this._onGamepadConnectedEvent = function (evt) {
  53068. var gamepad = evt.gamepad;
  53069. if (gamepad.index in _this._babylonGamepads) {
  53070. if (_this._babylonGamepads[gamepad.index].isConnected) {
  53071. return;
  53072. }
  53073. }
  53074. var newGamepad;
  53075. if (_this._babylonGamepads[gamepad.index]) {
  53076. newGamepad = _this._babylonGamepads[gamepad.index];
  53077. newGamepad.browserGamepad = gamepad;
  53078. newGamepad._isConnected = true;
  53079. }
  53080. else {
  53081. newGamepad = _this._addNewGamepad(gamepad);
  53082. }
  53083. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53084. _this._startMonitoringGamepads();
  53085. };
  53086. this._onGamepadDisconnectedEvent = function (evt) {
  53087. var gamepad = evt.gamepad;
  53088. // Remove the gamepad from the list of gamepads to monitor.
  53089. for (var i in _this._babylonGamepads) {
  53090. if (_this._babylonGamepads[i].index === gamepad.index) {
  53091. var disconnectedGamepad = _this._babylonGamepads[i];
  53092. disconnectedGamepad._isConnected = false;
  53093. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  53094. break;
  53095. }
  53096. }
  53097. };
  53098. if (this._gamepadSupport) {
  53099. //first add already-connected gamepads
  53100. this._updateGamepadObjects();
  53101. if (this._babylonGamepads.length) {
  53102. this._startMonitoringGamepads();
  53103. }
  53104. // Checking if the gamepad connected event is supported (like in Firefox)
  53105. if (this._gamepadEventSupported) {
  53106. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53107. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  53108. }
  53109. else {
  53110. this._startMonitoringGamepads();
  53111. }
  53112. }
  53113. }
  53114. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  53115. get: function () {
  53116. return this._babylonGamepads;
  53117. },
  53118. enumerable: true,
  53119. configurable: true
  53120. });
  53121. GamepadManager.prototype.getGamepadByType = function (type) {
  53122. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  53123. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  53124. var gamepad = _a[_i];
  53125. if (gamepad && gamepad.type === type) {
  53126. return gamepad;
  53127. }
  53128. }
  53129. return null;
  53130. };
  53131. GamepadManager.prototype.dispose = function () {
  53132. if (this._gamepadEventSupported) {
  53133. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  53134. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  53135. this._onGamepadConnectedEvent = null;
  53136. this._onGamepadDisconnectedEvent = null;
  53137. }
  53138. this._babylonGamepads.forEach(function (gamepad) {
  53139. gamepad.dispose();
  53140. });
  53141. this.onGamepadConnectedObservable.clear();
  53142. this.onGamepadDisconnectedObservable.clear();
  53143. this._oneGamepadConnected = false;
  53144. this._stopMonitoringGamepads();
  53145. this._babylonGamepads = [];
  53146. };
  53147. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  53148. if (!this._oneGamepadConnected) {
  53149. this._oneGamepadConnected = true;
  53150. }
  53151. var newGamepad;
  53152. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  53153. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  53154. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  53155. }
  53156. else if (gamepad.pose) {
  53157. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  53158. }
  53159. else {
  53160. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  53161. }
  53162. this._babylonGamepads[newGamepad.index] = newGamepad;
  53163. return newGamepad;
  53164. };
  53165. GamepadManager.prototype._startMonitoringGamepads = function () {
  53166. if (!this._isMonitoring) {
  53167. this._isMonitoring = true;
  53168. this._checkGamepadsStatus();
  53169. }
  53170. };
  53171. GamepadManager.prototype._stopMonitoringGamepads = function () {
  53172. this._isMonitoring = false;
  53173. };
  53174. GamepadManager.prototype._checkGamepadsStatus = function () {
  53175. var _this = this;
  53176. // Hack to be compatible Chrome
  53177. this._updateGamepadObjects();
  53178. for (var i in this._babylonGamepads) {
  53179. var gamepad = this._babylonGamepads[i];
  53180. if (!gamepad || !gamepad.isConnected) {
  53181. continue;
  53182. }
  53183. gamepad.update();
  53184. }
  53185. if (this._isMonitoring) {
  53186. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  53187. }
  53188. };
  53189. // This function is called only on Chrome, which does not properly support
  53190. // connection/disconnection events and forces you to recopy again the gamepad object
  53191. GamepadManager.prototype._updateGamepadObjects = function () {
  53192. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  53193. for (var i = 0; i < gamepads.length; i++) {
  53194. if (gamepads[i]) {
  53195. if (!this._babylonGamepads[gamepads[i].index]) {
  53196. var newGamepad = this._addNewGamepad(gamepads[i]);
  53197. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53198. }
  53199. else {
  53200. // Forced to copy again this object for Chrome for unknown reason
  53201. this._babylonGamepads[i].browserGamepad = gamepads[i];
  53202. if (!this._babylonGamepads[i].isConnected) {
  53203. this._babylonGamepads[i]._isConnected = true;
  53204. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  53205. }
  53206. }
  53207. }
  53208. }
  53209. };
  53210. return GamepadManager;
  53211. }());
  53212. BABYLON.GamepadManager = GamepadManager;
  53213. })(BABYLON || (BABYLON = {}));
  53214. //# sourceMappingURL=babylon.gamepadManager.js.map
  53215. var BABYLON;
  53216. (function (BABYLON) {
  53217. var StickValues = (function () {
  53218. function StickValues(x, y) {
  53219. this.x = x;
  53220. this.y = y;
  53221. }
  53222. return StickValues;
  53223. }());
  53224. BABYLON.StickValues = StickValues;
  53225. var Gamepad = (function () {
  53226. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  53227. if (leftStickX === void 0) { leftStickX = 0; }
  53228. if (leftStickY === void 0) { leftStickY = 1; }
  53229. if (rightStickX === void 0) { rightStickX = 2; }
  53230. if (rightStickY === void 0) { rightStickY = 3; }
  53231. this.id = id;
  53232. this.index = index;
  53233. this.browserGamepad = browserGamepad;
  53234. this._isConnected = true;
  53235. this.type = Gamepad.GAMEPAD;
  53236. this._leftStickAxisX = leftStickX;
  53237. this._leftStickAxisY = leftStickY;
  53238. this._rightStickAxisX = rightStickX;
  53239. this._rightStickAxisY = rightStickY;
  53240. if (this.browserGamepad.axes.length >= 2) {
  53241. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53242. }
  53243. if (this.browserGamepad.axes.length >= 4) {
  53244. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53245. }
  53246. }
  53247. Object.defineProperty(Gamepad.prototype, "isConnected", {
  53248. get: function () {
  53249. return this._isConnected;
  53250. },
  53251. enumerable: true,
  53252. configurable: true
  53253. });
  53254. Gamepad.prototype.onleftstickchanged = function (callback) {
  53255. this._onleftstickchanged = callback;
  53256. };
  53257. Gamepad.prototype.onrightstickchanged = function (callback) {
  53258. this._onrightstickchanged = callback;
  53259. };
  53260. Object.defineProperty(Gamepad.prototype, "leftStick", {
  53261. get: function () {
  53262. return this._leftStick;
  53263. },
  53264. set: function (newValues) {
  53265. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  53266. this._onleftstickchanged(newValues);
  53267. }
  53268. this._leftStick = newValues;
  53269. },
  53270. enumerable: true,
  53271. configurable: true
  53272. });
  53273. Object.defineProperty(Gamepad.prototype, "rightStick", {
  53274. get: function () {
  53275. return this._rightStick;
  53276. },
  53277. set: function (newValues) {
  53278. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  53279. this._onrightstickchanged(newValues);
  53280. }
  53281. this._rightStick = newValues;
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. Gamepad.prototype.update = function () {
  53287. if (this._leftStick) {
  53288. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53289. }
  53290. if (this._rightStick) {
  53291. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53292. }
  53293. };
  53294. Gamepad.prototype.dispose = function () {
  53295. };
  53296. Gamepad.GAMEPAD = 0;
  53297. Gamepad.GENERIC = 1;
  53298. Gamepad.XBOX = 2;
  53299. Gamepad.POSE_ENABLED = 3;
  53300. return Gamepad;
  53301. }());
  53302. BABYLON.Gamepad = Gamepad;
  53303. var GenericPad = (function (_super) {
  53304. __extends(GenericPad, _super);
  53305. function GenericPad(id, index, browserGamepad) {
  53306. var _this = _super.call(this, id, index, browserGamepad) || this;
  53307. _this.onButtonDownObservable = new BABYLON.Observable();
  53308. _this.onButtonUpObservable = new BABYLON.Observable();
  53309. _this.type = Gamepad.GENERIC;
  53310. _this._buttons = new Array(browserGamepad.buttons.length);
  53311. return _this;
  53312. }
  53313. GenericPad.prototype.onbuttondown = function (callback) {
  53314. this._onbuttondown = callback;
  53315. };
  53316. GenericPad.prototype.onbuttonup = function (callback) {
  53317. this._onbuttonup = callback;
  53318. };
  53319. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  53320. if (newValue !== currentValue) {
  53321. if (newValue === 1) {
  53322. if (this._onbuttondown) {
  53323. this._onbuttondown(buttonIndex);
  53324. }
  53325. this.onButtonDownObservable.notifyObservers(buttonIndex);
  53326. }
  53327. if (newValue === 0) {
  53328. if (this._onbuttonup) {
  53329. this._onbuttonup(buttonIndex);
  53330. }
  53331. this.onButtonUpObservable.notifyObservers(buttonIndex);
  53332. }
  53333. }
  53334. return newValue;
  53335. };
  53336. GenericPad.prototype.update = function () {
  53337. _super.prototype.update.call(this);
  53338. for (var index = 0; index < this._buttons.length; index++) {
  53339. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  53340. }
  53341. };
  53342. return GenericPad;
  53343. }(Gamepad));
  53344. BABYLON.GenericPad = GenericPad;
  53345. })(BABYLON || (BABYLON = {}));
  53346. //# sourceMappingURL=babylon.gamepad.js.map
  53347. var BABYLON;
  53348. (function (BABYLON) {
  53349. var Xbox360Button;
  53350. (function (Xbox360Button) {
  53351. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  53352. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  53353. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  53354. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  53355. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  53356. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  53357. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  53358. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  53359. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  53360. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  53361. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  53362. var Xbox360Dpad;
  53363. (function (Xbox360Dpad) {
  53364. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  53365. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  53366. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  53367. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  53368. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  53369. var Xbox360Pad = (function (_super) {
  53370. __extends(Xbox360Pad, _super);
  53371. function Xbox360Pad(id, index, gamepad, xboxOne) {
  53372. if (xboxOne === void 0) { xboxOne = false; }
  53373. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  53374. _this._leftTrigger = 0;
  53375. _this._rightTrigger = 0;
  53376. _this.onButtonDownObservable = new BABYLON.Observable();
  53377. _this.onButtonUpObservable = new BABYLON.Observable();
  53378. _this.onPadDownObservable = new BABYLON.Observable();
  53379. _this.onPadUpObservable = new BABYLON.Observable();
  53380. _this._buttonA = 0;
  53381. _this._buttonB = 0;
  53382. _this._buttonX = 0;
  53383. _this._buttonY = 0;
  53384. _this._buttonBack = 0;
  53385. _this._buttonStart = 0;
  53386. _this._buttonLB = 0;
  53387. _this._buttonRB = 0;
  53388. _this._buttonLeftStick = 0;
  53389. _this._buttonRightStick = 0;
  53390. _this._dPadUp = 0;
  53391. _this._dPadDown = 0;
  53392. _this._dPadLeft = 0;
  53393. _this._dPadRight = 0;
  53394. _this._isXboxOnePad = false;
  53395. _this.type = BABYLON.Gamepad.XBOX;
  53396. _this._isXboxOnePad = xboxOne;
  53397. return _this;
  53398. }
  53399. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  53400. this._onlefttriggerchanged = callback;
  53401. };
  53402. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  53403. this._onrighttriggerchanged = callback;
  53404. };
  53405. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  53406. get: function () {
  53407. return this._leftTrigger;
  53408. },
  53409. set: function (newValue) {
  53410. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  53411. this._onlefttriggerchanged(newValue);
  53412. }
  53413. this._leftTrigger = newValue;
  53414. },
  53415. enumerable: true,
  53416. configurable: true
  53417. });
  53418. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  53419. get: function () {
  53420. return this._rightTrigger;
  53421. },
  53422. set: function (newValue) {
  53423. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  53424. this._onrighttriggerchanged(newValue);
  53425. }
  53426. this._rightTrigger = newValue;
  53427. },
  53428. enumerable: true,
  53429. configurable: true
  53430. });
  53431. Xbox360Pad.prototype.onbuttondown = function (callback) {
  53432. this._onbuttondown = callback;
  53433. };
  53434. Xbox360Pad.prototype.onbuttonup = function (callback) {
  53435. this._onbuttonup = callback;
  53436. };
  53437. Xbox360Pad.prototype.ondpaddown = function (callback) {
  53438. this._ondpaddown = callback;
  53439. };
  53440. Xbox360Pad.prototype.ondpadup = function (callback) {
  53441. this._ondpadup = callback;
  53442. };
  53443. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  53444. if (newValue !== currentValue) {
  53445. if (newValue === 1) {
  53446. if (this._onbuttondown) {
  53447. this._onbuttondown(buttonType);
  53448. }
  53449. this.onButtonDownObservable.notifyObservers(buttonType);
  53450. }
  53451. if (newValue === 0) {
  53452. if (this._onbuttonup) {
  53453. this._onbuttonup(buttonType);
  53454. }
  53455. this.onButtonUpObservable.notifyObservers(buttonType);
  53456. }
  53457. }
  53458. return newValue;
  53459. };
  53460. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  53461. if (newValue !== currentValue) {
  53462. if (newValue === 1) {
  53463. if (this._ondpaddown) {
  53464. this._ondpaddown(buttonType);
  53465. }
  53466. this.onPadDownObservable.notifyObservers(buttonType);
  53467. }
  53468. if (newValue === 0) {
  53469. if (this._ondpadup) {
  53470. this._ondpadup(buttonType);
  53471. }
  53472. this.onPadUpObservable.notifyObservers(buttonType);
  53473. }
  53474. }
  53475. return newValue;
  53476. };
  53477. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  53478. get: function () {
  53479. return this._buttonA;
  53480. },
  53481. set: function (value) {
  53482. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  53483. },
  53484. enumerable: true,
  53485. configurable: true
  53486. });
  53487. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  53488. get: function () {
  53489. return this._buttonB;
  53490. },
  53491. set: function (value) {
  53492. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  53493. },
  53494. enumerable: true,
  53495. configurable: true
  53496. });
  53497. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  53498. get: function () {
  53499. return this._buttonX;
  53500. },
  53501. set: function (value) {
  53502. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  53503. },
  53504. enumerable: true,
  53505. configurable: true
  53506. });
  53507. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  53508. get: function () {
  53509. return this._buttonY;
  53510. },
  53511. set: function (value) {
  53512. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  53513. },
  53514. enumerable: true,
  53515. configurable: true
  53516. });
  53517. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  53518. get: function () {
  53519. return this._buttonStart;
  53520. },
  53521. set: function (value) {
  53522. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  53523. },
  53524. enumerable: true,
  53525. configurable: true
  53526. });
  53527. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  53528. get: function () {
  53529. return this._buttonBack;
  53530. },
  53531. set: function (value) {
  53532. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  53533. },
  53534. enumerable: true,
  53535. configurable: true
  53536. });
  53537. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  53538. get: function () {
  53539. return this._buttonLB;
  53540. },
  53541. set: function (value) {
  53542. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  53543. },
  53544. enumerable: true,
  53545. configurable: true
  53546. });
  53547. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  53548. get: function () {
  53549. return this._buttonRB;
  53550. },
  53551. set: function (value) {
  53552. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  53553. },
  53554. enumerable: true,
  53555. configurable: true
  53556. });
  53557. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  53558. get: function () {
  53559. return this._buttonLeftStick;
  53560. },
  53561. set: function (value) {
  53562. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  53563. },
  53564. enumerable: true,
  53565. configurable: true
  53566. });
  53567. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  53568. get: function () {
  53569. return this._buttonRightStick;
  53570. },
  53571. set: function (value) {
  53572. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  53573. },
  53574. enumerable: true,
  53575. configurable: true
  53576. });
  53577. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53578. get: function () {
  53579. return this._dPadUp;
  53580. },
  53581. set: function (value) {
  53582. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53583. },
  53584. enumerable: true,
  53585. configurable: true
  53586. });
  53587. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53588. get: function () {
  53589. return this._dPadDown;
  53590. },
  53591. set: function (value) {
  53592. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53598. get: function () {
  53599. return this._dPadLeft;
  53600. },
  53601. set: function (value) {
  53602. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53603. },
  53604. enumerable: true,
  53605. configurable: true
  53606. });
  53607. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53608. get: function () {
  53609. return this._dPadRight;
  53610. },
  53611. set: function (value) {
  53612. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53613. },
  53614. enumerable: true,
  53615. configurable: true
  53616. });
  53617. Xbox360Pad.prototype.update = function () {
  53618. _super.prototype.update.call(this);
  53619. if (this._isXboxOnePad) {
  53620. this.buttonA = this.browserGamepad.buttons[0].value;
  53621. this.buttonB = this.browserGamepad.buttons[1].value;
  53622. this.buttonX = this.browserGamepad.buttons[2].value;
  53623. this.buttonY = this.browserGamepad.buttons[3].value;
  53624. this.buttonLB = this.browserGamepad.buttons[4].value;
  53625. this.buttonRB = this.browserGamepad.buttons[5].value;
  53626. this.leftTrigger = this.browserGamepad.axes[2];
  53627. this.rightTrigger = this.browserGamepad.axes[5];
  53628. this.buttonBack = this.browserGamepad.buttons[9].value;
  53629. this.buttonStart = this.browserGamepad.buttons[8].value;
  53630. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  53631. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  53632. this.dPadUp = this.browserGamepad.buttons[11].value;
  53633. this.dPadDown = this.browserGamepad.buttons[12].value;
  53634. this.dPadLeft = this.browserGamepad.buttons[13].value;
  53635. this.dPadRight = this.browserGamepad.buttons[14].value;
  53636. }
  53637. else {
  53638. this.buttonA = this.browserGamepad.buttons[0].value;
  53639. this.buttonB = this.browserGamepad.buttons[1].value;
  53640. this.buttonX = this.browserGamepad.buttons[2].value;
  53641. this.buttonY = this.browserGamepad.buttons[3].value;
  53642. this.buttonLB = this.browserGamepad.buttons[4].value;
  53643. this.buttonRB = this.browserGamepad.buttons[5].value;
  53644. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53645. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53646. this.buttonBack = this.browserGamepad.buttons[8].value;
  53647. this.buttonStart = this.browserGamepad.buttons[9].value;
  53648. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53649. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53650. this.dPadUp = this.browserGamepad.buttons[12].value;
  53651. this.dPadDown = this.browserGamepad.buttons[13].value;
  53652. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53653. this.dPadRight = this.browserGamepad.buttons[15].value;
  53654. }
  53655. };
  53656. return Xbox360Pad;
  53657. }(BABYLON.Gamepad));
  53658. BABYLON.Xbox360Pad = Xbox360Pad;
  53659. })(BABYLON || (BABYLON = {}));
  53660. //# sourceMappingURL=babylon.xboxGamepad.js.map
  53661. var BABYLON;
  53662. (function (BABYLON) {
  53663. var PoseEnabledControllerType;
  53664. (function (PoseEnabledControllerType) {
  53665. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  53666. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  53667. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  53668. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  53669. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  53670. var PoseEnabledControllerHelper = (function () {
  53671. function PoseEnabledControllerHelper() {
  53672. }
  53673. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  53674. // Oculus Touch
  53675. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  53676. return new BABYLON.OculusTouchController(vrGamepad);
  53677. }
  53678. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  53679. return new BABYLON.WindowsMotionController(vrGamepad);
  53680. }
  53681. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  53682. return new BABYLON.ViveController(vrGamepad);
  53683. }
  53684. else {
  53685. return new BABYLON.GenericController(vrGamepad);
  53686. }
  53687. };
  53688. return PoseEnabledControllerHelper;
  53689. }());
  53690. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  53691. var PoseEnabledController = (function (_super) {
  53692. __extends(PoseEnabledController, _super);
  53693. function PoseEnabledController(browserGamepad) {
  53694. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  53695. _this.deviceScaleFactor = 1;
  53696. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  53697. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  53698. _this.controllerType = PoseEnabledControllerType.GENERIC;
  53699. _this.position = BABYLON.Vector3.Zero();
  53700. _this.rotationQuaternion = new BABYLON.Quaternion();
  53701. _this.devicePosition = BABYLON.Vector3.Zero();
  53702. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  53703. _this._calculatedPosition = BABYLON.Vector3.Zero();
  53704. _this._calculatedRotation = new BABYLON.Quaternion();
  53705. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  53706. return _this;
  53707. }
  53708. PoseEnabledController.prototype.update = function () {
  53709. _super.prototype.update.call(this);
  53710. var pose = this.browserGamepad.pose;
  53711. this.updateFromDevice(pose);
  53712. if (this._mesh) {
  53713. this._mesh.position.copyFrom(this._calculatedPosition);
  53714. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  53715. }
  53716. };
  53717. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  53718. if (poseData) {
  53719. this.rawPose = poseData;
  53720. if (poseData.position) {
  53721. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  53722. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  53723. this.devicePosition.z *= -1;
  53724. }
  53725. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  53726. this._calculatedPosition.addInPlace(this.position);
  53727. }
  53728. if (poseData.orientation) {
  53729. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  53730. if (this._mesh) {
  53731. if (this._mesh.getScene().useRightHandedSystem) {
  53732. this.deviceRotationQuaternion.z *= -1;
  53733. this.deviceRotationQuaternion.w *= -1;
  53734. }
  53735. else {
  53736. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  53737. }
  53738. }
  53739. // if the camera is set, rotate to the camera's rotation
  53740. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  53741. }
  53742. }
  53743. };
  53744. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  53745. if (this._mesh) {
  53746. this._mesh.parent = undefined;
  53747. }
  53748. this._mesh = mesh;
  53749. if (this._poseControlledCamera) {
  53750. this._mesh.parent = this._poseControlledCamera;
  53751. }
  53752. if (!this._mesh.rotationQuaternion) {
  53753. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  53754. }
  53755. };
  53756. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  53757. this._poseControlledCamera = camera;
  53758. if (this._mesh) {
  53759. this._mesh.parent = this._poseControlledCamera;
  53760. }
  53761. };
  53762. PoseEnabledController.prototype.dispose = function () {
  53763. if (this._mesh) {
  53764. this._mesh.dispose();
  53765. }
  53766. this._mesh = undefined;
  53767. _super.prototype.dispose.call(this);
  53768. };
  53769. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  53770. get: function () {
  53771. return this._mesh;
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. PoseEnabledController.prototype.getForwardRay = function (length) {
  53777. if (length === void 0) { length = 100; }
  53778. if (!this.mesh) {
  53779. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  53780. }
  53781. var m = this.mesh.getWorldMatrix();
  53782. var origin = m.getTranslation();
  53783. var forward = new BABYLON.Vector3(0, 0, -1);
  53784. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  53785. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  53786. return new BABYLON.Ray(origin, direction, length);
  53787. };
  53788. return PoseEnabledController;
  53789. }(BABYLON.Gamepad));
  53790. BABYLON.PoseEnabledController = PoseEnabledController;
  53791. })(BABYLON || (BABYLON = {}));
  53792. //# sourceMappingURL=babylon.poseEnabledController.js.map
  53793. var BABYLON;
  53794. (function (BABYLON) {
  53795. var WebVRController = (function (_super) {
  53796. __extends(WebVRController, _super);
  53797. function WebVRController(vrGamepad) {
  53798. var _this = _super.call(this, vrGamepad) || this;
  53799. // Observables
  53800. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  53801. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  53802. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  53803. _this.onPadStateChangedObservable = new BABYLON.Observable();
  53804. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  53805. _this.pad = { x: 0, y: 0 };
  53806. // avoid GC, store state in a tmp object
  53807. _this._changes = {
  53808. pressChanged: false,
  53809. touchChanged: false,
  53810. valueChanged: false,
  53811. changed: false
  53812. };
  53813. _this._buttons = new Array(vrGamepad.buttons.length);
  53814. _this.hand = vrGamepad.hand;
  53815. return _this;
  53816. }
  53817. WebVRController.prototype.onButtonStateChange = function (callback) {
  53818. this._onButtonStateChange = callback;
  53819. };
  53820. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  53821. get: function () {
  53822. return this._defaultModel;
  53823. },
  53824. enumerable: true,
  53825. configurable: true
  53826. });
  53827. WebVRController.prototype.update = function () {
  53828. _super.prototype.update.call(this);
  53829. for (var index = 0; index < this._buttons.length; index++) {
  53830. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  53831. }
  53832. ;
  53833. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  53834. this.pad.x = this.leftStick.x;
  53835. this.pad.y = this.leftStick.y;
  53836. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  53837. }
  53838. };
  53839. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  53840. if (!newState) {
  53841. newState = {
  53842. pressed: false,
  53843. touched: false,
  53844. value: 0
  53845. };
  53846. }
  53847. if (!currentState) {
  53848. this._buttons[buttonIndex] = {
  53849. pressed: newState.pressed,
  53850. touched: newState.touched,
  53851. value: newState.value
  53852. };
  53853. return;
  53854. }
  53855. this._checkChanges(newState, currentState);
  53856. if (this._changes.changed) {
  53857. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  53858. this.handleButtonChange(buttonIndex, newState, this._changes);
  53859. }
  53860. this._buttons[buttonIndex].pressed = newState.pressed;
  53861. this._buttons[buttonIndex].touched = newState.touched;
  53862. // oculus triggers are never 0, thou not touched.
  53863. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  53864. };
  53865. WebVRController.prototype._checkChanges = function (newState, currentState) {
  53866. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  53867. this._changes.touchChanged = newState.touched !== currentState.touched;
  53868. this._changes.valueChanged = newState.value !== currentState.value;
  53869. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  53870. return this._changes;
  53871. };
  53872. WebVRController.prototype.dispose = function () {
  53873. _super.prototype.dispose.call(this);
  53874. this.onTriggerStateChangedObservable.clear();
  53875. this.onMainButtonStateChangedObservable.clear();
  53876. this.onSecondaryButtonStateChangedObservable.clear();
  53877. this.onPadStateChangedObservable.clear();
  53878. this.onPadValuesChangedObservable.clear();
  53879. };
  53880. return WebVRController;
  53881. }(BABYLON.PoseEnabledController));
  53882. BABYLON.WebVRController = WebVRController;
  53883. })(BABYLON || (BABYLON = {}));
  53884. //# sourceMappingURL=babylon.webVRController.js.map
  53885. var BABYLON;
  53886. (function (BABYLON) {
  53887. var OculusTouchController = (function (_super) {
  53888. __extends(OculusTouchController, _super);
  53889. function OculusTouchController(vrGamepad) {
  53890. var _this = _super.call(this, vrGamepad) || this;
  53891. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  53892. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  53893. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  53894. return _this;
  53895. }
  53896. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  53897. var _this = this;
  53898. var meshName;
  53899. // Hand
  53900. if (this.hand === 'left') {
  53901. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  53902. }
  53903. else {
  53904. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  53905. }
  53906. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  53907. /*
  53908. Parent Mesh name: oculus_touch_left
  53909. - body
  53910. - trigger
  53911. - thumbstick
  53912. - grip
  53913. - button_y
  53914. - button_x
  53915. - button_enter
  53916. */
  53917. _this._defaultModel = newMeshes[1];
  53918. if (meshLoaded) {
  53919. meshLoaded(_this._defaultModel);
  53920. }
  53921. _this.attachToMesh(_this._defaultModel);
  53922. });
  53923. };
  53924. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  53925. // helper getters for left and right hand.
  53926. get: function () {
  53927. if (this.hand === 'right') {
  53928. return this.onMainButtonStateChangedObservable;
  53929. }
  53930. else {
  53931. throw new Error('No A button on left hand');
  53932. }
  53933. },
  53934. enumerable: true,
  53935. configurable: true
  53936. });
  53937. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  53938. get: function () {
  53939. if (this.hand === 'right') {
  53940. return this.onSecondaryButtonStateChangedObservable;
  53941. }
  53942. else {
  53943. throw new Error('No B button on left hand');
  53944. }
  53945. },
  53946. enumerable: true,
  53947. configurable: true
  53948. });
  53949. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  53950. get: function () {
  53951. if (this.hand === 'left') {
  53952. return this.onMainButtonStateChangedObservable;
  53953. }
  53954. else {
  53955. throw new Error('No X button on right hand');
  53956. }
  53957. },
  53958. enumerable: true,
  53959. configurable: true
  53960. });
  53961. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  53962. get: function () {
  53963. if (this.hand === 'left') {
  53964. return this.onSecondaryButtonStateChangedObservable;
  53965. }
  53966. else {
  53967. throw new Error('No Y button on right hand');
  53968. }
  53969. },
  53970. enumerable: true,
  53971. configurable: true
  53972. });
  53973. /*
  53974. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  53975. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  53976. 2) secondary trigger (same)
  53977. 3) A (right) X (left), touch, pressed = value
  53978. 4) B / Y
  53979. 5) thumb rest
  53980. */
  53981. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53982. var notifyObject = state; //{ state: state, changes: changes };
  53983. var triggerDirection = this.hand === 'right' ? -1 : 1;
  53984. switch (buttonIdx) {
  53985. case 0:
  53986. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53987. return;
  53988. case 1:// index trigger
  53989. if (this._defaultModel) {
  53990. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  53991. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  53992. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  53993. }
  53994. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53995. return;
  53996. case 2:// secondary trigger
  53997. if (this._defaultModel) {
  53998. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  53999. }
  54000. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  54001. return;
  54002. case 3:
  54003. if (this._defaultModel) {
  54004. if (notifyObject.pressed) {
  54005. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  54006. }
  54007. else {
  54008. (this._defaultModel.getChildren()[1]).position.y = 0;
  54009. }
  54010. }
  54011. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54012. return;
  54013. case 4:
  54014. if (this._defaultModel) {
  54015. if (notifyObject.pressed) {
  54016. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54017. }
  54018. else {
  54019. (this._defaultModel.getChildren()[2]).position.y = 0;
  54020. }
  54021. }
  54022. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54023. return;
  54024. case 5:
  54025. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  54026. return;
  54027. }
  54028. };
  54029. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  54030. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  54031. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  54032. return OculusTouchController;
  54033. }(BABYLON.WebVRController));
  54034. BABYLON.OculusTouchController = OculusTouchController;
  54035. })(BABYLON || (BABYLON = {}));
  54036. //# sourceMappingURL=babylon.oculusTouchController.js.map
  54037. var BABYLON;
  54038. (function (BABYLON) {
  54039. var ViveController = (function (_super) {
  54040. __extends(ViveController, _super);
  54041. function ViveController(vrGamepad) {
  54042. var _this = _super.call(this, vrGamepad) || this;
  54043. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  54044. return _this;
  54045. }
  54046. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54047. var _this = this;
  54048. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  54049. /*
  54050. Parent Mesh name: ViveWand
  54051. - body
  54052. - r_gripper
  54053. - l_gripper
  54054. - menu_button
  54055. - system_button
  54056. - trackpad
  54057. - trigger
  54058. - LED
  54059. */
  54060. _this._defaultModel = newMeshes[1];
  54061. if (meshLoaded) {
  54062. meshLoaded(_this._defaultModel);
  54063. }
  54064. _this.attachToMesh(_this._defaultModel);
  54065. });
  54066. };
  54067. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  54068. get: function () {
  54069. return this.onMainButtonStateChangedObservable;
  54070. },
  54071. enumerable: true,
  54072. configurable: true
  54073. });
  54074. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  54075. get: function () {
  54076. return this.onMainButtonStateChangedObservable;
  54077. },
  54078. enumerable: true,
  54079. configurable: true
  54080. });
  54081. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  54082. get: function () {
  54083. return this.onSecondaryButtonStateChangedObservable;
  54084. },
  54085. enumerable: true,
  54086. configurable: true
  54087. });
  54088. /**
  54089. * Vive mapping:
  54090. * 0: touchpad
  54091. * 1: trigger
  54092. * 2: left AND right buttons
  54093. * 3: menu button
  54094. */
  54095. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54096. var notifyObject = state; //{ state: state, changes: changes };
  54097. switch (buttonIdx) {
  54098. case 0:
  54099. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  54100. return;
  54101. case 1:// index trigger
  54102. if (this._defaultModel) {
  54103. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  54104. }
  54105. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  54106. return;
  54107. case 2:// left AND right button
  54108. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54109. return;
  54110. case 3:
  54111. if (this._defaultModel) {
  54112. if (notifyObject.pressed) {
  54113. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54114. }
  54115. else {
  54116. (this._defaultModel.getChildren()[2]).position.y = 0;
  54117. }
  54118. }
  54119. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54120. return;
  54121. }
  54122. };
  54123. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  54124. ViveController.MODEL_FILENAME = 'wand.babylon';
  54125. return ViveController;
  54126. }(BABYLON.WebVRController));
  54127. BABYLON.ViveController = ViveController;
  54128. })(BABYLON || (BABYLON = {}));
  54129. //# sourceMappingURL=babylon.viveController.js.map
  54130. var BABYLON;
  54131. (function (BABYLON) {
  54132. var GenericController = (function (_super) {
  54133. __extends(GenericController, _super);
  54134. function GenericController(vrGamepad) {
  54135. return _super.call(this, vrGamepad) || this;
  54136. }
  54137. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54138. var _this = this;
  54139. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  54140. _this._defaultModel = newMeshes[1];
  54141. if (meshLoaded) {
  54142. meshLoaded(_this._defaultModel);
  54143. }
  54144. _this.attachToMesh(_this._defaultModel);
  54145. });
  54146. };
  54147. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54148. console.log("Button id: " + buttonIdx + "state: ");
  54149. console.dir(state);
  54150. };
  54151. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  54152. GenericController.MODEL_FILENAME = 'generic.babylon';
  54153. return GenericController;
  54154. }(BABYLON.WebVRController));
  54155. BABYLON.GenericController = GenericController;
  54156. })(BABYLON || (BABYLON = {}));
  54157. //# sourceMappingURL=babylon.genericController.js.map
  54158. var BABYLON;
  54159. (function (BABYLON) {
  54160. var LoadedMeshInfo = (function () {
  54161. function LoadedMeshInfo() {
  54162. this.buttonMeshes = {};
  54163. this.axisMeshes = {};
  54164. }
  54165. return LoadedMeshInfo;
  54166. }());
  54167. var WindowsMotionController = (function (_super) {
  54168. __extends(WindowsMotionController, _super);
  54169. function WindowsMotionController(vrGamepad) {
  54170. var _this = _super.call(this, vrGamepad) || this;
  54171. _this._mapping = {
  54172. // Semantic button names
  54173. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  54174. // A mapping of the button name to glTF model node name
  54175. // that should be transformed by button value.
  54176. buttonMeshNames: {
  54177. 'trigger': 'SELECT',
  54178. 'menu': 'MENU',
  54179. 'grip': 'GRASP',
  54180. 'thumbstick': 'THUMBSTICK_PRESS',
  54181. 'trackpad': 'TOUCHPAD_PRESS'
  54182. },
  54183. // This mapping is used to translate from the Motion Controller to Babylon semantics
  54184. buttonObservableNames: {
  54185. 'trigger': 'onTriggerStateChangedObservable',
  54186. 'menu': 'onSecondaryButtonStateChangedObservable',
  54187. 'grip': 'onMainButtonStateChangedObservable',
  54188. 'thumbstick': 'onPadStateChangedObservable',
  54189. 'trackpad': 'onTrackpadChangedObservable'
  54190. },
  54191. // A mapping of the axis name to glTF model node name
  54192. // that should be transformed by axis value.
  54193. // This array mirrors the browserGamepad.axes array, such that
  54194. // the mesh corresponding to axis 0 is in this array index 0.
  54195. axisMeshNames: [
  54196. 'THUMBSTICK_X',
  54197. 'THUMBSTICK_Y',
  54198. 'TOUCHPAD_TOUCH_X',
  54199. 'TOUCHPAD_TOUCH_Y'
  54200. ],
  54201. pointingPoseMeshName: 'POINTING_POSE'
  54202. };
  54203. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  54204. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  54205. _this._loadedMeshInfo = null;
  54206. return _this;
  54207. }
  54208. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  54209. get: function () {
  54210. return this.onTriggerStateChangedObservable;
  54211. },
  54212. enumerable: true,
  54213. configurable: true
  54214. });
  54215. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  54216. get: function () {
  54217. return this.onSecondaryButtonStateChangedObservable;
  54218. },
  54219. enumerable: true,
  54220. configurable: true
  54221. });
  54222. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  54223. get: function () {
  54224. return this.onMainButtonStateChangedObservable;
  54225. },
  54226. enumerable: true,
  54227. configurable: true
  54228. });
  54229. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  54230. get: function () {
  54231. return this.onPadStateChangedObservable;
  54232. },
  54233. enumerable: true,
  54234. configurable: true
  54235. });
  54236. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  54237. get: function () {
  54238. return this.onTrackpadChangedObservable;
  54239. },
  54240. enumerable: true,
  54241. configurable: true
  54242. });
  54243. /**
  54244. * Called once per frame by the engine.
  54245. */
  54246. WindowsMotionController.prototype.update = function () {
  54247. _super.prototype.update.call(this);
  54248. // Only need to animate axes if there is a loaded mesh
  54249. if (this._loadedMeshInfo) {
  54250. if (this.browserGamepad.axes) {
  54251. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  54252. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  54253. }
  54254. }
  54255. }
  54256. };
  54257. /**
  54258. * Called once for each button that changed state since the last frame
  54259. * @param buttonIdx Which button index changed
  54260. * @param state New state of the button
  54261. * @param changes Which properties on the state changed since last frame
  54262. */
  54263. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54264. var buttonName = this._mapping.buttons[buttonIdx];
  54265. if (!buttonName) {
  54266. return;
  54267. }
  54268. // Only emit events for buttons that we know how to map from index to name
  54269. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  54270. if (observable) {
  54271. observable.notifyObservers(state);
  54272. }
  54273. this.lerpButtonTransform(buttonName, state.value);
  54274. };
  54275. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  54276. // If there is no loaded mesh, there is nothing to transform.
  54277. if (!this._loadedMeshInfo) {
  54278. return;
  54279. }
  54280. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  54281. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  54282. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  54283. };
  54284. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  54285. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  54286. if (!meshInfo) {
  54287. return;
  54288. }
  54289. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  54290. var lerpValue = axisValue * 0.5 + 0.5;
  54291. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  54292. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  54293. };
  54294. /**
  54295. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  54296. * @param scene scene in which to add meshes
  54297. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  54298. */
  54299. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  54300. var _this = this;
  54301. if (forceDefault === void 0) { forceDefault = false; }
  54302. var path;
  54303. var filename;
  54304. // Checking if GLB loader is present
  54305. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  54306. // Determine the device specific folder based on the ID suffix
  54307. var device = 'default';
  54308. if (this.id && !forceDefault) {
  54309. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  54310. device = ((match && match[0]) || device);
  54311. }
  54312. // Hand
  54313. if (this.hand === 'left') {
  54314. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  54315. }
  54316. else {
  54317. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  54318. }
  54319. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  54320. }
  54321. else {
  54322. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  54323. path = BABYLON.GenericController.MODEL_BASE_URL;
  54324. filename = BABYLON.GenericController.MODEL_FILENAME;
  54325. }
  54326. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  54327. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  54328. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  54329. if (!_this._loadedMeshInfo) {
  54330. return;
  54331. }
  54332. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  54333. _this.attachToMesh(_this._defaultModel);
  54334. if (meshLoaded) {
  54335. meshLoaded(_this._defaultModel);
  54336. }
  54337. }, null, function (scene, message) {
  54338. BABYLON.Tools.Log(message);
  54339. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  54340. if (!forceDefault) {
  54341. _this.initControllerMesh(scene, meshLoaded, true);
  54342. }
  54343. });
  54344. };
  54345. /**
  54346. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  54347. * can be transformed by button presses and axes values, based on this._mapping.
  54348. *
  54349. * @param scene scene in which the meshes exist
  54350. * @param meshes list of meshes that make up the controller model to process
  54351. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  54352. */
  54353. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  54354. var loadedMeshInfo = null;
  54355. // Create a new mesh to contain the glTF hierarchy
  54356. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  54357. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  54358. var childMesh = null;
  54359. for (var i = 0; i < meshes.length; i++) {
  54360. var mesh = meshes[i];
  54361. if (!mesh.parent) {
  54362. // Exclude controller meshes from picking results
  54363. mesh.isPickable = false;
  54364. // Handle root node, attach to the new parentMesh
  54365. childMesh = mesh;
  54366. break;
  54367. }
  54368. }
  54369. if (childMesh) {
  54370. childMesh.setParent(parentMesh);
  54371. // Create our mesh info. Note that this method will always return non-null.
  54372. loadedMeshInfo = this.createMeshInfo(parentMesh);
  54373. }
  54374. else {
  54375. BABYLON.Tools.Warn('Could not find root node in model file.');
  54376. }
  54377. return loadedMeshInfo;
  54378. };
  54379. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  54380. var loadedMeshInfo = new LoadedMeshInfo();
  54381. var i;
  54382. loadedMeshInfo.rootNode = rootNode;
  54383. // Reset the caches
  54384. loadedMeshInfo.buttonMeshes = {};
  54385. loadedMeshInfo.axisMeshes = {};
  54386. // Button Meshes
  54387. for (i = 0; i < this._mapping.buttons.length; i++) {
  54388. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  54389. if (!buttonMeshName) {
  54390. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  54391. continue;
  54392. }
  54393. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  54394. if (!buttonMesh) {
  54395. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  54396. continue;
  54397. }
  54398. var buttonMeshInfo = {
  54399. index: i,
  54400. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  54401. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  54402. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  54403. };
  54404. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  54405. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  54406. }
  54407. else {
  54408. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  54409. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  54410. '(VALUE: ' + !!buttonMeshInfo.value +
  54411. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  54412. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  54413. ')');
  54414. }
  54415. }
  54416. // Axis Meshes
  54417. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  54418. var axisMeshName = this._mapping.axisMeshNames[i];
  54419. if (!axisMeshName) {
  54420. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  54421. continue;
  54422. }
  54423. var axisMesh = getChildByName(rootNode, axisMeshName);
  54424. if (!axisMesh) {
  54425. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  54426. continue;
  54427. }
  54428. var axisMeshInfo = {
  54429. index: i,
  54430. value: getImmediateChildByName(axisMesh, 'VALUE'),
  54431. min: getImmediateChildByName(axisMesh, 'MIN'),
  54432. max: getImmediateChildByName(axisMesh, 'MAX')
  54433. };
  54434. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  54435. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  54436. }
  54437. else {
  54438. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  54439. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  54440. '(VALUE: ' + !!axisMeshInfo.value +
  54441. ', MIN: ' + !!axisMeshInfo.min +
  54442. ', MAX:' + !!axisMeshInfo.max +
  54443. ')');
  54444. }
  54445. }
  54446. // Pointing Ray
  54447. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  54448. if (!loadedMeshInfo.pointingPoseNode) {
  54449. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  54450. }
  54451. return loadedMeshInfo;
  54452. // Look through all children recursively. This will return null if no mesh exists with the given name.
  54453. function getChildByName(node, name) {
  54454. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  54455. }
  54456. // Look through only immediate children. This will return null if no mesh exists with the given name.
  54457. function getImmediateChildByName(node, name) {
  54458. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  54459. }
  54460. };
  54461. WindowsMotionController.prototype.getForwardRay = function (length) {
  54462. if (length === void 0) { length = 100; }
  54463. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  54464. return _super.prototype.getForwardRay.call(this, length);
  54465. }
  54466. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  54467. var origin = m.getTranslation();
  54468. var forward = new BABYLON.Vector3(0, 0, -1);
  54469. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  54470. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  54471. return new BABYLON.Ray(origin, direction, length);
  54472. };
  54473. WindowsMotionController.prototype.dispose = function () {
  54474. _super.prototype.dispose.call(this);
  54475. this.onTrackpadChangedObservable.clear();
  54476. };
  54477. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  54478. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  54479. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  54480. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  54481. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  54482. return WindowsMotionController;
  54483. }(BABYLON.WebVRController));
  54484. BABYLON.WindowsMotionController = WindowsMotionController;
  54485. })(BABYLON || (BABYLON = {}));
  54486. //# sourceMappingURL=babylon.windowsMotionController.js.map
  54487. /// <reference path="babylon.targetCamera.ts" />
  54488. var BABYLON;
  54489. (function (BABYLON) {
  54490. var FollowCamera = (function (_super) {
  54491. __extends(FollowCamera, _super);
  54492. function FollowCamera(name, position, scene, lockedTarget) {
  54493. var _this = _super.call(this, name, position, scene) || this;
  54494. _this.radius = 12;
  54495. _this.rotationOffset = 0;
  54496. _this.heightOffset = 4;
  54497. _this.cameraAcceleration = 0.05;
  54498. _this.maxCameraSpeed = 20;
  54499. _this.lockedTarget = lockedTarget;
  54500. return _this;
  54501. }
  54502. FollowCamera.prototype.getRadians = function (degrees) {
  54503. return degrees * Math.PI / 180;
  54504. };
  54505. FollowCamera.prototype.follow = function (cameraTarget) {
  54506. if (!cameraTarget)
  54507. return;
  54508. var yRotation;
  54509. if (cameraTarget.rotationQuaternion) {
  54510. var rotMatrix = new BABYLON.Matrix();
  54511. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  54512. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  54513. }
  54514. else {
  54515. yRotation = cameraTarget.rotation.y;
  54516. }
  54517. var radians = this.getRadians(this.rotationOffset) + yRotation;
  54518. var targetPosition = cameraTarget.getAbsolutePosition();
  54519. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  54520. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  54521. var dx = targetX - this.position.x;
  54522. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  54523. var dz = (targetZ) - this.position.z;
  54524. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  54525. var vy = dy * this.cameraAcceleration;
  54526. var vz = dz * this.cameraAcceleration * 2;
  54527. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  54528. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54529. }
  54530. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  54531. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54532. }
  54533. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  54534. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54535. }
  54536. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  54537. this.setTarget(targetPosition);
  54538. };
  54539. FollowCamera.prototype._checkInputs = function () {
  54540. _super.prototype._checkInputs.call(this);
  54541. this.follow(this.lockedTarget);
  54542. };
  54543. FollowCamera.prototype.getClassName = function () {
  54544. return "FollowCamera";
  54545. };
  54546. __decorate([
  54547. BABYLON.serialize()
  54548. ], FollowCamera.prototype, "radius", void 0);
  54549. __decorate([
  54550. BABYLON.serialize()
  54551. ], FollowCamera.prototype, "rotationOffset", void 0);
  54552. __decorate([
  54553. BABYLON.serialize()
  54554. ], FollowCamera.prototype, "heightOffset", void 0);
  54555. __decorate([
  54556. BABYLON.serialize()
  54557. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  54558. __decorate([
  54559. BABYLON.serialize()
  54560. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  54561. __decorate([
  54562. BABYLON.serializeAsMeshReference("lockedTargetId")
  54563. ], FollowCamera.prototype, "lockedTarget", void 0);
  54564. return FollowCamera;
  54565. }(BABYLON.TargetCamera));
  54566. BABYLON.FollowCamera = FollowCamera;
  54567. var ArcFollowCamera = (function (_super) {
  54568. __extends(ArcFollowCamera, _super);
  54569. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  54570. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  54571. _this.alpha = alpha;
  54572. _this.beta = beta;
  54573. _this.radius = radius;
  54574. _this.target = target;
  54575. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  54576. _this.follow();
  54577. return _this;
  54578. }
  54579. ArcFollowCamera.prototype.follow = function () {
  54580. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  54581. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  54582. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  54583. var targetPosition = this.target.getAbsolutePosition();
  54584. this.position = targetPosition.add(this._cartesianCoordinates);
  54585. this.setTarget(targetPosition);
  54586. };
  54587. ArcFollowCamera.prototype._checkInputs = function () {
  54588. _super.prototype._checkInputs.call(this);
  54589. this.follow();
  54590. };
  54591. ArcFollowCamera.prototype.getClassName = function () {
  54592. return "ArcFollowCamera";
  54593. };
  54594. return ArcFollowCamera;
  54595. }(BABYLON.TargetCamera));
  54596. BABYLON.ArcFollowCamera = ArcFollowCamera;
  54597. })(BABYLON || (BABYLON = {}));
  54598. //# sourceMappingURL=babylon.followCamera.js.map
  54599. /// <reference path="babylon.touchCamera.ts" />
  54600. var BABYLON;
  54601. (function (BABYLON) {
  54602. // We're mainly based on the logic defined into the FreeCamera code
  54603. var UniversalCamera = (function (_super) {
  54604. __extends(UniversalCamera, _super);
  54605. //-- end properties for backward compatibility for inputs
  54606. function UniversalCamera(name, position, scene) {
  54607. var _this = _super.call(this, name, position, scene) || this;
  54608. _this.inputs.addGamepad();
  54609. return _this;
  54610. }
  54611. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54612. //-- Begin properties for backward compatibility for inputs
  54613. get: function () {
  54614. var gamepad = this.inputs.attached["gamepad"];
  54615. if (gamepad)
  54616. return gamepad.gamepadAngularSensibility;
  54617. },
  54618. set: function (value) {
  54619. var gamepad = this.inputs.attached["gamepad"];
  54620. if (gamepad)
  54621. gamepad.gamepadAngularSensibility = value;
  54622. },
  54623. enumerable: true,
  54624. configurable: true
  54625. });
  54626. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54627. get: function () {
  54628. var gamepad = this.inputs.attached["gamepad"];
  54629. if (gamepad)
  54630. return gamepad.gamepadMoveSensibility;
  54631. },
  54632. set: function (value) {
  54633. var gamepad = this.inputs.attached["gamepad"];
  54634. if (gamepad)
  54635. gamepad.gamepadMoveSensibility = value;
  54636. },
  54637. enumerable: true,
  54638. configurable: true
  54639. });
  54640. UniversalCamera.prototype.getClassName = function () {
  54641. return "UniversalCamera";
  54642. };
  54643. return UniversalCamera;
  54644. }(BABYLON.TouchCamera));
  54645. BABYLON.UniversalCamera = UniversalCamera;
  54646. })(BABYLON || (BABYLON = {}));
  54647. //# sourceMappingURL=babylon.universalCamera.js.map
  54648. /// <reference path="babylon.universalCamera.ts" />
  54649. var BABYLON;
  54650. (function (BABYLON) {
  54651. // We're mainly based on the logic defined into the FreeCamera code
  54652. var GamepadCamera = (function (_super) {
  54653. __extends(GamepadCamera, _super);
  54654. //-- end properties for backward compatibility for inputs
  54655. function GamepadCamera(name, position, scene) {
  54656. return _super.call(this, name, position, scene) || this;
  54657. }
  54658. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54659. //-- Begin properties for backward compatibility for inputs
  54660. get: function () {
  54661. var gamepad = this.inputs.attached["gamepad"];
  54662. if (gamepad)
  54663. return gamepad.gamepadAngularSensibility;
  54664. },
  54665. set: function (value) {
  54666. var gamepad = this.inputs.attached["gamepad"];
  54667. if (gamepad)
  54668. gamepad.gamepadAngularSensibility = value;
  54669. },
  54670. enumerable: true,
  54671. configurable: true
  54672. });
  54673. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54674. get: function () {
  54675. var gamepad = this.inputs.attached["gamepad"];
  54676. if (gamepad)
  54677. return gamepad.gamepadMoveSensibility;
  54678. },
  54679. set: function (value) {
  54680. var gamepad = this.inputs.attached["gamepad"];
  54681. if (gamepad)
  54682. gamepad.gamepadMoveSensibility = value;
  54683. },
  54684. enumerable: true,
  54685. configurable: true
  54686. });
  54687. GamepadCamera.prototype.getClassName = function () {
  54688. return "GamepadCamera";
  54689. };
  54690. return GamepadCamera;
  54691. }(BABYLON.UniversalCamera));
  54692. BABYLON.GamepadCamera = GamepadCamera;
  54693. })(BABYLON || (BABYLON = {}));
  54694. //# sourceMappingURL=babylon.gamepadCamera.js.map
  54695. var BABYLON;
  54696. (function (BABYLON) {
  54697. var PostProcessRenderPipelineManager = (function () {
  54698. function PostProcessRenderPipelineManager() {
  54699. this._renderPipelines = {};
  54700. }
  54701. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  54702. this._renderPipelines[renderPipeline._name] = renderPipeline;
  54703. };
  54704. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  54705. var renderPipeline = this._renderPipelines[renderPipelineName];
  54706. if (!renderPipeline) {
  54707. return;
  54708. }
  54709. renderPipeline._attachCameras(cameras, unique);
  54710. };
  54711. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  54712. var renderPipeline = this._renderPipelines[renderPipelineName];
  54713. if (!renderPipeline) {
  54714. return;
  54715. }
  54716. renderPipeline._detachCameras(cameras);
  54717. };
  54718. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54719. var renderPipeline = this._renderPipelines[renderPipelineName];
  54720. if (!renderPipeline) {
  54721. return;
  54722. }
  54723. renderPipeline._enableEffect(renderEffectName, cameras);
  54724. };
  54725. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54726. var renderPipeline = this._renderPipelines[renderPipelineName];
  54727. if (!renderPipeline) {
  54728. return;
  54729. }
  54730. renderPipeline._disableEffect(renderEffectName, cameras);
  54731. };
  54732. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  54733. var renderPipeline = this._renderPipelines[renderPipelineName];
  54734. if (!renderPipeline) {
  54735. return;
  54736. }
  54737. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  54738. };
  54739. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  54740. var renderPipeline = this._renderPipelines[renderPipelineName];
  54741. if (!renderPipeline) {
  54742. return;
  54743. }
  54744. renderPipeline._disableDisplayOnlyPass(cameras);
  54745. };
  54746. PostProcessRenderPipelineManager.prototype.update = function () {
  54747. for (var renderPipelineName in this._renderPipelines) {
  54748. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54749. var pipeline = this._renderPipelines[renderPipelineName];
  54750. if (!pipeline.isSupported) {
  54751. pipeline.dispose();
  54752. delete this._renderPipelines[renderPipelineName];
  54753. }
  54754. else {
  54755. pipeline._update();
  54756. }
  54757. }
  54758. }
  54759. };
  54760. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  54761. for (var renderPipelineName in this._renderPipelines) {
  54762. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54763. var pipeline = this._renderPipelines[renderPipelineName];
  54764. pipeline._rebuild();
  54765. }
  54766. }
  54767. };
  54768. PostProcessRenderPipelineManager.prototype.dispose = function () {
  54769. for (var renderPipelineName in this._renderPipelines) {
  54770. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54771. var pipeline = this._renderPipelines[renderPipelineName];
  54772. pipeline.dispose();
  54773. }
  54774. }
  54775. };
  54776. return PostProcessRenderPipelineManager;
  54777. }());
  54778. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  54779. })(BABYLON || (BABYLON = {}));
  54780. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  54781. var BABYLON;
  54782. (function (BABYLON) {
  54783. var PostProcessRenderPass = (function () {
  54784. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  54785. this._enabled = true;
  54786. this._refCount = 0;
  54787. this._name = name;
  54788. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  54789. this.setRenderList(renderList);
  54790. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  54791. this._renderTexture.onAfterRenderObservable.add(afterRender);
  54792. this._scene = scene;
  54793. this._renderList = renderList;
  54794. }
  54795. // private
  54796. PostProcessRenderPass.prototype._incRefCount = function () {
  54797. if (this._refCount === 0) {
  54798. this._scene.customRenderTargets.push(this._renderTexture);
  54799. }
  54800. return ++this._refCount;
  54801. };
  54802. PostProcessRenderPass.prototype._decRefCount = function () {
  54803. this._refCount--;
  54804. if (this._refCount <= 0) {
  54805. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  54806. }
  54807. return this._refCount;
  54808. };
  54809. PostProcessRenderPass.prototype._update = function () {
  54810. this.setRenderList(this._renderList);
  54811. };
  54812. // public
  54813. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  54814. this._renderTexture.renderList = renderList;
  54815. };
  54816. PostProcessRenderPass.prototype.getRenderTexture = function () {
  54817. return this._renderTexture;
  54818. };
  54819. return PostProcessRenderPass;
  54820. }());
  54821. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  54822. })(BABYLON || (BABYLON = {}));
  54823. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  54824. var BABYLON;
  54825. (function (BABYLON) {
  54826. var PostProcessRenderEffect = (function () {
  54827. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  54828. this._engine = engine;
  54829. this._name = name;
  54830. this._singleInstance = singleInstance || true;
  54831. this._getPostProcess = getPostProcess;
  54832. this._cameras = [];
  54833. this._indicesForCamera = [];
  54834. this._postProcesses = {};
  54835. this._renderPasses = {};
  54836. this._renderEffectAsPasses = {};
  54837. }
  54838. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  54839. get: function () {
  54840. for (var index in this._postProcesses) {
  54841. if (!this._postProcesses[index].isSupported) {
  54842. return false;
  54843. }
  54844. }
  54845. return true;
  54846. },
  54847. enumerable: true,
  54848. configurable: true
  54849. });
  54850. PostProcessRenderEffect.prototype._update = function () {
  54851. for (var renderPassName in this._renderPasses) {
  54852. this._renderPasses[renderPassName]._update();
  54853. }
  54854. };
  54855. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  54856. this._renderPasses[renderPass._name] = renderPass;
  54857. this._linkParameters();
  54858. };
  54859. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  54860. delete this._renderPasses[renderPass._name];
  54861. this._linkParameters();
  54862. };
  54863. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  54864. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  54865. this._linkParameters();
  54866. };
  54867. PostProcessRenderEffect.prototype.getPass = function (passName) {
  54868. for (var renderPassName in this._renderPasses) {
  54869. if (renderPassName === passName) {
  54870. return this._renderPasses[passName];
  54871. }
  54872. }
  54873. };
  54874. PostProcessRenderEffect.prototype.emptyPasses = function () {
  54875. this._renderPasses = {};
  54876. this._linkParameters();
  54877. };
  54878. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  54879. var cameraKey;
  54880. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54881. for (var i = 0; i < _cam.length; i++) {
  54882. var camera = _cam[i];
  54883. var cameraName = camera.name;
  54884. if (this._singleInstance) {
  54885. cameraKey = 0;
  54886. }
  54887. else {
  54888. cameraKey = cameraName;
  54889. }
  54890. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  54891. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  54892. if (!this._indicesForCamera[cameraName]) {
  54893. this._indicesForCamera[cameraName] = [];
  54894. }
  54895. this._indicesForCamera[cameraName].push(index);
  54896. if (this._cameras.indexOf(camera) === -1) {
  54897. this._cameras[cameraName] = camera;
  54898. }
  54899. for (var passName in this._renderPasses) {
  54900. this._renderPasses[passName]._incRefCount();
  54901. }
  54902. }
  54903. this._linkParameters();
  54904. };
  54905. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  54906. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54907. for (var i = 0; i < _cam.length; i++) {
  54908. var camera = _cam[i];
  54909. var cameraName = camera.name;
  54910. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  54911. var index = this._cameras.indexOf(cameraName);
  54912. this._indicesForCamera.splice(index, 1);
  54913. this._cameras.splice(index, 1);
  54914. for (var passName in this._renderPasses) {
  54915. this._renderPasses[passName]._decRefCount();
  54916. }
  54917. }
  54918. };
  54919. PostProcessRenderEffect.prototype._enable = function (cameras) {
  54920. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54921. for (var i = 0; i < _cam.length; i++) {
  54922. var camera = _cam[i];
  54923. var cameraName = camera.name;
  54924. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  54925. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  54926. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  54927. }
  54928. }
  54929. for (var passName in this._renderPasses) {
  54930. this._renderPasses[passName]._incRefCount();
  54931. }
  54932. }
  54933. };
  54934. PostProcessRenderEffect.prototype._disable = function (cameras) {
  54935. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54936. for (var i = 0; i < _cam.length; i++) {
  54937. var camera = _cam[i];
  54938. var cameraName = camera.Name;
  54939. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  54940. for (var passName in this._renderPasses) {
  54941. this._renderPasses[passName]._decRefCount();
  54942. }
  54943. }
  54944. };
  54945. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  54946. if (this._singleInstance) {
  54947. return this._postProcesses[0];
  54948. }
  54949. else {
  54950. return this._postProcesses[camera.name];
  54951. }
  54952. };
  54953. PostProcessRenderEffect.prototype._linkParameters = function () {
  54954. var _this = this;
  54955. for (var index in this._postProcesses) {
  54956. if (this.applyParameters) {
  54957. this.applyParameters(this._postProcesses[index]);
  54958. }
  54959. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  54960. _this._linkTextures(effect);
  54961. });
  54962. }
  54963. };
  54964. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  54965. for (var renderPassName in this._renderPasses) {
  54966. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  54967. }
  54968. for (var renderEffectName in this._renderEffectAsPasses) {
  54969. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  54970. }
  54971. };
  54972. return PostProcessRenderEffect;
  54973. }());
  54974. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  54975. })(BABYLON || (BABYLON = {}));
  54976. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  54977. var BABYLON;
  54978. (function (BABYLON) {
  54979. var PostProcessRenderPipeline = (function () {
  54980. function PostProcessRenderPipeline(engine, name) {
  54981. this._engine = engine;
  54982. this._name = name;
  54983. this._renderEffects = new Array();
  54984. this._renderEffectsForIsolatedPass = new Array();
  54985. this._cameras = [];
  54986. }
  54987. PostProcessRenderPipeline.prototype.getClassName = function () {
  54988. return "PostProcessRenderPipeline";
  54989. };
  54990. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  54991. get: function () {
  54992. for (var renderEffectName in this._renderEffects) {
  54993. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  54994. if (!this._renderEffects[renderEffectName].isSupported) {
  54995. return false;
  54996. }
  54997. }
  54998. }
  54999. return true;
  55000. },
  55001. enumerable: true,
  55002. configurable: true
  55003. });
  55004. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  55005. this._renderEffects[renderEffect._name] = renderEffect;
  55006. };
  55007. // private
  55008. PostProcessRenderPipeline.prototype._rebuild = function () {
  55009. };
  55010. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  55011. var renderEffects = this._renderEffects[renderEffectName];
  55012. if (!renderEffects) {
  55013. return;
  55014. }
  55015. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55016. };
  55017. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  55018. var renderEffects = this._renderEffects[renderEffectName];
  55019. if (!renderEffects) {
  55020. return;
  55021. }
  55022. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  55023. };
  55024. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  55025. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55026. var indicesToDelete = [];
  55027. var i;
  55028. for (i = 0; i < _cam.length; i++) {
  55029. var camera = _cam[i];
  55030. var cameraName = camera.name;
  55031. if (this._cameras.indexOf(camera) === -1) {
  55032. this._cameras[cameraName] = camera;
  55033. }
  55034. else if (unique) {
  55035. indicesToDelete.push(i);
  55036. }
  55037. }
  55038. for (i = 0; i < indicesToDelete.length; i++) {
  55039. cameras.splice(indicesToDelete[i], 1);
  55040. }
  55041. for (var renderEffectName in this._renderEffects) {
  55042. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55043. this._renderEffects[renderEffectName]._attachCameras(_cam);
  55044. }
  55045. }
  55046. };
  55047. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  55048. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55049. for (var renderEffectName in this._renderEffects) {
  55050. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55051. this._renderEffects[renderEffectName]._detachCameras(_cam);
  55052. }
  55053. }
  55054. for (var i = 0; i < _cam.length; i++) {
  55055. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  55056. }
  55057. };
  55058. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  55059. var _this = this;
  55060. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55061. var pass = null;
  55062. var renderEffectName;
  55063. for (renderEffectName in this._renderEffects) {
  55064. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55065. pass = this._renderEffects[renderEffectName].getPass(passName);
  55066. if (pass != null) {
  55067. break;
  55068. }
  55069. }
  55070. }
  55071. if (pass === null) {
  55072. return;
  55073. }
  55074. for (renderEffectName in this._renderEffects) {
  55075. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55076. this._renderEffects[renderEffectName]._disable(_cam);
  55077. }
  55078. }
  55079. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  55080. for (var i = 0; i < _cam.length; i++) {
  55081. var camera = _cam[i];
  55082. var cameraName = camera.name;
  55083. 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, null, _this._engine, true); });
  55084. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  55085. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  55086. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  55087. }
  55088. };
  55089. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  55090. var _this = this;
  55091. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55092. for (var i = 0; i < _cam.length; i++) {
  55093. var camera = _cam[i];
  55094. var cameraName = camera.name;
  55095. 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, null, _this._engine, true); });
  55096. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  55097. }
  55098. for (var renderEffectName in this._renderEffects) {
  55099. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55100. this._renderEffects[renderEffectName]._enable(_cam);
  55101. }
  55102. }
  55103. };
  55104. PostProcessRenderPipeline.prototype._update = function () {
  55105. for (var renderEffectName in this._renderEffects) {
  55106. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55107. this._renderEffects[renderEffectName]._update();
  55108. }
  55109. }
  55110. for (var i = 0; i < this._cameras.length; i++) {
  55111. var cameraName = this._cameras[i].name;
  55112. if (this._renderEffectsForIsolatedPass[cameraName]) {
  55113. this._renderEffectsForIsolatedPass[cameraName]._update();
  55114. }
  55115. }
  55116. };
  55117. PostProcessRenderPipeline.prototype._reset = function () {
  55118. this._renderEffects = new Array();
  55119. this._renderEffectsForIsolatedPass = new Array();
  55120. };
  55121. PostProcessRenderPipeline.prototype.dispose = function () {
  55122. // Must be implemented by children
  55123. };
  55124. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  55125. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  55126. __decorate([
  55127. BABYLON.serialize()
  55128. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  55129. return PostProcessRenderPipeline;
  55130. }());
  55131. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  55132. })(BABYLON || (BABYLON = {}));
  55133. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  55134. var BABYLON;
  55135. (function (BABYLON) {
  55136. var DepthRenderer = (function () {
  55137. function DepthRenderer(scene, type) {
  55138. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55139. var _this = this;
  55140. this._viewMatrix = BABYLON.Matrix.Zero();
  55141. this._projectionMatrix = BABYLON.Matrix.Zero();
  55142. this._transformMatrix = BABYLON.Matrix.Zero();
  55143. this._worldViewProjection = BABYLON.Matrix.Zero();
  55144. this._scene = scene;
  55145. var engine = scene.getEngine();
  55146. // Render target
  55147. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55148. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55149. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55150. this._depthMap.refreshRate = 1;
  55151. this._depthMap.renderParticles = false;
  55152. this._depthMap.renderList = null;
  55153. // set default depth value to 1.0 (far away)
  55154. this._depthMap.onClearObservable.add(function (engine) {
  55155. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55156. });
  55157. // Custom render function
  55158. var renderSubMesh = function (subMesh) {
  55159. var mesh = subMesh.getRenderingMesh();
  55160. var scene = _this._scene;
  55161. var engine = scene.getEngine();
  55162. // Culling
  55163. engine.setState(subMesh.getMaterial().backFaceCulling);
  55164. // Managing instances
  55165. var batch = mesh._getInstancesRenderList(subMesh._id);
  55166. if (batch.mustReturn) {
  55167. return;
  55168. }
  55169. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55170. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55171. engine.enableEffect(_this._effect);
  55172. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55173. var material = subMesh.getMaterial();
  55174. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55175. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  55176. // Alpha test
  55177. if (material && material.needAlphaTesting()) {
  55178. var alphaTexture = material.getAlphaTestTexture();
  55179. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55180. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55181. }
  55182. // Bones
  55183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55184. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55185. }
  55186. // Draw
  55187. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55188. }
  55189. };
  55190. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55191. var index;
  55192. if (depthOnlySubMeshes.length) {
  55193. engine.setColorWrite(false);
  55194. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55195. renderSubMesh(depthOnlySubMeshes.data[index]);
  55196. }
  55197. engine.setColorWrite(true);
  55198. }
  55199. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55200. renderSubMesh(opaqueSubMeshes.data[index]);
  55201. }
  55202. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55203. renderSubMesh(alphaTestSubMeshes.data[index]);
  55204. }
  55205. };
  55206. }
  55207. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55208. var material = subMesh.getMaterial();
  55209. if (material.disableDepthWrite) {
  55210. return false;
  55211. }
  55212. var defines = [];
  55213. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55214. var mesh = subMesh.getMesh();
  55215. var scene = mesh.getScene();
  55216. // Alpha test
  55217. if (material && material.needAlphaTesting()) {
  55218. defines.push("#define ALPHATEST");
  55219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55220. attribs.push(BABYLON.VertexBuffer.UVKind);
  55221. defines.push("#define UV1");
  55222. }
  55223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55225. defines.push("#define UV2");
  55226. }
  55227. }
  55228. // Bones
  55229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55232. if (mesh.numBoneInfluencers > 4) {
  55233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55235. }
  55236. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55237. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55238. }
  55239. else {
  55240. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55241. }
  55242. // Instances
  55243. if (useInstances) {
  55244. defines.push("#define INSTANCES");
  55245. attribs.push("world0");
  55246. attribs.push("world1");
  55247. attribs.push("world2");
  55248. attribs.push("world3");
  55249. }
  55250. // Get correct effect
  55251. var join = defines.join("\n");
  55252. if (this._cachedDefines !== join) {
  55253. this._cachedDefines = join;
  55254. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  55255. }
  55256. return this._effect.isReady();
  55257. };
  55258. DepthRenderer.prototype.getDepthMap = function () {
  55259. return this._depthMap;
  55260. };
  55261. // Methods
  55262. DepthRenderer.prototype.dispose = function () {
  55263. this._depthMap.dispose();
  55264. };
  55265. return DepthRenderer;
  55266. }());
  55267. BABYLON.DepthRenderer = DepthRenderer;
  55268. })(BABYLON || (BABYLON = {}));
  55269. //# sourceMappingURL=babylon.depthRenderer.js.map
  55270. var BABYLON;
  55271. (function (BABYLON) {
  55272. var SSAORenderingPipeline = (function (_super) {
  55273. __extends(SSAORenderingPipeline, _super);
  55274. /**
  55275. * @constructor
  55276. * @param {string} name - The rendering pipeline name
  55277. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55278. * @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 }
  55279. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55280. */
  55281. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55282. var _this = _super.call(this, scene.getEngine(), name) || this;
  55283. // Members
  55284. /**
  55285. * The PassPostProcess id in the pipeline that contains the original scene color
  55286. * @type {string}
  55287. */
  55288. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55289. /**
  55290. * The SSAO PostProcess id in the pipeline
  55291. * @type {string}
  55292. */
  55293. _this.SSAORenderEffect = "SSAORenderEffect";
  55294. /**
  55295. * The horizontal blur PostProcess id in the pipeline
  55296. * @type {string}
  55297. */
  55298. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55299. /**
  55300. * The vertical blur PostProcess id in the pipeline
  55301. * @type {string}
  55302. */
  55303. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55304. /**
  55305. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55306. * @type {string}
  55307. */
  55308. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55309. /**
  55310. * The output strength of the SSAO post-process. Default value is 1.0.
  55311. * @type {number}
  55312. */
  55313. _this.totalStrength = 1.0;
  55314. /**
  55315. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55316. * @type {number}
  55317. */
  55318. _this.radius = 0.0001;
  55319. /**
  55320. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55321. * Must not be equal to fallOff and superior to fallOff.
  55322. * Default value is 0.975
  55323. * @type {number}
  55324. */
  55325. _this.area = 0.0075;
  55326. /**
  55327. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55328. * Must not be equal to area and inferior to area.
  55329. * Default value is 0.0
  55330. * @type {number}
  55331. */
  55332. _this.fallOff = 0.000001;
  55333. /**
  55334. * The base color of the SSAO post-process
  55335. * The final result is "base + ssao" between [0, 1]
  55336. * @type {number}
  55337. */
  55338. _this.base = 0.5;
  55339. _this._firstUpdate = true;
  55340. _this._scene = scene;
  55341. // Set up assets
  55342. _this._createRandomTexture();
  55343. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55344. var ssaoRatio = ratio.ssaoRatio || ratio;
  55345. var combineRatio = ratio.combineRatio || ratio;
  55346. _this._ratio = {
  55347. ssaoRatio: ssaoRatio,
  55348. combineRatio: combineRatio
  55349. };
  55350. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55351. _this._createSSAOPostProcess(ssaoRatio);
  55352. _this._createBlurPostProcess(ssaoRatio);
  55353. _this._createSSAOCombinePostProcess(combineRatio);
  55354. // Set up pipeline
  55355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55360. // Finish
  55361. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55362. if (cameras)
  55363. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55364. return _this;
  55365. }
  55366. // Public Methods
  55367. /**
  55368. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55369. */
  55370. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55371. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55372. for (var i = 0; i < this._scene.cameras.length; i++) {
  55373. var camera = this._scene.cameras[i];
  55374. this._originalColorPostProcess.dispose(camera);
  55375. this._ssaoPostProcess.dispose(camera);
  55376. this._blurHPostProcess.dispose(camera);
  55377. this._blurVPostProcess.dispose(camera);
  55378. this._ssaoCombinePostProcess.dispose(camera);
  55379. }
  55380. this._randomTexture.dispose();
  55381. if (disableDepthRender)
  55382. this._scene.disableDepthRenderer();
  55383. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55384. _super.prototype.dispose.call(this);
  55385. };
  55386. // Private Methods
  55387. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55388. var _this = this;
  55389. /*
  55390. var samplerOffsets = [
  55391. -8.0, -6.0, -4.0, -2.0,
  55392. 0.0,
  55393. 2.0, 4.0, 6.0, 8.0
  55394. ];
  55395. */
  55396. var samples = 16;
  55397. var samplerOffsets = new Array();
  55398. for (var i = -8; i < 8; i++) {
  55399. samplerOffsets.push(i * 2);
  55400. }
  55401. 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");
  55402. this._blurHPostProcess.onApply = function (effect) {
  55403. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55404. effect.setTexture("depthSampler", _this._depthTexture);
  55405. if (_this._firstUpdate) {
  55406. effect.setArray("samplerOffsets", samplerOffsets);
  55407. }
  55408. };
  55409. 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");
  55410. this._blurVPostProcess.onApply = function (effect) {
  55411. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55412. effect.setTexture("depthSampler", _this._depthTexture);
  55413. if (_this._firstUpdate) {
  55414. effect.setArray("samplerOffsets", samplerOffsets);
  55415. _this._firstUpdate = false;
  55416. }
  55417. };
  55418. };
  55419. SSAORenderingPipeline.prototype._rebuild = function () {
  55420. this._firstUpdate = true;
  55421. _super.prototype._rebuild.call(this);
  55422. };
  55423. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55424. var _this = this;
  55425. var numSamples = 16;
  55426. var sampleSphere = [
  55427. 0.5381, 0.1856, -0.4319,
  55428. 0.1379, 0.2486, 0.4430,
  55429. 0.3371, 0.5679, -0.0057,
  55430. -0.6999, -0.0451, -0.0019,
  55431. 0.0689, -0.1598, -0.8547,
  55432. 0.0560, 0.0069, -0.1843,
  55433. -0.0146, 0.1402, 0.0762,
  55434. 0.0100, -0.1924, -0.0344,
  55435. -0.3577, -0.5301, -0.4358,
  55436. -0.3169, 0.1063, 0.0158,
  55437. 0.0103, -0.5869, 0.0046,
  55438. -0.0897, -0.4940, 0.3287,
  55439. 0.7119, -0.0154, -0.0918,
  55440. -0.0533, 0.0596, -0.5411,
  55441. 0.0352, -0.0631, 0.5460,
  55442. -0.4776, 0.2847, -0.0271
  55443. ];
  55444. var samplesFactor = 1.0 / numSamples;
  55445. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55446. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55447. "area", "fallOff", "base", "range", "viewport"
  55448. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55449. var viewport = new BABYLON.Vector2(0, 0);
  55450. this._ssaoPostProcess.onApply = function (effect) {
  55451. if (_this._firstUpdate) {
  55452. effect.setArray3("sampleSphere", sampleSphere);
  55453. effect.setFloat("samplesFactor", samplesFactor);
  55454. effect.setFloat("randTextureTiles", 4.0);
  55455. }
  55456. effect.setFloat("totalStrength", _this.totalStrength);
  55457. effect.setFloat("radius", _this.radius);
  55458. effect.setFloat("area", _this.area);
  55459. effect.setFloat("fallOff", _this.fallOff);
  55460. effect.setFloat("base", _this.base);
  55461. effect.setTexture("textureSampler", _this._depthTexture);
  55462. effect.setTexture("randomSampler", _this._randomTexture);
  55463. };
  55464. };
  55465. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55466. var _this = this;
  55467. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55468. this._ssaoCombinePostProcess.onApply = function (effect) {
  55469. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55470. };
  55471. };
  55472. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55473. var size = 512;
  55474. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55475. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55476. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55477. var context = this._randomTexture.getContext();
  55478. var rand = function (min, max) {
  55479. return Math.random() * (max - min) + min;
  55480. };
  55481. var randVector = BABYLON.Vector3.Zero();
  55482. for (var x = 0; x < size; x++) {
  55483. for (var y = 0; y < size; y++) {
  55484. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55485. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55486. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55487. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55488. context.fillRect(x, y, 1, 1);
  55489. }
  55490. }
  55491. this._randomTexture.update(false);
  55492. };
  55493. __decorate([
  55494. BABYLON.serialize()
  55495. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55496. __decorate([
  55497. BABYLON.serialize()
  55498. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55499. __decorate([
  55500. BABYLON.serialize()
  55501. ], SSAORenderingPipeline.prototype, "area", void 0);
  55502. __decorate([
  55503. BABYLON.serialize()
  55504. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55505. __decorate([
  55506. BABYLON.serialize()
  55507. ], SSAORenderingPipeline.prototype, "base", void 0);
  55508. __decorate([
  55509. BABYLON.serialize()
  55510. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55511. return SSAORenderingPipeline;
  55512. }(BABYLON.PostProcessRenderPipeline));
  55513. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55514. })(BABYLON || (BABYLON = {}));
  55515. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  55516. var BABYLON;
  55517. (function (BABYLON) {
  55518. var SSAO2RenderingPipeline = (function (_super) {
  55519. __extends(SSAO2RenderingPipeline, _super);
  55520. /**
  55521. * @constructor
  55522. * @param {string} name - The rendering pipeline name
  55523. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55524. * @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 }
  55525. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55526. */
  55527. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  55528. var _this = _super.call(this, scene.getEngine(), name) || this;
  55529. // Members
  55530. /**
  55531. * The PassPostProcess id in the pipeline that contains the original scene color
  55532. * @type {string}
  55533. */
  55534. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55535. /**
  55536. * The SSAO PostProcess id in the pipeline
  55537. * @type {string}
  55538. */
  55539. _this.SSAORenderEffect = "SSAORenderEffect";
  55540. /**
  55541. * The horizontal blur PostProcess id in the pipeline
  55542. * @type {string}
  55543. */
  55544. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55545. /**
  55546. * The vertical blur PostProcess id in the pipeline
  55547. * @type {string}
  55548. */
  55549. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55550. /**
  55551. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55552. * @type {string}
  55553. */
  55554. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55555. /**
  55556. * The output strength of the SSAO post-process. Default value is 1.0.
  55557. * @type {number}
  55558. */
  55559. _this.totalStrength = 1.0;
  55560. /**
  55561. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  55562. * @type {number}
  55563. */
  55564. _this.maxZ = 100.0;
  55565. /**
  55566. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  55567. * @type {number}
  55568. */
  55569. _this.minZAspect = 0.2;
  55570. /**
  55571. * Number of samples used for the SSAO calculations. Default value is 8
  55572. * @type {number}
  55573. */
  55574. _this._samples = 8;
  55575. /**
  55576. * Are we using bilateral blur ?
  55577. * @type {boolean}
  55578. */
  55579. _this._expensiveBlur = true;
  55580. /**
  55581. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  55582. * @type {number}
  55583. */
  55584. _this.radius = 2.0;
  55585. /**
  55586. * The base color of the SSAO post-process
  55587. * The final result is "base + ssao" between [0, 1]
  55588. * @type {number}
  55589. */
  55590. _this.base = 0.1;
  55591. _this._firstUpdate = true;
  55592. _this._scene = scene;
  55593. if (!_this.isSupported) {
  55594. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  55595. return _this;
  55596. }
  55597. var ssaoRatio = ratio.ssaoRatio || ratio;
  55598. var blurRatio = ratio.blurRatio || ratio;
  55599. _this._ratio = {
  55600. ssaoRatio: ssaoRatio,
  55601. blurRatio: blurRatio
  55602. };
  55603. // Set up assets
  55604. _this._createRandomTexture();
  55605. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  55606. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  55607. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55608. _this._createSSAOPostProcess(1.0);
  55609. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  55610. _this._createSSAOCombinePostProcess(blurRatio);
  55611. // Set up pipeline
  55612. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55613. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55614. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55615. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55616. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55617. // Finish
  55618. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55619. if (cameras)
  55620. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55621. return _this;
  55622. }
  55623. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  55624. get: function () {
  55625. return this._samples;
  55626. },
  55627. set: function (n) {
  55628. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  55629. this._samples = n;
  55630. this._sampleSphere = this._generateHemisphere();
  55631. this._firstUpdate = true;
  55632. },
  55633. enumerable: true,
  55634. configurable: true
  55635. });
  55636. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  55637. get: function () {
  55638. return this._expensiveBlur;
  55639. },
  55640. set: function (b) {
  55641. 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"]);
  55642. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  55643. this._expensiveBlur = b;
  55644. this._firstUpdate = true;
  55645. },
  55646. enumerable: true,
  55647. configurable: true
  55648. });
  55649. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  55650. /**
  55651. * Support test.
  55652. * @type {boolean}
  55653. */
  55654. get: function () {
  55655. var engine = BABYLON.Engine.LastCreatedEngine;
  55656. return engine.getCaps().drawBuffersExtension;
  55657. },
  55658. enumerable: true,
  55659. configurable: true
  55660. });
  55661. // Public Methods
  55662. /**
  55663. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55664. */
  55665. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  55666. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  55667. for (var i = 0; i < this._scene.cameras.length; i++) {
  55668. var camera = this._scene.cameras[i];
  55669. this._originalColorPostProcess.dispose(camera);
  55670. this._ssaoPostProcess.dispose(camera);
  55671. this._blurHPostProcess.dispose(camera);
  55672. this._blurVPostProcess.dispose(camera);
  55673. this._ssaoCombinePostProcess.dispose(camera);
  55674. }
  55675. this._randomTexture.dispose();
  55676. if (disableGeometryBufferRenderer)
  55677. this._scene.disableGeometryBufferRenderer();
  55678. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55679. _super.prototype.dispose.call(this);
  55680. };
  55681. // Private Methods
  55682. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  55683. var _this = this;
  55684. var samples = 16;
  55685. this._samplerOffsets = [];
  55686. var expensive = this.expensiveBlur;
  55687. for (var i = -8; i < 8; i++) {
  55688. this._samplerOffsets.push(i * 2 + 0.5);
  55689. }
  55690. 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");
  55691. this._blurHPostProcess.onApply = function (effect) {
  55692. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55693. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55694. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55695. effect.setFloat("radius", _this.radius);
  55696. effect.setTexture("depthSampler", _this._depthTexture);
  55697. if (_this._firstUpdate) {
  55698. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55699. }
  55700. };
  55701. 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");
  55702. this._blurVPostProcess.onApply = function (effect) {
  55703. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55704. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55705. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55706. effect.setFloat("radius", _this.radius);
  55707. effect.setTexture("depthSampler", _this._depthTexture);
  55708. if (_this._firstUpdate) {
  55709. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55710. _this._firstUpdate = false;
  55711. }
  55712. };
  55713. };
  55714. SSAO2RenderingPipeline.prototype._rebuild = function () {
  55715. this._firstUpdate = true;
  55716. _super.prototype._rebuild.call(this);
  55717. };
  55718. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  55719. var numSamples = this.samples;
  55720. var result = [];
  55721. var vector, scale;
  55722. var rand = function (min, max) {
  55723. return Math.random() * (max - min) + min;
  55724. };
  55725. var i = 0;
  55726. var normal = new BABYLON.Vector3(0, 0, 1);
  55727. while (i < numSamples) {
  55728. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  55729. vector.normalize();
  55730. scale = i / numSamples;
  55731. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  55732. vector.scaleInPlace(scale);
  55733. result.push(vector.x, vector.y, vector.z);
  55734. i++;
  55735. }
  55736. return result;
  55737. };
  55738. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55739. var _this = this;
  55740. var numSamples = this.samples;
  55741. this._sampleSphere = this._generateHemisphere();
  55742. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  55743. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55744. "base", "range", "projection", "near", "far", "texelSize",
  55745. "xViewport", "yViewport", "maxZ", "minZAspect"
  55746. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55747. this._ssaoPostProcess.onApply = function (effect) {
  55748. if (_this._firstUpdate) {
  55749. effect.setArray3("sampleSphere", _this._sampleSphere);
  55750. effect.setFloat("randTextureTiles", 4.0);
  55751. }
  55752. effect.setFloat("samplesFactor", 1 / _this.samples);
  55753. effect.setFloat("totalStrength", _this.totalStrength);
  55754. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  55755. effect.setFloat("radius", _this.radius);
  55756. effect.setFloat("maxZ", _this.maxZ);
  55757. effect.setFloat("minZAspect", _this.minZAspect);
  55758. effect.setFloat("base", _this.base);
  55759. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55760. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55761. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  55762. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  55763. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  55764. effect.setTexture("textureSampler", _this._depthTexture);
  55765. effect.setTexture("normalSampler", _this._normalTexture);
  55766. effect.setTexture("randomSampler", _this._randomTexture);
  55767. };
  55768. };
  55769. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55770. var _this = this;
  55771. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55772. this._ssaoCombinePostProcess.onApply = function (effect) {
  55773. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55774. };
  55775. };
  55776. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  55777. var size = 512;
  55778. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55779. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55780. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55781. var context = this._randomTexture.getContext();
  55782. var rand = function (min, max) {
  55783. return Math.random() * (max - min) + min;
  55784. };
  55785. var randVector = BABYLON.Vector3.Zero();
  55786. for (var x = 0; x < size; x++) {
  55787. for (var y = 0; y < size; y++) {
  55788. randVector.x = rand(0.0, 1.0);
  55789. randVector.y = rand(0.0, 1.0);
  55790. randVector.z = 0.0;
  55791. randVector.normalize();
  55792. randVector.scaleInPlace(255);
  55793. randVector.x = Math.floor(randVector.x);
  55794. randVector.y = Math.floor(randVector.y);
  55795. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55796. context.fillRect(x, y, 1, 1);
  55797. }
  55798. }
  55799. this._randomTexture.update(false);
  55800. };
  55801. __decorate([
  55802. BABYLON.serialize()
  55803. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  55804. __decorate([
  55805. BABYLON.serialize()
  55806. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  55807. __decorate([
  55808. BABYLON.serialize()
  55809. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  55810. __decorate([
  55811. BABYLON.serialize("samples")
  55812. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  55813. __decorate([
  55814. BABYLON.serialize("expensiveBlur")
  55815. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  55816. __decorate([
  55817. BABYLON.serialize()
  55818. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  55819. __decorate([
  55820. BABYLON.serialize()
  55821. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  55822. __decorate([
  55823. BABYLON.serialize()
  55824. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  55825. return SSAO2RenderingPipeline;
  55826. }(BABYLON.PostProcessRenderPipeline));
  55827. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  55828. })(BABYLON || (BABYLON = {}));
  55829. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  55830. // BABYLON.JS Chromatic Aberration GLSL Shader
  55831. // Author: Olivier Guyot
  55832. // Separates very slightly R, G and B colors on the edges of the screen
  55833. // Inspired by Francois Tarlier & Martins Upitis
  55834. var BABYLON;
  55835. (function (BABYLON) {
  55836. var LensRenderingPipeline = (function (_super) {
  55837. __extends(LensRenderingPipeline, _super);
  55838. /**
  55839. * @constructor
  55840. *
  55841. * Effect parameters are as follow:
  55842. * {
  55843. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55844. * edge_blur: number; // from 0 to x (1 for realism)
  55845. * distortion: number; // from 0 to x (1 for realism)
  55846. * grain_amount: number; // from 0 to 1
  55847. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55848. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55849. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55850. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55851. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55852. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55853. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55854. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55855. * }
  55856. * Note: if an effect parameter is unset, effect is disabled
  55857. *
  55858. * @param {string} name - The rendering pipeline name
  55859. * @param {object} parameters - An object containing all parameters (see above)
  55860. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55861. * @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)
  55862. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55863. */
  55864. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55865. if (ratio === void 0) { ratio = 1.0; }
  55866. var _this = _super.call(this, scene.getEngine(), name) || this;
  55867. // Lens effects can be of the following:
  55868. // - chromatic aberration (slight shift of RGB colors)
  55869. // - blur on the edge of the lens
  55870. // - lens distortion
  55871. // - depth-of-field blur & highlights enhancing
  55872. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55873. // - grain effect (noise or custom texture)
  55874. // Two additional texture samplers are needed:
  55875. // - depth map (for depth-of-field)
  55876. // - grain texture
  55877. /**
  55878. * The chromatic aberration PostProcess id in the pipeline
  55879. * @type {string}
  55880. */
  55881. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55882. /**
  55883. * The highlights enhancing PostProcess id in the pipeline
  55884. * @type {string}
  55885. */
  55886. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55887. /**
  55888. * The depth-of-field PostProcess id in the pipeline
  55889. * @type {string}
  55890. */
  55891. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55892. _this._scene = scene;
  55893. // Fetch texture samplers
  55894. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55895. if (parameters.grain_texture) {
  55896. _this._grainTexture = parameters.grain_texture;
  55897. }
  55898. else {
  55899. _this._createGrainTexture();
  55900. }
  55901. // save parameters
  55902. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55903. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55904. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55905. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  55906. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55907. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55908. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55909. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55910. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55911. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55912. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55913. // Create effects
  55914. _this._createChromaticAberrationPostProcess(ratio);
  55915. _this._createHighlightsPostProcess(ratio);
  55916. _this._createDepthOfFieldPostProcess(ratio / 4);
  55917. // Set up pipeline
  55918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55920. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55921. if (_this._highlightsGain === -1) {
  55922. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  55923. }
  55924. // Finish
  55925. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55926. if (cameras) {
  55927. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55928. }
  55929. return _this;
  55930. }
  55931. // public methods (self explanatory)
  55932. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55933. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55934. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55935. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55936. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55937. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55938. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55939. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55940. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55941. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55942. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55943. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55944. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55945. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55946. };
  55947. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55948. this._highlightsPostProcess.updateEffect();
  55949. };
  55950. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55951. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55952. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55953. this._highlightsGain = amount;
  55954. };
  55955. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55956. if (this._highlightsGain === -1) {
  55957. this._highlightsGain = 1.0;
  55958. }
  55959. this._highlightsThreshold = amount;
  55960. };
  55961. LensRenderingPipeline.prototype.disableHighlights = function () {
  55962. this._highlightsGain = -1;
  55963. };
  55964. /**
  55965. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55966. */
  55967. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55968. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55969. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55970. this._chromaticAberrationPostProcess = undefined;
  55971. this._highlightsPostProcess = undefined;
  55972. this._depthOfFieldPostProcess = undefined;
  55973. this._grainTexture.dispose();
  55974. if (disableDepthRender)
  55975. this._scene.disableDepthRenderer();
  55976. };
  55977. // colors shifting and distortion
  55978. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55979. var _this = this;
  55980. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55981. [], // samplers
  55982. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55983. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55984. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55985. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55986. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55987. };
  55988. };
  55989. // highlights enhancing
  55990. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55991. var _this = this;
  55992. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55993. [], // samplers
  55994. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55995. this._highlightsPostProcess.onApply = function (effect) {
  55996. effect.setFloat('gain', _this._highlightsGain);
  55997. effect.setFloat('threshold', _this._highlightsThreshold);
  55998. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55999. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56000. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56001. };
  56002. };
  56003. // colors shifting and distortion
  56004. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  56005. var _this = this;
  56006. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  56007. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  56008. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  56009. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  56010. this._depthOfFieldPostProcess.onApply = function (effect) {
  56011. effect.setTexture("depthSampler", _this._depthTexture);
  56012. effect.setTexture("grainSampler", _this._grainTexture);
  56013. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  56014. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  56015. effect.setFloat('grain_amount', _this._grainAmount);
  56016. effect.setBool('blur_noise', _this._blurNoise);
  56017. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  56018. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  56019. effect.setFloat('distortion', _this._distortion);
  56020. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  56021. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  56022. effect.setFloat('aperture', _this._dofAperture);
  56023. effect.setFloat('darken', _this._dofDarken);
  56024. effect.setFloat('edge_blur', _this._edgeBlur);
  56025. effect.setBool('highlights', (_this._highlightsGain !== -1));
  56026. effect.setFloat('near', _this._scene.activeCamera.minZ);
  56027. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  56028. };
  56029. };
  56030. // creates a black and white random noise texture, 512x512
  56031. LensRenderingPipeline.prototype._createGrainTexture = function () {
  56032. var size = 512;
  56033. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56034. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56035. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56036. var context = this._grainTexture.getContext();
  56037. var rand = function (min, max) {
  56038. return Math.random() * (max - min) + min;
  56039. };
  56040. var value;
  56041. for (var x = 0; x < size; x++) {
  56042. for (var y = 0; y < size; y++) {
  56043. value = Math.floor(rand(0.42, 0.58) * 255);
  56044. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56045. context.fillRect(x, y, 1, 1);
  56046. }
  56047. }
  56048. this._grainTexture.update(false);
  56049. };
  56050. return LensRenderingPipeline;
  56051. }(BABYLON.PostProcessRenderPipeline));
  56052. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56053. })(BABYLON || (BABYLON = {}));
  56054. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  56055. var BABYLON;
  56056. (function (BABYLON) {
  56057. var StandardRenderingPipeline = (function (_super) {
  56058. __extends(StandardRenderingPipeline, _super);
  56059. /**
  56060. * @constructor
  56061. * @param {string} name - The rendering pipeline name
  56062. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56063. * @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)
  56064. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56065. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56066. */
  56067. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56068. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56069. var _this = _super.call(this, scene.getEngine(), name) || this;
  56070. _this.downSampleX4PostProcess = null;
  56071. _this.brightPassPostProcess = null;
  56072. _this.blurHPostProcesses = [];
  56073. _this.blurVPostProcesses = [];
  56074. _this.textureAdderPostProcess = null;
  56075. _this.volumetricLightPostProcess = null;
  56076. _this.volumetricLightSmoothXPostProcess = null;
  56077. _this.volumetricLightSmoothYPostProcess = null;
  56078. _this.volumetricLightMergePostProces = null;
  56079. _this.volumetricLightFinalPostProcess = null;
  56080. _this.luminancePostProcess = null;
  56081. _this.luminanceDownSamplePostProcesses = [];
  56082. _this.hdrPostProcess = null;
  56083. _this.textureAdderFinalPostProcess = null;
  56084. _this.lensFlareFinalPostProcess = null;
  56085. _this.hdrFinalPostProcess = null;
  56086. _this.lensFlarePostProcess = null;
  56087. _this.lensFlareComposePostProcess = null;
  56088. _this.motionBlurPostProcess = null;
  56089. _this.depthOfFieldPostProcess = null;
  56090. // Values
  56091. _this.brightThreshold = 1.0;
  56092. _this.blurWidth = 512.0;
  56093. _this.horizontalBlur = false;
  56094. _this.exposure = 1.0;
  56095. _this.lensTexture = null;
  56096. _this.volumetricLightCoefficient = 0.2;
  56097. _this.volumetricLightPower = 4.0;
  56098. _this.volumetricLightBlurScale = 64.0;
  56099. _this.sourceLight = null;
  56100. _this.hdrMinimumLuminance = 1.0;
  56101. _this.hdrDecreaseRate = 0.5;
  56102. _this.hdrIncreaseRate = 0.5;
  56103. _this.lensColorTexture = null;
  56104. _this.lensFlareStrength = 20.0;
  56105. _this.lensFlareGhostDispersal = 1.4;
  56106. _this.lensFlareHaloWidth = 0.7;
  56107. _this.lensFlareDistortionStrength = 16.0;
  56108. _this.lensStarTexture = null;
  56109. _this.lensFlareDirtTexture = null;
  56110. _this.depthOfFieldDistance = 10.0;
  56111. _this.depthOfFieldBlurWidth = 64.0;
  56112. _this.motionStrength = 1.0;
  56113. // IAnimatable
  56114. _this.animations = [];
  56115. _this._currentDepthOfFieldSource = null;
  56116. _this._hdrCurrentLuminance = 1.0;
  56117. // Getters and setters
  56118. _this._bloomEnabled = true;
  56119. _this._depthOfFieldEnabled = false;
  56120. _this._vlsEnabled = false;
  56121. _this._lensFlareEnabled = false;
  56122. _this._hdrEnabled = false;
  56123. _this._motionBlurEnabled = false;
  56124. _this._motionBlurSamples = 64.0;
  56125. _this._volumetricLightStepsCount = 50.0;
  56126. _this._cameras = cameras || [];
  56127. // Initialize
  56128. _this._scene = scene;
  56129. _this._basePostProcess = originalPostProcess;
  56130. _this._ratio = ratio;
  56131. // Misc
  56132. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56133. // Finish
  56134. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56135. _this._buildPipeline();
  56136. return _this;
  56137. }
  56138. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  56139. get: function () {
  56140. return this._bloomEnabled;
  56141. },
  56142. set: function (enabled) {
  56143. if (this._bloomEnabled === enabled) {
  56144. return;
  56145. }
  56146. this._bloomEnabled = enabled;
  56147. this._buildPipeline();
  56148. },
  56149. enumerable: true,
  56150. configurable: true
  56151. });
  56152. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  56153. get: function () {
  56154. return this._depthOfFieldEnabled;
  56155. },
  56156. set: function (enabled) {
  56157. if (this._depthOfFieldEnabled === enabled) {
  56158. return;
  56159. }
  56160. this._depthOfFieldEnabled = enabled;
  56161. this._buildPipeline();
  56162. },
  56163. enumerable: true,
  56164. configurable: true
  56165. });
  56166. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  56167. get: function () {
  56168. return this._lensFlareEnabled;
  56169. },
  56170. set: function (enabled) {
  56171. if (this._lensFlareEnabled === enabled) {
  56172. return;
  56173. }
  56174. this._lensFlareEnabled = enabled;
  56175. this._buildPipeline();
  56176. },
  56177. enumerable: true,
  56178. configurable: true
  56179. });
  56180. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  56181. get: function () {
  56182. return this._hdrEnabled;
  56183. },
  56184. set: function (enabled) {
  56185. if (this._hdrEnabled === enabled) {
  56186. return;
  56187. }
  56188. this._hdrEnabled = enabled;
  56189. this._buildPipeline();
  56190. },
  56191. enumerable: true,
  56192. configurable: true
  56193. });
  56194. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  56195. get: function () {
  56196. return this._vlsEnabled;
  56197. },
  56198. set: function (enabled) {
  56199. if (this._vlsEnabled === enabled) {
  56200. return;
  56201. }
  56202. if (enabled) {
  56203. var geometry = this._scene.enableGeometryBufferRenderer();
  56204. if (!geometry) {
  56205. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  56206. return;
  56207. }
  56208. }
  56209. this._vlsEnabled = enabled;
  56210. this._buildPipeline();
  56211. },
  56212. enumerable: true,
  56213. configurable: true
  56214. });
  56215. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  56216. get: function () {
  56217. return this._motionBlurEnabled;
  56218. },
  56219. set: function (enabled) {
  56220. if (this._motionBlurEnabled === enabled) {
  56221. return;
  56222. }
  56223. this._motionBlurEnabled = enabled;
  56224. this._buildPipeline();
  56225. },
  56226. enumerable: true,
  56227. configurable: true
  56228. });
  56229. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  56230. get: function () {
  56231. return this._volumetricLightStepsCount;
  56232. },
  56233. set: function (count) {
  56234. if (this.volumetricLightPostProcess) {
  56235. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  56236. }
  56237. this._volumetricLightStepsCount = count;
  56238. },
  56239. enumerable: true,
  56240. configurable: true
  56241. });
  56242. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  56243. get: function () {
  56244. return this._motionBlurSamples;
  56245. },
  56246. set: function (samples) {
  56247. if (this.motionBlurPostProcess) {
  56248. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  56249. }
  56250. this._motionBlurSamples = samples;
  56251. },
  56252. enumerable: true,
  56253. configurable: true
  56254. });
  56255. StandardRenderingPipeline.prototype._buildPipeline = function () {
  56256. var _this = this;
  56257. var ratio = this._ratio;
  56258. var scene = this._scene;
  56259. this._disposePostProcesses();
  56260. this._reset();
  56261. // Create pass post-process
  56262. if (!this._basePostProcess) {
  56263. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  56264. this.originalPostProcess.onApply = function (effect) {
  56265. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  56266. };
  56267. }
  56268. else {
  56269. this.originalPostProcess = this._basePostProcess;
  56270. }
  56271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  56272. this._currentDepthOfFieldSource = this.originalPostProcess;
  56273. if (this._vlsEnabled) {
  56274. // Create volumetric light
  56275. this._createVolumetricLightPostProcess(scene, ratio);
  56276. // Create volumetric light final post-process
  56277. 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);
  56278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  56279. }
  56280. if (this._bloomEnabled) {
  56281. // Create down sample X4 post-process
  56282. this._createDownSampleX4PostProcess(scene, ratio / 2);
  56283. // Create bright pass post-process
  56284. this._createBrightPassPostProcess(scene, ratio / 2);
  56285. // Create gaussian blur post-processes (down sampling blurs)
  56286. this._createBlurPostProcesses(scene, ratio / 4, 1);
  56287. // Create texture adder post-process
  56288. this._createTextureAdderPostProcess(scene, ratio);
  56289. // Create depth-of-field source post-process
  56290. 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);
  56291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  56292. }
  56293. if (this._lensFlareEnabled) {
  56294. // Create lens flare post-process
  56295. this._createLensFlarePostProcess(scene, ratio);
  56296. // Create depth-of-field source post-process post lens-flare and disable it now
  56297. 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);
  56298. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  56299. }
  56300. if (this._hdrEnabled) {
  56301. // Create luminance
  56302. this._createLuminancePostProcesses(scene, this._floatTextureType);
  56303. // Create HDR
  56304. this._createHdrPostProcess(scene, ratio);
  56305. // Create depth-of-field source post-process post hdr and disable it now
  56306. 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);
  56307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  56308. }
  56309. if (this._depthOfFieldEnabled) {
  56310. // Create gaussian blur used by depth-of-field
  56311. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  56312. // Create depth-of-field post-process
  56313. this._createDepthOfFieldPostProcess(scene, ratio);
  56314. }
  56315. if (this._motionBlurEnabled) {
  56316. // Create motion blur post-process
  56317. this._createMotionBlurPostProcess(scene, ratio);
  56318. }
  56319. if (this._cameras !== null) {
  56320. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  56321. }
  56322. };
  56323. // Down Sample X4 Post-Processs
  56324. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56325. var _this = this;
  56326. var downSampleX4Offsets = new Array(32);
  56327. 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);
  56328. this.downSampleX4PostProcess.onApply = function (effect) {
  56329. var id = 0;
  56330. for (var i = -2; i < 2; i++) {
  56331. for (var j = -2; j < 2; j++) {
  56332. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  56333. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  56334. id += 2;
  56335. }
  56336. }
  56337. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56338. };
  56339. // Add to pipeline
  56340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  56341. };
  56342. // Brightpass Post-Process
  56343. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56344. var _this = this;
  56345. var brightOffsets = new Array(8);
  56346. 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);
  56347. this.brightPassPostProcess.onApply = function (effect) {
  56348. var sU = (1.0 / _this.brightPassPostProcess.width);
  56349. var sV = (1.0 / _this.brightPassPostProcess.height);
  56350. brightOffsets[0] = -0.5 * sU;
  56351. brightOffsets[1] = 0.5 * sV;
  56352. brightOffsets[2] = 0.5 * sU;
  56353. brightOffsets[3] = 0.5 * sV;
  56354. brightOffsets[4] = -0.5 * sU;
  56355. brightOffsets[5] = -0.5 * sV;
  56356. brightOffsets[6] = 0.5 * sU;
  56357. brightOffsets[7] = -0.5 * sV;
  56358. effect.setArray2("dsOffsets", brightOffsets);
  56359. effect.setFloat("brightThreshold", _this.brightThreshold);
  56360. };
  56361. // Add to pipeline
  56362. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  56363. };
  56364. // Create blur H&V post-processes
  56365. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  56366. var _this = this;
  56367. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  56368. var engine = scene.getEngine();
  56369. 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);
  56370. 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);
  56371. blurX.onActivateObservable.add(function () {
  56372. var dw = blurX.width / engine.getRenderingCanvas().width;
  56373. blurX.kernel = _this[blurWidthKey] * dw;
  56374. });
  56375. blurY.onActivateObservable.add(function () {
  56376. var dw = blurY.height / engine.getRenderingCanvas().height;
  56377. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  56378. });
  56379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  56380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  56381. this.blurHPostProcesses.push(blurX);
  56382. this.blurVPostProcesses.push(blurY);
  56383. };
  56384. // Create texture adder post-process
  56385. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56386. var _this = this;
  56387. 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);
  56388. this.textureAdderPostProcess.onApply = function (effect) {
  56389. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  56390. effect.setTexture("lensSampler", _this.lensTexture);
  56391. effect.setFloat("exposure", _this.exposure);
  56392. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  56393. };
  56394. // Add to pipeline
  56395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  56396. };
  56397. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  56398. var _this = this;
  56399. var geometryRenderer = scene.enableGeometryBufferRenderer();
  56400. geometryRenderer.enablePosition = true;
  56401. var geometry = geometryRenderer.getGBuffer();
  56402. // Base post-process
  56403. 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));
  56404. var depthValues = BABYLON.Vector2.Zero();
  56405. this.volumetricLightPostProcess.onApply = function (effect) {
  56406. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  56407. var generator = _this.sourceLight.getShadowGenerator();
  56408. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  56409. effect.setTexture("positionSampler", geometry.textures[2]);
  56410. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  56411. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  56412. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  56413. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  56414. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  56415. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  56416. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  56417. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  56418. effect.setVector2("depthValues", depthValues);
  56419. }
  56420. };
  56421. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  56422. // Smooth
  56423. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  56424. // Merge
  56425. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  56426. this.volumetricLightMergePostProces.onApply = function (effect) {
  56427. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  56428. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  56429. };
  56430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  56431. };
  56432. // Create luminance
  56433. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  56434. var _this = this;
  56435. // Create luminance
  56436. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  56437. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  56438. var offsets = [];
  56439. this.luminancePostProcess.onApply = function (effect) {
  56440. var sU = (1.0 / _this.luminancePostProcess.width);
  56441. var sV = (1.0 / _this.luminancePostProcess.height);
  56442. offsets[0] = -0.5 * sU;
  56443. offsets[1] = 0.5 * sV;
  56444. offsets[2] = 0.5 * sU;
  56445. offsets[3] = 0.5 * sV;
  56446. offsets[4] = -0.5 * sU;
  56447. offsets[5] = -0.5 * sV;
  56448. offsets[6] = 0.5 * sU;
  56449. offsets[7] = -0.5 * sV;
  56450. effect.setArray2("lumOffsets", offsets);
  56451. };
  56452. // Add to pipeline
  56453. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  56454. // Create down sample luminance
  56455. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  56456. var size = Math.pow(3, i);
  56457. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  56458. if (i === 0) {
  56459. defines += "#define FINAL_DOWN_SAMPLER";
  56460. }
  56461. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  56462. this.luminanceDownSamplePostProcesses.push(postProcess);
  56463. }
  56464. // Create callbacks and add effects
  56465. var lastLuminance = this.luminancePostProcess;
  56466. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  56467. var downSampleOffsets = new Array(18);
  56468. pp.onApply = function (effect) {
  56469. var id = 0;
  56470. for (var x = -1; x < 2; x++) {
  56471. for (var y = -1; y < 2; y++) {
  56472. downSampleOffsets[id] = x / lastLuminance.width;
  56473. downSampleOffsets[id + 1] = y / lastLuminance.height;
  56474. id += 2;
  56475. }
  56476. }
  56477. effect.setArray2("dsOffsets", downSampleOffsets);
  56478. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  56479. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56480. lastLuminance = _this.luminancePostProcess;
  56481. }
  56482. else {
  56483. lastLuminance = pp;
  56484. }
  56485. };
  56486. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56487. pp.onAfterRender = function (effect) {
  56488. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56489. 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);
  56490. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56491. };
  56492. }
  56493. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  56494. });
  56495. };
  56496. // Create HDR post-process
  56497. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  56498. var _this = this;
  56499. 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);
  56500. var outputLiminance = 1;
  56501. var time = 0;
  56502. var lastTime = 0;
  56503. this.hdrPostProcess.onApply = function (effect) {
  56504. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  56505. time += scene.getEngine().getDeltaTime();
  56506. if (outputLiminance < 0) {
  56507. outputLiminance = _this._hdrCurrentLuminance;
  56508. }
  56509. else {
  56510. var dt = (lastTime - time) / 1000.0;
  56511. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  56512. outputLiminance += _this.hdrDecreaseRate * dt;
  56513. }
  56514. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  56515. outputLiminance -= _this.hdrIncreaseRate * dt;
  56516. }
  56517. else {
  56518. outputLiminance = _this._hdrCurrentLuminance;
  56519. }
  56520. }
  56521. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  56522. effect.setFloat("averageLuminance", outputLiminance);
  56523. lastTime = time;
  56524. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  56525. };
  56526. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  56527. };
  56528. // Create lens flare post-process
  56529. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  56530. var _this = this;
  56531. 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);
  56532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  56533. this._createBlurPostProcesses(scene, ratio / 4, 2);
  56534. 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);
  56535. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  56536. var resolution = new BABYLON.Vector2(0, 0);
  56537. // Lens flare
  56538. this.lensFlarePostProcess.onApply = function (effect) {
  56539. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  56540. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  56541. effect.setFloat("strength", _this.lensFlareStrength);
  56542. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  56543. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  56544. // Shift
  56545. resolution.x = _this.lensFlarePostProcess.width;
  56546. resolution.y = _this.lensFlarePostProcess.height;
  56547. effect.setVector2("resolution", resolution);
  56548. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  56549. };
  56550. // Compose
  56551. 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);
  56552. 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);
  56553. this.lensFlareComposePostProcess.onApply = function (effect) {
  56554. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56555. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  56556. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  56557. // Lens start rotation matrix
  56558. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  56559. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  56560. 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));
  56561. camRot *= 4.0;
  56562. 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);
  56563. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  56564. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  56565. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  56566. };
  56567. };
  56568. // Create depth-of-field post-process
  56569. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  56570. var _this = this;
  56571. 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);
  56572. this.depthOfFieldPostProcess.onApply = function (effect) {
  56573. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56574. effect.setTexture("depthSampler", _this._getDepthTexture());
  56575. effect.setFloat("distance", _this.depthOfFieldDistance);
  56576. };
  56577. // Add to pipeline
  56578. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  56579. };
  56580. // Create motion blur post-process
  56581. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  56582. var _this = this;
  56583. 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);
  56584. var motionScale = 0;
  56585. var prevViewProjection = BABYLON.Matrix.Identity();
  56586. var invViewProjection = BABYLON.Matrix.Identity();
  56587. var viewProjection = BABYLON.Matrix.Identity();
  56588. var screenSize = BABYLON.Vector2.Zero();
  56589. this.motionBlurPostProcess.onApply = function (effect) {
  56590. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  56591. viewProjection.invertToRef(invViewProjection);
  56592. effect.setMatrix("inverseViewProjection", invViewProjection);
  56593. effect.setMatrix("prevViewProjection", prevViewProjection);
  56594. prevViewProjection = viewProjection;
  56595. screenSize.x = _this.motionBlurPostProcess.width;
  56596. screenSize.y = _this.motionBlurPostProcess.height;
  56597. effect.setVector2("screenSize", screenSize);
  56598. motionScale = scene.getEngine().getFps() / 60.0;
  56599. effect.setFloat("motionScale", motionScale);
  56600. effect.setFloat("motionStrength", _this.motionStrength);
  56601. effect.setTexture("depthSampler", _this._getDepthTexture());
  56602. };
  56603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  56604. };
  56605. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  56606. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  56607. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  56608. }
  56609. return this._scene.enableDepthRenderer().getDepthMap();
  56610. };
  56611. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  56612. for (var i = 0; i < this._cameras.length; i++) {
  56613. var camera = this._cameras[i];
  56614. if (this.originalPostProcess) {
  56615. this.originalPostProcess.dispose(camera);
  56616. }
  56617. if (this.downSampleX4PostProcess) {
  56618. this.downSampleX4PostProcess.dispose(camera);
  56619. }
  56620. if (this.brightPassPostProcess) {
  56621. this.brightPassPostProcess.dispose(camera);
  56622. }
  56623. if (this.textureAdderPostProcess) {
  56624. this.textureAdderPostProcess.dispose(camera);
  56625. }
  56626. if (this.textureAdderFinalPostProcess) {
  56627. this.textureAdderFinalPostProcess.dispose(camera);
  56628. }
  56629. if (this.volumetricLightPostProcess) {
  56630. this.volumetricLightPostProcess.dispose(camera);
  56631. }
  56632. if (this.volumetricLightSmoothXPostProcess) {
  56633. this.volumetricLightSmoothXPostProcess.dispose(camera);
  56634. }
  56635. if (this.volumetricLightSmoothYPostProcess) {
  56636. this.volumetricLightSmoothYPostProcess.dispose(camera);
  56637. }
  56638. if (this.volumetricLightMergePostProces) {
  56639. this.volumetricLightMergePostProces.dispose(camera);
  56640. }
  56641. if (this.volumetricLightFinalPostProcess) {
  56642. this.volumetricLightFinalPostProcess.dispose(camera);
  56643. }
  56644. if (this.lensFlarePostProcess) {
  56645. this.lensFlarePostProcess.dispose(camera);
  56646. }
  56647. if (this.lensFlareComposePostProcess) {
  56648. this.lensFlareComposePostProcess.dispose(camera);
  56649. }
  56650. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  56651. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  56652. }
  56653. if (this.luminancePostProcess) {
  56654. this.luminancePostProcess.dispose(camera);
  56655. }
  56656. if (this.hdrPostProcess) {
  56657. this.hdrPostProcess.dispose(camera);
  56658. }
  56659. if (this.hdrFinalPostProcess) {
  56660. this.hdrFinalPostProcess.dispose(camera);
  56661. }
  56662. if (this.depthOfFieldPostProcess) {
  56663. this.depthOfFieldPostProcess.dispose(camera);
  56664. }
  56665. if (this.motionBlurPostProcess) {
  56666. this.motionBlurPostProcess.dispose(camera);
  56667. }
  56668. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  56669. this.blurHPostProcesses[j].dispose(camera);
  56670. }
  56671. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  56672. this.blurVPostProcesses[j].dispose(camera);
  56673. }
  56674. }
  56675. this.originalPostProcess = null;
  56676. this.downSampleX4PostProcess = null;
  56677. this.brightPassPostProcess = null;
  56678. this.textureAdderPostProcess = null;
  56679. this.textureAdderFinalPostProcess = null;
  56680. this.volumetricLightPostProcess = null;
  56681. this.volumetricLightSmoothXPostProcess = null;
  56682. this.volumetricLightSmoothYPostProcess = null;
  56683. this.volumetricLightMergePostProces = null;
  56684. this.volumetricLightFinalPostProcess = null;
  56685. this.lensFlarePostProcess = null;
  56686. this.lensFlareComposePostProcess = null;
  56687. this.luminancePostProcess = null;
  56688. this.hdrPostProcess = null;
  56689. this.hdrFinalPostProcess = null;
  56690. this.depthOfFieldPostProcess = null;
  56691. this.motionBlurPostProcess = null;
  56692. this.luminanceDownSamplePostProcesses = [];
  56693. this.blurHPostProcesses = [];
  56694. this.blurVPostProcesses = [];
  56695. };
  56696. // Dispose
  56697. StandardRenderingPipeline.prototype.dispose = function () {
  56698. this._disposePostProcesses();
  56699. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  56700. _super.prototype.dispose.call(this);
  56701. };
  56702. // Serialize rendering pipeline
  56703. StandardRenderingPipeline.prototype.serialize = function () {
  56704. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  56705. serializationObject.customType = "StandardRenderingPipeline";
  56706. return serializationObject;
  56707. };
  56708. /**
  56709. * Static members
  56710. */
  56711. // Parse serialized pipeline
  56712. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  56713. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  56714. };
  56715. // Luminance steps
  56716. StandardRenderingPipeline.LuminanceSteps = 6;
  56717. __decorate([
  56718. BABYLON.serialize()
  56719. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  56720. __decorate([
  56721. BABYLON.serialize()
  56722. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  56723. __decorate([
  56724. BABYLON.serialize()
  56725. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  56726. __decorate([
  56727. BABYLON.serialize()
  56728. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  56729. __decorate([
  56730. BABYLON.serializeAsTexture("lensTexture")
  56731. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  56732. __decorate([
  56733. BABYLON.serialize()
  56734. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  56735. __decorate([
  56736. BABYLON.serialize()
  56737. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  56738. __decorate([
  56739. BABYLON.serialize()
  56740. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  56741. __decorate([
  56742. BABYLON.serialize()
  56743. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  56744. __decorate([
  56745. BABYLON.serialize()
  56746. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  56747. __decorate([
  56748. BABYLON.serialize()
  56749. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  56750. __decorate([
  56751. BABYLON.serializeAsTexture("lensColorTexture")
  56752. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  56753. __decorate([
  56754. BABYLON.serialize()
  56755. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  56756. __decorate([
  56757. BABYLON.serialize()
  56758. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  56759. __decorate([
  56760. BABYLON.serialize()
  56761. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  56762. __decorate([
  56763. BABYLON.serialize()
  56764. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  56765. __decorate([
  56766. BABYLON.serializeAsTexture("lensStarTexture")
  56767. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  56768. __decorate([
  56769. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  56770. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  56771. __decorate([
  56772. BABYLON.serialize()
  56773. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  56774. __decorate([
  56775. BABYLON.serialize()
  56776. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  56777. __decorate([
  56778. BABYLON.serialize()
  56779. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  56780. __decorate([
  56781. BABYLON.serialize()
  56782. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  56783. __decorate([
  56784. BABYLON.serialize()
  56785. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  56786. __decorate([
  56787. BABYLON.serialize()
  56788. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  56789. __decorate([
  56790. BABYLON.serialize()
  56791. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  56792. __decorate([
  56793. BABYLON.serialize()
  56794. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  56795. __decorate([
  56796. BABYLON.serialize()
  56797. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  56798. __decorate([
  56799. BABYLON.serialize()
  56800. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  56801. __decorate([
  56802. BABYLON.serialize()
  56803. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  56804. return StandardRenderingPipeline;
  56805. }(BABYLON.PostProcessRenderPipeline));
  56806. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  56807. })(BABYLON || (BABYLON = {}));
  56808. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  56809. var BABYLON;
  56810. (function (BABYLON) {
  56811. var FxaaPostProcess = (function (_super) {
  56812. __extends(FxaaPostProcess, _super);
  56813. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56814. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56815. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  56816. _this.onApplyObservable.add(function (effect) {
  56817. var texelSize = _this.texelSize;
  56818. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  56819. });
  56820. return _this;
  56821. }
  56822. return FxaaPostProcess;
  56823. }(BABYLON.PostProcess));
  56824. BABYLON.FxaaPostProcess = FxaaPostProcess;
  56825. })(BABYLON || (BABYLON = {}));
  56826. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  56827. var BABYLON;
  56828. (function (BABYLON) {
  56829. var DefaultRenderingPipeline = (function (_super) {
  56830. __extends(DefaultRenderingPipeline, _super);
  56831. /**
  56832. * @constructor
  56833. * @param {string} name - The rendering pipeline name
  56834. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56835. * @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)
  56836. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56837. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  56838. */
  56839. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  56840. if (automaticBuild === void 0) { automaticBuild = true; }
  56841. var _this = _super.call(this, scene.getEngine(), name) || this;
  56842. _this.PassPostProcessId = "PassPostProcessEffect";
  56843. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  56844. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  56845. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  56846. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  56847. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  56848. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  56849. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  56850. // IAnimatable
  56851. _this.animations = [];
  56852. // Values
  56853. _this._bloomEnabled = false;
  56854. _this._fxaaEnabled = false;
  56855. _this._imageProcessingEnabled = true;
  56856. _this._bloomScale = 0.6;
  56857. _this._buildAllowed = true;
  56858. /**
  56859. * Specifies the size of the bloom blur kernel, relative to the final output size
  56860. */
  56861. _this.bloomKernel = 64;
  56862. /**
  56863. * Specifies the weight of the bloom in the final rendering
  56864. */
  56865. _this._bloomWeight = 0.15;
  56866. _this._cameras = cameras || [];
  56867. _this._buildAllowed = automaticBuild;
  56868. // Initialize
  56869. _this._scene = scene;
  56870. var caps = _this._scene.getEngine().getCaps();
  56871. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  56872. // Misc
  56873. if (_this._hdr) {
  56874. if (caps.textureHalfFloatRender) {
  56875. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56876. }
  56877. else if (caps.textureFloatRender) {
  56878. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56879. }
  56880. }
  56881. else {
  56882. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56883. }
  56884. // Attach
  56885. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56886. _this._buildPipeline();
  56887. return _this;
  56888. }
  56889. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  56890. get: function () {
  56891. return this._bloomWeight;
  56892. },
  56893. set: function (value) {
  56894. if (this._bloomWeight === value) {
  56895. return;
  56896. }
  56897. this._bloomWeight = value;
  56898. if (this._hdr && this.copyBack) {
  56899. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  56900. }
  56901. },
  56902. enumerable: true,
  56903. configurable: true
  56904. });
  56905. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  56906. get: function () {
  56907. return this._bloomScale;
  56908. },
  56909. set: function (value) {
  56910. if (this._bloomScale === value) {
  56911. return;
  56912. }
  56913. this._bloomScale = value;
  56914. this._buildPipeline();
  56915. },
  56916. enumerable: true,
  56917. configurable: true
  56918. });
  56919. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  56920. get: function () {
  56921. return this._bloomEnabled;
  56922. },
  56923. set: function (enabled) {
  56924. if (this._bloomEnabled === enabled) {
  56925. return;
  56926. }
  56927. this._bloomEnabled = enabled;
  56928. this._buildPipeline();
  56929. },
  56930. enumerable: true,
  56931. configurable: true
  56932. });
  56933. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  56934. get: function () {
  56935. return this._fxaaEnabled;
  56936. },
  56937. set: function (enabled) {
  56938. if (this._fxaaEnabled === enabled) {
  56939. return;
  56940. }
  56941. this._fxaaEnabled = enabled;
  56942. this._buildPipeline();
  56943. },
  56944. enumerable: true,
  56945. configurable: true
  56946. });
  56947. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  56948. get: function () {
  56949. return this._imageProcessingEnabled;
  56950. },
  56951. set: function (enabled) {
  56952. if (this._imageProcessingEnabled === enabled) {
  56953. return;
  56954. }
  56955. this._imageProcessingEnabled = enabled;
  56956. this._buildPipeline();
  56957. },
  56958. enumerable: true,
  56959. configurable: true
  56960. });
  56961. /**
  56962. * Force the compilation of the entire pipeline.
  56963. */
  56964. DefaultRenderingPipeline.prototype.prepare = function () {
  56965. var previousState = this._buildAllowed;
  56966. this._buildAllowed = true;
  56967. this._buildPipeline();
  56968. this._buildAllowed = previousState;
  56969. };
  56970. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  56971. var _this = this;
  56972. if (!this._buildAllowed) {
  56973. return;
  56974. }
  56975. var engine = this._scene.getEngine();
  56976. this._disposePostProcesses();
  56977. this._reset();
  56978. if (this.bloomEnabled) {
  56979. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56980. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  56981. if (!this._hdr) {
  56982. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56983. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  56984. this.highlights.autoClear = false;
  56985. this.highlights.alwaysForcePOT = true;
  56986. }
  56987. 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);
  56988. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  56989. this.blurX.alwaysForcePOT = true;
  56990. this.blurX.autoClear = false;
  56991. this.blurX.onActivateObservable.add(function () {
  56992. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  56993. _this.blurX.kernel = _this.bloomKernel * dw;
  56994. });
  56995. 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);
  56996. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  56997. this.blurY.alwaysForcePOT = true;
  56998. this.blurY.autoClear = false;
  56999. this.blurY.onActivateObservable.add(function () {
  57000. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  57001. _this.blurY.kernel = _this.bloomKernel * dh;
  57002. });
  57003. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57004. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  57005. this.copyBack.alwaysForcePOT = true;
  57006. if (this._hdr) {
  57007. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  57008. var w = this.bloomWeight;
  57009. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  57010. }
  57011. else {
  57012. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  57013. }
  57014. this.copyBack.autoClear = false;
  57015. }
  57016. if (this._imageProcessingEnabled) {
  57017. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57018. if (this._hdr) {
  57019. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  57020. }
  57021. else {
  57022. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  57023. }
  57024. }
  57025. if (this.fxaaEnabled) {
  57026. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57027. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  57028. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57029. }
  57030. else {
  57031. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  57032. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  57033. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  57034. }
  57035. if (this.bloomEnabled) {
  57036. if (this._hdr) {
  57037. this.copyBack.shareOutputWith(this.blurX);
  57038. if (this.imageProcessing) {
  57039. this.imageProcessing.shareOutputWith(this.pass);
  57040. this.imageProcessing.autoClear = false;
  57041. }
  57042. else if (this.fxaa) {
  57043. this.fxaa.shareOutputWith(this.pass);
  57044. }
  57045. else {
  57046. this.finalMerge.shareOutputWith(this.pass);
  57047. }
  57048. }
  57049. else {
  57050. if (this.fxaa) {
  57051. this.fxaa.shareOutputWith(this.pass);
  57052. }
  57053. else {
  57054. this.finalMerge.shareOutputWith(this.pass);
  57055. }
  57056. }
  57057. }
  57058. if (this._cameras !== null) {
  57059. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57060. }
  57061. };
  57062. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  57063. for (var i = 0; i < this._cameras.length; i++) {
  57064. var camera = this._cameras[i];
  57065. if (this.pass) {
  57066. this.pass.dispose(camera);
  57067. }
  57068. if (this.highlights) {
  57069. this.highlights.dispose(camera);
  57070. }
  57071. if (this.blurX) {
  57072. this.blurX.dispose(camera);
  57073. }
  57074. if (this.blurY) {
  57075. this.blurY.dispose(camera);
  57076. }
  57077. if (this.copyBack) {
  57078. this.copyBack.dispose(camera);
  57079. }
  57080. if (this.imageProcessing) {
  57081. this.imageProcessing.dispose(camera);
  57082. }
  57083. if (this.fxaa) {
  57084. this.fxaa.dispose(camera);
  57085. }
  57086. if (this.finalMerge) {
  57087. this.finalMerge.dispose(camera);
  57088. }
  57089. }
  57090. this.pass = null;
  57091. this.highlights = null;
  57092. this.blurX = null;
  57093. this.blurY = null;
  57094. this.copyBack = null;
  57095. this.imageProcessing = null;
  57096. this.fxaa = null;
  57097. this.finalMerge = null;
  57098. };
  57099. // Dispose
  57100. DefaultRenderingPipeline.prototype.dispose = function () {
  57101. this._disposePostProcesses();
  57102. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  57103. _super.prototype.dispose.call(this);
  57104. };
  57105. // Serialize rendering pipeline
  57106. DefaultRenderingPipeline.prototype.serialize = function () {
  57107. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57108. serializationObject.customType = "DefaultRenderingPipeline";
  57109. return serializationObject;
  57110. };
  57111. // Parse serialized pipeline
  57112. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  57113. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  57114. };
  57115. __decorate([
  57116. BABYLON.serialize()
  57117. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  57118. __decorate([
  57119. BABYLON.serialize()
  57120. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  57121. __decorate([
  57122. BABYLON.serialize()
  57123. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  57124. __decorate([
  57125. BABYLON.serialize()
  57126. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  57127. __decorate([
  57128. BABYLON.serialize()
  57129. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  57130. __decorate([
  57131. BABYLON.serialize()
  57132. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  57133. __decorate([
  57134. BABYLON.serialize()
  57135. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  57136. __decorate([
  57137. BABYLON.serialize()
  57138. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  57139. return DefaultRenderingPipeline;
  57140. }(BABYLON.PostProcessRenderPipeline));
  57141. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  57142. })(BABYLON || (BABYLON = {}));
  57143. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  57144. var BABYLON;
  57145. (function (BABYLON) {
  57146. var GeometryBufferRenderer = (function () {
  57147. function GeometryBufferRenderer(scene, ratio) {
  57148. if (ratio === void 0) { ratio = 1; }
  57149. this._viewMatrix = BABYLON.Matrix.Zero();
  57150. this._projectionMatrix = BABYLON.Matrix.Zero();
  57151. this._transformMatrix = BABYLON.Matrix.Zero();
  57152. this._worldViewProjection = BABYLON.Matrix.Zero();
  57153. this._enablePosition = false;
  57154. this._scene = scene;
  57155. this._ratio = ratio;
  57156. // Render target
  57157. this._createRenderTargets();
  57158. }
  57159. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  57160. set: function (meshes) {
  57161. this._multiRenderTarget.renderList = meshes;
  57162. },
  57163. enumerable: true,
  57164. configurable: true
  57165. });
  57166. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  57167. get: function () {
  57168. return this._multiRenderTarget.isSupported;
  57169. },
  57170. enumerable: true,
  57171. configurable: true
  57172. });
  57173. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  57174. get: function () {
  57175. return this._enablePosition;
  57176. },
  57177. set: function (enable) {
  57178. this._enablePosition = enable;
  57179. this.dispose();
  57180. this._createRenderTargets();
  57181. },
  57182. enumerable: true,
  57183. configurable: true
  57184. });
  57185. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  57186. var material = subMesh.getMaterial();
  57187. if (material && material.disableDepthWrite) {
  57188. return false;
  57189. }
  57190. var defines = [];
  57191. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  57192. var mesh = subMesh.getMesh();
  57193. var scene = mesh.getScene();
  57194. // Alpha test
  57195. if (material && material.needAlphaTesting()) {
  57196. defines.push("#define ALPHATEST");
  57197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57198. attribs.push(BABYLON.VertexBuffer.UVKind);
  57199. defines.push("#define UV1");
  57200. }
  57201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57203. defines.push("#define UV2");
  57204. }
  57205. }
  57206. // Buffers
  57207. if (this._enablePosition) {
  57208. defines.push("#define POSITION");
  57209. }
  57210. // Bones
  57211. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57214. if (mesh.numBoneInfluencers > 4) {
  57215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57217. }
  57218. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57219. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57220. }
  57221. else {
  57222. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57223. }
  57224. // Instances
  57225. if (useInstances) {
  57226. defines.push("#define INSTANCES");
  57227. attribs.push("world0");
  57228. attribs.push("world1");
  57229. attribs.push("world2");
  57230. attribs.push("world3");
  57231. }
  57232. // Get correct effect
  57233. var join = defines.join("\n");
  57234. if (this._cachedDefines !== join) {
  57235. this._cachedDefines = join;
  57236. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  57237. }
  57238. return this._effect.isReady();
  57239. };
  57240. GeometryBufferRenderer.prototype.getGBuffer = function () {
  57241. return this._multiRenderTarget;
  57242. };
  57243. // Methods
  57244. GeometryBufferRenderer.prototype.dispose = function () {
  57245. this.getGBuffer().dispose();
  57246. };
  57247. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  57248. var _this = this;
  57249. var engine = this._scene.getEngine();
  57250. var count = this._enablePosition ? 3 : 2;
  57251. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  57252. if (!this.isSupported) {
  57253. return null;
  57254. }
  57255. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57256. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57257. this._multiRenderTarget.refreshRate = 1;
  57258. this._multiRenderTarget.renderParticles = false;
  57259. this._multiRenderTarget.renderList = null;
  57260. // set default depth value to 1.0 (far away)
  57261. this._multiRenderTarget.onClearObservable.add(function (engine) {
  57262. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  57263. });
  57264. // Custom render function
  57265. var renderSubMesh = function (subMesh) {
  57266. var mesh = subMesh.getRenderingMesh();
  57267. var scene = _this._scene;
  57268. var engine = scene.getEngine();
  57269. // Culling
  57270. engine.setState(subMesh.getMaterial().backFaceCulling);
  57271. // Managing instances
  57272. var batch = mesh._getInstancesRenderList(subMesh._id);
  57273. if (batch.mustReturn) {
  57274. return;
  57275. }
  57276. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57277. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57278. engine.enableEffect(_this._effect);
  57279. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57280. var material = subMesh.getMaterial();
  57281. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57282. _this._effect.setMatrix("view", scene.getViewMatrix());
  57283. // Alpha test
  57284. if (material && material.needAlphaTesting()) {
  57285. var alphaTexture = material.getAlphaTestTexture();
  57286. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57287. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57288. }
  57289. // Bones
  57290. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57291. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57292. }
  57293. // Draw
  57294. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57295. }
  57296. };
  57297. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57298. var index;
  57299. if (depthOnlySubMeshes.length) {
  57300. engine.setColorWrite(false);
  57301. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57302. renderSubMesh(depthOnlySubMeshes.data[index]);
  57303. }
  57304. engine.setColorWrite(true);
  57305. }
  57306. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57307. renderSubMesh(opaqueSubMeshes.data[index]);
  57308. }
  57309. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57310. renderSubMesh(alphaTestSubMeshes.data[index]);
  57311. }
  57312. };
  57313. };
  57314. return GeometryBufferRenderer;
  57315. }());
  57316. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  57317. })(BABYLON || (BABYLON = {}));
  57318. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  57319. var BABYLON;
  57320. (function (BABYLON) {
  57321. var RefractionPostProcess = (function (_super) {
  57322. __extends(RefractionPostProcess, _super);
  57323. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  57324. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  57325. _this.color = color;
  57326. _this.depth = depth;
  57327. _this.colorLevel = colorLevel;
  57328. _this.onActivateObservable.add(function (cam) {
  57329. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  57330. });
  57331. _this.onApplyObservable.add(function (effect) {
  57332. effect.setColor3("baseColor", _this.color);
  57333. effect.setFloat("depth", _this.depth);
  57334. effect.setFloat("colorLevel", _this.colorLevel);
  57335. effect.setTexture("refractionSampler", _this._refRexture);
  57336. });
  57337. return _this;
  57338. }
  57339. // Methods
  57340. RefractionPostProcess.prototype.dispose = function (camera) {
  57341. if (this._refRexture) {
  57342. this._refRexture.dispose();
  57343. }
  57344. _super.prototype.dispose.call(this, camera);
  57345. };
  57346. return RefractionPostProcess;
  57347. }(BABYLON.PostProcess));
  57348. BABYLON.RefractionPostProcess = RefractionPostProcess;
  57349. })(BABYLON || (BABYLON = {}));
  57350. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  57351. var BABYLON;
  57352. (function (BABYLON) {
  57353. var BlackAndWhitePostProcess = (function (_super) {
  57354. __extends(BlackAndWhitePostProcess, _super);
  57355. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  57356. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  57357. _this.degree = 1;
  57358. _this.onApplyObservable.add(function (effect) {
  57359. effect.setFloat("degree", _this.degree);
  57360. });
  57361. return _this;
  57362. }
  57363. return BlackAndWhitePostProcess;
  57364. }(BABYLON.PostProcess));
  57365. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  57366. })(BABYLON || (BABYLON = {}));
  57367. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  57368. var BABYLON;
  57369. (function (BABYLON) {
  57370. var ConvolutionPostProcess = (function (_super) {
  57371. __extends(ConvolutionPostProcess, _super);
  57372. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  57373. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  57374. _this.kernel = kernel;
  57375. _this.onApply = function (effect) {
  57376. effect.setFloat2("screenSize", _this.width, _this.height);
  57377. effect.setArray("kernel", _this.kernel);
  57378. };
  57379. return _this;
  57380. }
  57381. // Statics
  57382. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  57383. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  57384. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  57385. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  57386. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  57387. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  57388. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  57389. return ConvolutionPostProcess;
  57390. }(BABYLON.PostProcess));
  57391. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  57392. })(BABYLON || (BABYLON = {}));
  57393. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  57394. var BABYLON;
  57395. (function (BABYLON) {
  57396. var FilterPostProcess = (function (_super) {
  57397. __extends(FilterPostProcess, _super);
  57398. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  57399. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  57400. _this.kernelMatrix = kernelMatrix;
  57401. _this.onApply = function (effect) {
  57402. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  57403. };
  57404. return _this;
  57405. }
  57406. return FilterPostProcess;
  57407. }(BABYLON.PostProcess));
  57408. BABYLON.FilterPostProcess = FilterPostProcess;
  57409. })(BABYLON || (BABYLON = {}));
  57410. //# sourceMappingURL=babylon.filterPostProcess.js.map
  57411. var BABYLON;
  57412. (function (BABYLON) {
  57413. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  57414. var VolumetricLightScatteringPostProcess = (function (_super) {
  57415. __extends(VolumetricLightScatteringPostProcess, _super);
  57416. /**
  57417. * @constructor
  57418. * @param {string} name - The post-process name
  57419. * @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)
  57420. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  57421. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  57422. * @param {number} samples - The post-process quality, default 100
  57423. * @param {number} samplingMode - The post-process filtering mode
  57424. * @param {BABYLON.Engine} engine - The babylon engine
  57425. * @param {boolean} reusable - If the post-process is reusable
  57426. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  57427. */
  57428. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  57429. if (samples === void 0) { samples = 100; }
  57430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57431. 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;
  57432. _this._screenCoordinates = BABYLON.Vector2.Zero();
  57433. /**
  57434. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  57435. * @type {Vector3}
  57436. */
  57437. _this.customMeshPosition = BABYLON.Vector3.Zero();
  57438. /**
  57439. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  57440. * @type {boolean}
  57441. */
  57442. _this.useCustomMeshPosition = false;
  57443. /**
  57444. * If the post-process should inverse the light scattering direction
  57445. * @type {boolean}
  57446. */
  57447. _this.invert = true;
  57448. /**
  57449. * Array containing the excluded meshes not rendered in the internal pass
  57450. */
  57451. _this.excludedMeshes = new Array();
  57452. /**
  57453. * Controls the overall intensity of the post-process
  57454. * @type {number}
  57455. */
  57456. _this.exposure = 0.3;
  57457. /**
  57458. * Dissipates each sample's contribution in range [0, 1]
  57459. * @type {number}
  57460. */
  57461. _this.decay = 0.96815;
  57462. /**
  57463. * Controls the overall intensity of each sample
  57464. * @type {number}
  57465. */
  57466. _this.weight = 0.58767;
  57467. /**
  57468. * Controls the density of each sample
  57469. * @type {number}
  57470. */
  57471. _this.density = 0.926;
  57472. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  57473. var engine = scene.getEngine();
  57474. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  57475. // Configure mesh
  57476. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  57477. // Configure
  57478. _this._createPass(scene, ratio.passRatio || ratio);
  57479. _this.onActivate = function (camera) {
  57480. if (!_this.isSupported) {
  57481. _this.dispose(camera);
  57482. }
  57483. _this.onActivate = null;
  57484. };
  57485. _this.onApplyObservable.add(function (effect) {
  57486. _this._updateMeshScreenCoordinates(scene);
  57487. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  57488. effect.setFloat("exposure", _this.exposure);
  57489. effect.setFloat("decay", _this.decay);
  57490. effect.setFloat("weight", _this.weight);
  57491. effect.setFloat("density", _this.density);
  57492. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  57493. });
  57494. return _this;
  57495. }
  57496. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  57497. get: function () {
  57498. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57499. return false;
  57500. },
  57501. set: function (useDiffuseColor) {
  57502. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57503. },
  57504. enumerable: true,
  57505. configurable: true
  57506. });
  57507. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  57508. return "VolumetricLightScatteringPostProcess";
  57509. };
  57510. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  57511. var mesh = subMesh.getMesh();
  57512. // Render this.mesh as default
  57513. if (mesh === this.mesh) {
  57514. return mesh.material.isReady(mesh);
  57515. }
  57516. var defines = [];
  57517. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57518. var material = subMesh.getMaterial();
  57519. var needUV = false;
  57520. // Alpha test
  57521. if (material) {
  57522. if (material.needAlphaTesting()) {
  57523. defines.push("#define ALPHATEST");
  57524. }
  57525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57526. attribs.push(BABYLON.VertexBuffer.UVKind);
  57527. defines.push("#define UV1");
  57528. }
  57529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57530. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57531. defines.push("#define UV2");
  57532. }
  57533. }
  57534. // Bones
  57535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57538. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57539. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57540. }
  57541. else {
  57542. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57543. }
  57544. // Instances
  57545. if (useInstances) {
  57546. defines.push("#define INSTANCES");
  57547. attribs.push("world0");
  57548. attribs.push("world1");
  57549. attribs.push("world2");
  57550. attribs.push("world3");
  57551. }
  57552. // Get correct effect
  57553. var join = defines.join("\n");
  57554. if (this._cachedDefines !== join) {
  57555. this._cachedDefines = join;
  57556. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  57557. }
  57558. return this._volumetricLightScatteringPass.isReady();
  57559. };
  57560. /**
  57561. * Sets the new light position for light scattering effect
  57562. * @param {BABYLON.Vector3} The new custom light position
  57563. */
  57564. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  57565. this.customMeshPosition = position;
  57566. };
  57567. /**
  57568. * Returns the light position for light scattering effect
  57569. * @return {BABYLON.Vector3} The custom light position
  57570. */
  57571. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  57572. return this.customMeshPosition;
  57573. };
  57574. /**
  57575. * Disposes the internal assets and detaches the post-process from the camera
  57576. */
  57577. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  57578. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  57579. if (rttIndex !== -1) {
  57580. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  57581. }
  57582. this._volumetricLightScatteringRTT.dispose();
  57583. _super.prototype.dispose.call(this, camera);
  57584. };
  57585. /**
  57586. * Returns the render target texture used by the post-process
  57587. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  57588. */
  57589. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  57590. return this._volumetricLightScatteringRTT;
  57591. };
  57592. // Private methods
  57593. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  57594. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  57595. return true;
  57596. }
  57597. return false;
  57598. };
  57599. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  57600. var _this = this;
  57601. var engine = scene.getEngine();
  57602. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57603. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57604. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57605. this._volumetricLightScatteringRTT.renderList = null;
  57606. this._volumetricLightScatteringRTT.renderParticles = false;
  57607. var camera = this.getCamera();
  57608. if (camera) {
  57609. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57610. }
  57611. else {
  57612. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57613. }
  57614. // Custom render function for submeshes
  57615. var renderSubMesh = function (subMesh) {
  57616. var mesh = subMesh.getRenderingMesh();
  57617. if (_this._meshExcluded(mesh)) {
  57618. return;
  57619. }
  57620. var scene = mesh.getScene();
  57621. var engine = scene.getEngine();
  57622. // Culling
  57623. engine.setState(subMesh.getMaterial().backFaceCulling);
  57624. // Managing instances
  57625. var batch = mesh._getInstancesRenderList(subMesh._id);
  57626. if (batch.mustReturn) {
  57627. return;
  57628. }
  57629. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57630. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57631. var effect = _this._volumetricLightScatteringPass;
  57632. if (mesh === _this.mesh) {
  57633. if (subMesh.effect) {
  57634. effect = subMesh.effect;
  57635. }
  57636. else {
  57637. effect = subMesh.getMaterial().getEffect();
  57638. }
  57639. }
  57640. engine.enableEffect(effect);
  57641. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  57642. if (mesh === _this.mesh) {
  57643. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  57644. }
  57645. else {
  57646. var material = subMesh.getMaterial();
  57647. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  57648. // Alpha test
  57649. if (material && material.needAlphaTesting()) {
  57650. var alphaTexture = material.getAlphaTestTexture();
  57651. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  57652. if (alphaTexture) {
  57653. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57654. }
  57655. }
  57656. // Bones
  57657. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57658. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57659. }
  57660. }
  57661. // Draw
  57662. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  57663. }
  57664. };
  57665. // Render target texture callbacks
  57666. var savedSceneClearColor;
  57667. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  57668. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  57669. savedSceneClearColor = scene.clearColor;
  57670. scene.clearColor = sceneClearColor;
  57671. });
  57672. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  57673. scene.clearColor = savedSceneClearColor;
  57674. });
  57675. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57676. var engine = scene.getEngine();
  57677. var index;
  57678. if (depthOnlySubMeshes.length) {
  57679. engine.setColorWrite(false);
  57680. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57681. renderSubMesh(depthOnlySubMeshes.data[index]);
  57682. }
  57683. engine.setColorWrite(true);
  57684. }
  57685. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57686. renderSubMesh(opaqueSubMeshes.data[index]);
  57687. }
  57688. engine.setAlphaTesting(true);
  57689. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57690. renderSubMesh(alphaTestSubMeshes.data[index]);
  57691. }
  57692. engine.setAlphaTesting(false);
  57693. if (transparentSubMeshes.length) {
  57694. // Sort sub meshes
  57695. for (index = 0; index < transparentSubMeshes.length; index++) {
  57696. var submesh = transparentSubMeshes.data[index];
  57697. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  57698. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  57699. }
  57700. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  57701. sortedArray.sort(function (a, b) {
  57702. // Alpha index first
  57703. if (a._alphaIndex > b._alphaIndex) {
  57704. return 1;
  57705. }
  57706. if (a._alphaIndex < b._alphaIndex) {
  57707. return -1;
  57708. }
  57709. // Then distance to camera
  57710. if (a._distanceToCamera < b._distanceToCamera) {
  57711. return 1;
  57712. }
  57713. if (a._distanceToCamera > b._distanceToCamera) {
  57714. return -1;
  57715. }
  57716. return 0;
  57717. });
  57718. // Render sub meshes
  57719. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57720. for (index = 0; index < sortedArray.length; index++) {
  57721. renderSubMesh(sortedArray[index]);
  57722. }
  57723. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57724. }
  57725. };
  57726. };
  57727. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  57728. var transform = scene.getTransformMatrix();
  57729. var meshPosition;
  57730. if (this.useCustomMeshPosition) {
  57731. meshPosition = this.customMeshPosition;
  57732. }
  57733. else if (this.attachedNode) {
  57734. meshPosition = this.attachedNode.position;
  57735. }
  57736. else {
  57737. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  57738. }
  57739. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  57740. this._screenCoordinates.x = pos.x / this._viewPort.width;
  57741. this._screenCoordinates.y = pos.y / this._viewPort.height;
  57742. if (this.invert)
  57743. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  57744. };
  57745. // Static methods
  57746. /**
  57747. * Creates a default mesh for the Volumeric Light Scattering post-process
  57748. * @param {string} The mesh name
  57749. * @param {BABYLON.Scene} The scene where to create the mesh
  57750. * @return {BABYLON.Mesh} the default mesh
  57751. */
  57752. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  57753. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  57754. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57755. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  57756. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  57757. mesh.material = material;
  57758. return mesh;
  57759. };
  57760. __decorate([
  57761. BABYLON.serializeAsVector3()
  57762. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  57763. __decorate([
  57764. BABYLON.serialize()
  57765. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  57766. __decorate([
  57767. BABYLON.serialize()
  57768. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  57769. __decorate([
  57770. BABYLON.serializeAsMeshReference()
  57771. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  57772. __decorate([
  57773. BABYLON.serialize()
  57774. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  57775. __decorate([
  57776. BABYLON.serialize()
  57777. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  57778. __decorate([
  57779. BABYLON.serialize()
  57780. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  57781. __decorate([
  57782. BABYLON.serialize()
  57783. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  57784. __decorate([
  57785. BABYLON.serialize()
  57786. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  57787. return VolumetricLightScatteringPostProcess;
  57788. }(BABYLON.PostProcess));
  57789. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  57790. })(BABYLON || (BABYLON = {}));
  57791. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  57792. //
  57793. // This post-process allows the modification of rendered colors by using
  57794. // a 'look-up table' (LUT). This effect is also called Color Grading.
  57795. //
  57796. // The object needs to be provided an url to a texture containing the color
  57797. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  57798. // Use an image editing software to tweak the LUT to match your needs.
  57799. //
  57800. // For an example of a color LUT, see here:
  57801. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  57802. // For explanations on color grading, see here:
  57803. // http://udn.epicgames.com/Three/ColorGrading.html
  57804. //
  57805. var BABYLON;
  57806. (function (BABYLON) {
  57807. var ColorCorrectionPostProcess = (function (_super) {
  57808. __extends(ColorCorrectionPostProcess, _super);
  57809. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  57810. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  57811. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57812. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  57813. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57814. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57815. _this.onApply = function (effect) {
  57816. effect.setTexture("colorTable", _this._colorTableTexture);
  57817. };
  57818. return _this;
  57819. }
  57820. return ColorCorrectionPostProcess;
  57821. }(BABYLON.PostProcess));
  57822. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  57823. })(BABYLON || (BABYLON = {}));
  57824. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  57825. var BABYLON;
  57826. (function (BABYLON) {
  57827. var TonemappingOperator;
  57828. (function (TonemappingOperator) {
  57829. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57830. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57831. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57832. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57833. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57834. ;
  57835. var TonemapPostProcess = (function (_super) {
  57836. __extends(TonemapPostProcess, _super);
  57837. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57839. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57840. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  57841. _this._operator = _operator;
  57842. _this.exposureAdjustment = exposureAdjustment;
  57843. var defines = "#define ";
  57844. if (_this._operator === TonemappingOperator.Hable)
  57845. defines += "HABLE_TONEMAPPING";
  57846. else if (_this._operator === TonemappingOperator.Reinhard)
  57847. defines += "REINHARD_TONEMAPPING";
  57848. else if (_this._operator === TonemappingOperator.HejiDawson)
  57849. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57850. else if (_this._operator === TonemappingOperator.Photographic)
  57851. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57852. //sadly a second call to create the effect.
  57853. _this.updateEffect(defines);
  57854. _this.onApply = function (effect) {
  57855. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57856. };
  57857. return _this;
  57858. }
  57859. return TonemapPostProcess;
  57860. }(BABYLON.PostProcess));
  57861. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57862. })(BABYLON || (BABYLON = {}));
  57863. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  57864. var BABYLON;
  57865. (function (BABYLON) {
  57866. var DisplayPassPostProcess = (function (_super) {
  57867. __extends(DisplayPassPostProcess, _super);
  57868. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  57869. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  57870. }
  57871. return DisplayPassPostProcess;
  57872. }(BABYLON.PostProcess));
  57873. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  57874. })(BABYLON || (BABYLON = {}));
  57875. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  57876. var BABYLON;
  57877. (function (BABYLON) {
  57878. var HighlightsPostProcess = (function (_super) {
  57879. __extends(HighlightsPostProcess, _super);
  57880. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57882. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  57883. }
  57884. return HighlightsPostProcess;
  57885. }(BABYLON.PostProcess));
  57886. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  57887. })(BABYLON || (BABYLON = {}));
  57888. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  57889. var BABYLON;
  57890. (function (BABYLON) {
  57891. var ImageProcessingPostProcess = (function (_super) {
  57892. __extends(ImageProcessingPostProcess, _super);
  57893. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57894. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57895. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  57896. _this._fromLinearSpace = true;
  57897. /**
  57898. * Defines cache preventing GC.
  57899. */
  57900. _this._defines = {
  57901. IMAGEPROCESSING: false,
  57902. VIGNETTE: false,
  57903. VIGNETTEBLENDMODEMULTIPLY: false,
  57904. VIGNETTEBLENDMODEOPAQUE: false,
  57905. TONEMAPPING: false,
  57906. CONTRAST: false,
  57907. COLORCURVES: false,
  57908. COLORGRADING: false,
  57909. FROMLINEARSPACE: false,
  57910. SAMPLER3DGREENDEPTH: false,
  57911. SAMPLER3DBGRMAP: false,
  57912. IMAGEPROCESSINGPOSTPROCESS: false,
  57913. EXPOSURE: false,
  57914. };
  57915. // Setup the default processing configuration to the scene.
  57916. _this._attachImageProcessingConfiguration(null, true);
  57917. _this.imageProcessingConfiguration.applyByPostProcess = true;
  57918. _this.onApply = function (effect) {
  57919. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  57920. };
  57921. return _this;
  57922. }
  57923. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  57924. /**
  57925. * Gets the image processing configuration used either in this material.
  57926. */
  57927. get: function () {
  57928. return this._imageProcessingConfiguration;
  57929. },
  57930. /**
  57931. * Sets the Default image processing configuration used either in the this material.
  57932. *
  57933. * If sets to null, the scene one is in use.
  57934. */
  57935. set: function (value) {
  57936. this._attachImageProcessingConfiguration(value);
  57937. },
  57938. enumerable: true,
  57939. configurable: true
  57940. });
  57941. /**
  57942. * Attaches a new image processing configuration to the PBR Material.
  57943. * @param configuration
  57944. */
  57945. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  57946. var _this = this;
  57947. if (doNotBuild === void 0) { doNotBuild = false; }
  57948. if (configuration === this._imageProcessingConfiguration) {
  57949. return;
  57950. }
  57951. // Detaches observer.
  57952. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  57953. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  57954. }
  57955. // Pick the scene configuration if needed.
  57956. if (!configuration) {
  57957. var scene = null;
  57958. var engine = this.getEngine();
  57959. var camera = this.getCamera();
  57960. if (camera) {
  57961. scene = camera.getScene();
  57962. }
  57963. else if (engine && engine.scenes) {
  57964. var scenes = engine.scenes;
  57965. scene = scenes[scenes.length - 1];
  57966. }
  57967. else {
  57968. scene = BABYLON.Engine.LastCreatedScene;
  57969. }
  57970. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  57971. }
  57972. else {
  57973. this._imageProcessingConfiguration = configuration;
  57974. }
  57975. // Attaches observer.
  57976. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  57977. _this._updateParameters();
  57978. });
  57979. // Ensure the effect will be rebuilt.
  57980. if (!doNotBuild) {
  57981. this._updateParameters();
  57982. }
  57983. };
  57984. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  57985. /**
  57986. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  57987. */
  57988. get: function () {
  57989. return this.imageProcessingConfiguration.colorCurves;
  57990. },
  57991. /**
  57992. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  57993. */
  57994. set: function (value) {
  57995. this.imageProcessingConfiguration.colorCurves = value;
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  58001. /**
  58002. * Gets wether the color curves effect is enabled.
  58003. */
  58004. get: function () {
  58005. return this.imageProcessingConfiguration.colorCurvesEnabled;
  58006. },
  58007. /**
  58008. * Sets wether the color curves effect is enabled.
  58009. */
  58010. set: function (value) {
  58011. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  58012. },
  58013. enumerable: true,
  58014. configurable: true
  58015. });
  58016. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  58017. /**
  58018. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58019. */
  58020. get: function () {
  58021. return this.imageProcessingConfiguration.colorGradingTexture;
  58022. },
  58023. /**
  58024. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  58025. */
  58026. set: function (value) {
  58027. this.imageProcessingConfiguration.colorGradingTexture = value;
  58028. },
  58029. enumerable: true,
  58030. configurable: true
  58031. });
  58032. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  58033. /**
  58034. * Gets wether the color grading effect is enabled.
  58035. */
  58036. get: function () {
  58037. return this.imageProcessingConfiguration.colorGradingEnabled;
  58038. },
  58039. /**
  58040. * Gets wether the color grading effect is enabled.
  58041. */
  58042. set: function (value) {
  58043. this.imageProcessingConfiguration.colorGradingEnabled = value;
  58044. },
  58045. enumerable: true,
  58046. configurable: true
  58047. });
  58048. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  58049. /**
  58050. * Gets exposure used in the effect.
  58051. */
  58052. get: function () {
  58053. return this.imageProcessingConfiguration.exposure;
  58054. },
  58055. /**
  58056. * Sets exposure used in the effect.
  58057. */
  58058. set: function (value) {
  58059. this.imageProcessingConfiguration.exposure = value;
  58060. },
  58061. enumerable: true,
  58062. configurable: true
  58063. });
  58064. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  58065. /**
  58066. * Gets wether tonemapping is enabled or not.
  58067. */
  58068. get: function () {
  58069. return this._imageProcessingConfiguration.toneMappingEnabled;
  58070. },
  58071. /**
  58072. * Sets wether tonemapping is enabled or not
  58073. */
  58074. set: function (value) {
  58075. this._imageProcessingConfiguration.toneMappingEnabled = value;
  58076. },
  58077. enumerable: true,
  58078. configurable: true
  58079. });
  58080. ;
  58081. ;
  58082. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  58083. /**
  58084. * Gets contrast used in the effect.
  58085. */
  58086. get: function () {
  58087. return this.imageProcessingConfiguration.contrast;
  58088. },
  58089. /**
  58090. * Sets contrast used in the effect.
  58091. */
  58092. set: function (value) {
  58093. this.imageProcessingConfiguration.contrast = value;
  58094. },
  58095. enumerable: true,
  58096. configurable: true
  58097. });
  58098. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  58099. /**
  58100. * Gets Vignette stretch size.
  58101. */
  58102. get: function () {
  58103. return this.imageProcessingConfiguration.vignetteStretch;
  58104. },
  58105. /**
  58106. * Sets Vignette stretch size.
  58107. */
  58108. set: function (value) {
  58109. this.imageProcessingConfiguration.vignetteStretch = value;
  58110. },
  58111. enumerable: true,
  58112. configurable: true
  58113. });
  58114. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  58115. /**
  58116. * Gets Vignette centre X Offset.
  58117. */
  58118. get: function () {
  58119. return this.imageProcessingConfiguration.vignetteCentreX;
  58120. },
  58121. /**
  58122. * Sets Vignette centre X Offset.
  58123. */
  58124. set: function (value) {
  58125. this.imageProcessingConfiguration.vignetteCentreX = value;
  58126. },
  58127. enumerable: true,
  58128. configurable: true
  58129. });
  58130. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  58131. /**
  58132. * Gets Vignette centre Y Offset.
  58133. */
  58134. get: function () {
  58135. return this.imageProcessingConfiguration.vignetteCentreY;
  58136. },
  58137. /**
  58138. * Sets Vignette centre Y Offset.
  58139. */
  58140. set: function (value) {
  58141. this.imageProcessingConfiguration.vignetteCentreY = value;
  58142. },
  58143. enumerable: true,
  58144. configurable: true
  58145. });
  58146. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  58147. /**
  58148. * Gets Vignette weight or intensity of the vignette effect.
  58149. */
  58150. get: function () {
  58151. return this.imageProcessingConfiguration.vignetteWeight;
  58152. },
  58153. /**
  58154. * Sets Vignette weight or intensity of the vignette effect.
  58155. */
  58156. set: function (value) {
  58157. this.imageProcessingConfiguration.vignetteWeight = value;
  58158. },
  58159. enumerable: true,
  58160. configurable: true
  58161. });
  58162. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  58163. /**
  58164. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58165. * if vignetteEnabled is set to true.
  58166. */
  58167. get: function () {
  58168. return this.imageProcessingConfiguration.vignetteColor;
  58169. },
  58170. /**
  58171. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58172. * if vignetteEnabled is set to true.
  58173. */
  58174. set: function (value) {
  58175. this.imageProcessingConfiguration.vignetteColor = value;
  58176. },
  58177. enumerable: true,
  58178. configurable: true
  58179. });
  58180. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  58181. /**
  58182. * Gets Camera field of view used by the Vignette effect.
  58183. */
  58184. get: function () {
  58185. return this.imageProcessingConfiguration.vignetteCameraFov;
  58186. },
  58187. /**
  58188. * Sets Camera field of view used by the Vignette effect.
  58189. */
  58190. set: function (value) {
  58191. this.imageProcessingConfiguration.vignetteCameraFov = value;
  58192. },
  58193. enumerable: true,
  58194. configurable: true
  58195. });
  58196. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  58197. /**
  58198. * Gets the vignette blend mode allowing different kind of effect.
  58199. */
  58200. get: function () {
  58201. return this.imageProcessingConfiguration.vignetteBlendMode;
  58202. },
  58203. /**
  58204. * Sets the vignette blend mode allowing different kind of effect.
  58205. */
  58206. set: function (value) {
  58207. this.imageProcessingConfiguration.vignetteBlendMode = value;
  58208. },
  58209. enumerable: true,
  58210. configurable: true
  58211. });
  58212. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  58213. /**
  58214. * Gets wether the vignette effect is enabled.
  58215. */
  58216. get: function () {
  58217. return this.imageProcessingConfiguration.vignetteEnabled;
  58218. },
  58219. /**
  58220. * Sets wether the vignette effect is enabled.
  58221. */
  58222. set: function (value) {
  58223. this.imageProcessingConfiguration.vignetteEnabled = value;
  58224. },
  58225. enumerable: true,
  58226. configurable: true
  58227. });
  58228. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  58229. /**
  58230. * Gets wether the input of the processing is in Gamma or Linear Space.
  58231. */
  58232. get: function () {
  58233. return this._fromLinearSpace;
  58234. },
  58235. /**
  58236. * Sets wether the input of the processing is in Gamma or Linear Space.
  58237. */
  58238. set: function (value) {
  58239. if (this._fromLinearSpace === value) {
  58240. return;
  58241. }
  58242. this._fromLinearSpace = value;
  58243. this._updateParameters();
  58244. },
  58245. enumerable: true,
  58246. configurable: true
  58247. });
  58248. ImageProcessingPostProcess.prototype.getClassName = function () {
  58249. return "ImageProcessingPostProcess";
  58250. };
  58251. ImageProcessingPostProcess.prototype._updateParameters = function () {
  58252. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  58253. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  58254. var defines = "";
  58255. for (var define in this._defines) {
  58256. if (this._defines[define]) {
  58257. defines += "#define " + define + ";\r\n";
  58258. }
  58259. }
  58260. var samplers = ["textureSampler"];
  58261. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  58262. var uniforms = ["scale"];
  58263. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  58264. this.updateEffect(defines, uniforms, samplers);
  58265. };
  58266. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  58267. _super.prototype.dispose.call(this, camera);
  58268. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  58269. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  58270. }
  58271. this.imageProcessingConfiguration.applyByPostProcess = false;
  58272. };
  58273. __decorate([
  58274. BABYLON.serialize()
  58275. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  58276. return ImageProcessingPostProcess;
  58277. }(BABYLON.PostProcess));
  58278. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  58279. })(BABYLON || (BABYLON = {}));
  58280. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  58281. var BABYLON;
  58282. (function (BABYLON) {
  58283. var BlurPostProcess = (function (_super) {
  58284. __extends(BlurPostProcess, _super);
  58285. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  58286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58288. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  58289. _this.direction = direction;
  58290. _this._packedFloat = false;
  58291. _this.onApplyObservable.add(function (effect) {
  58292. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  58293. });
  58294. _this.kernel = kernel;
  58295. return _this;
  58296. }
  58297. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  58298. /**
  58299. * Gets the length in pixels of the blur sample region
  58300. */
  58301. get: function () {
  58302. return this._idealKernel;
  58303. },
  58304. /**
  58305. * Sets the length in pixels of the blur sample region
  58306. */
  58307. set: function (v) {
  58308. if (this._idealKernel === v) {
  58309. return;
  58310. }
  58311. v = Math.max(v, 1);
  58312. this._idealKernel = v;
  58313. this._kernel = this._nearestBestKernel(v);
  58314. this._updateParameters();
  58315. },
  58316. enumerable: true,
  58317. configurable: true
  58318. });
  58319. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  58320. /**
  58321. * Gets wether or not the blur is unpacking/repacking floats
  58322. */
  58323. get: function () {
  58324. return this._packedFloat;
  58325. },
  58326. /**
  58327. * Sets wether or not the blur needs to unpack/repack floats
  58328. */
  58329. set: function (v) {
  58330. if (this._packedFloat === v) {
  58331. return;
  58332. }
  58333. this._packedFloat = v;
  58334. this._updateParameters();
  58335. },
  58336. enumerable: true,
  58337. configurable: true
  58338. });
  58339. BlurPostProcess.prototype._updateParameters = function () {
  58340. // Generate sampling offsets and weights
  58341. var N = this._kernel;
  58342. var centerIndex = (N - 1) / 2;
  58343. // Generate Gaussian sampling weights over kernel
  58344. var offsets = [];
  58345. var weights = [];
  58346. var totalWeight = 0;
  58347. for (var i = 0; i < N; i++) {
  58348. var u = i / (N - 1);
  58349. var w = this._gaussianWeight(u * 2.0 - 1);
  58350. offsets[i] = (i - centerIndex);
  58351. weights[i] = w;
  58352. totalWeight += w;
  58353. }
  58354. // Normalize weights
  58355. for (var i = 0; i < weights.length; i++) {
  58356. weights[i] /= totalWeight;
  58357. }
  58358. // Optimize: combine samples to take advantage of hardware linear sampling
  58359. // Walk from left to center, combining pairs (symmetrically)
  58360. var linearSamplingWeights = [];
  58361. var linearSamplingOffsets = [];
  58362. var linearSamplingMap = [];
  58363. for (var i = 0; i <= centerIndex; i += 2) {
  58364. var j = Math.min(i + 1, Math.floor(centerIndex));
  58365. var singleCenterSample = i === j;
  58366. if (singleCenterSample) {
  58367. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58368. }
  58369. else {
  58370. var sharedCell = j === centerIndex;
  58371. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  58372. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  58373. if (offsetLinear === 0) {
  58374. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58375. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  58376. }
  58377. else {
  58378. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  58379. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  58380. }
  58381. }
  58382. }
  58383. for (var i = 0; i < linearSamplingMap.length; i++) {
  58384. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  58385. linearSamplingWeights[i] = linearSamplingMap[i].w;
  58386. }
  58387. // Replace with optimized
  58388. offsets = linearSamplingOffsets;
  58389. weights = linearSamplingWeights;
  58390. // Generate shaders
  58391. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  58392. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  58393. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  58394. var defines = "";
  58395. for (var i = 0; i < varyingCount; i++) {
  58396. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  58397. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  58398. }
  58399. var depCount = 0;
  58400. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  58401. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  58402. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  58403. depCount++;
  58404. }
  58405. if (this.packedFloat) {
  58406. defines += "#define PACKEDFLOAT 1";
  58407. }
  58408. this.updateEffect(defines, null, null, {
  58409. varyingCount: varyingCount,
  58410. depCount: depCount
  58411. });
  58412. };
  58413. /**
  58414. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  58415. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  58416. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  58417. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  58418. * The gaps between physical kernels are compensated for in the weighting of the samples
  58419. * @param idealKernel Ideal blur kernel.
  58420. * @return Nearest best kernel.
  58421. */
  58422. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  58423. var v = Math.round(idealKernel);
  58424. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  58425. var k = _a[_i];
  58426. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  58427. return Math.max(k, 3);
  58428. }
  58429. }
  58430. return Math.max(v, 3);
  58431. };
  58432. /**
  58433. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  58434. * @param x The point on the Gaussian distribution to sample.
  58435. * @return the value of the Gaussian function at x.
  58436. */
  58437. BlurPostProcess.prototype._gaussianWeight = function (x) {
  58438. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  58439. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  58440. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  58441. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  58442. // truncated at around 1.3% of peak strength.
  58443. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  58444. var sigma = (1 / 3);
  58445. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  58446. var exponent = -((x * x) / (2.0 * sigma * sigma));
  58447. var weight = (1.0 / denominator) * Math.exp(exponent);
  58448. return weight;
  58449. };
  58450. /**
  58451. * Generates a string that can be used as a floating point number in GLSL.
  58452. * @param x Value to print.
  58453. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  58454. * @return GLSL float string.
  58455. */
  58456. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  58457. if (decimalFigures === void 0) { decimalFigures = 8; }
  58458. return x.toFixed(decimalFigures).replace(/0+$/, '');
  58459. };
  58460. return BlurPostProcess;
  58461. }(BABYLON.PostProcess));
  58462. BABYLON.BlurPostProcess = BlurPostProcess;
  58463. })(BABYLON || (BABYLON = {}));
  58464. //# sourceMappingURL=babylon.blurPostProcess.js.map
  58465. /// <reference path="..\babylon.node.ts" />
  58466. var BABYLON;
  58467. (function (BABYLON) {
  58468. var Bone = (function (_super) {
  58469. __extends(Bone, _super);
  58470. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  58471. if (parentBone === void 0) { parentBone = null; }
  58472. var _this = _super.call(this, name, skeleton.getScene()) || this;
  58473. _this.name = name;
  58474. _this.children = new Array();
  58475. _this.animations = new Array();
  58476. _this._worldTransform = new BABYLON.Matrix();
  58477. _this._absoluteTransform = new BABYLON.Matrix();
  58478. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  58479. _this._scaleMatrix = BABYLON.Matrix.Identity();
  58480. _this._scaleVector = BABYLON.Vector3.One();
  58481. _this._negateScaleChildren = BABYLON.Vector3.One();
  58482. _this._scalingDeterminant = 1;
  58483. _this._skeleton = skeleton;
  58484. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  58485. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  58486. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  58487. _this._index = index;
  58488. skeleton.bones.push(_this);
  58489. _this.setParent(parentBone, false);
  58490. _this._updateDifferenceMatrix();
  58491. return _this;
  58492. }
  58493. Object.defineProperty(Bone.prototype, "_matrix", {
  58494. get: function () {
  58495. return this._localMatrix;
  58496. },
  58497. set: function (val) {
  58498. if (this._localMatrix) {
  58499. this._localMatrix.copyFrom(val);
  58500. }
  58501. else {
  58502. this._localMatrix = val;
  58503. }
  58504. },
  58505. enumerable: true,
  58506. configurable: true
  58507. });
  58508. // Members
  58509. Bone.prototype.getSkeleton = function () {
  58510. return this._skeleton;
  58511. };
  58512. Bone.prototype.getParent = function () {
  58513. return this._parent;
  58514. };
  58515. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  58516. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58517. if (this._parent === parent) {
  58518. return;
  58519. }
  58520. if (this._parent) {
  58521. var index = this._parent.children.indexOf(this);
  58522. if (index !== -1) {
  58523. this._parent.children.splice(index);
  58524. }
  58525. }
  58526. this._parent = parent;
  58527. if (this._parent) {
  58528. this._parent.children.push(this);
  58529. }
  58530. if (updateDifferenceMatrix) {
  58531. this._updateDifferenceMatrix();
  58532. }
  58533. };
  58534. Bone.prototype.getLocalMatrix = function () {
  58535. return this._localMatrix;
  58536. };
  58537. Bone.prototype.getBaseMatrix = function () {
  58538. return this._baseMatrix;
  58539. };
  58540. Bone.prototype.getRestPose = function () {
  58541. return this._restPose;
  58542. };
  58543. Bone.prototype.returnToRest = function () {
  58544. this.updateMatrix(this._restPose.clone());
  58545. };
  58546. Bone.prototype.getWorldMatrix = function () {
  58547. return this._worldTransform;
  58548. };
  58549. Bone.prototype.getInvertedAbsoluteTransform = function () {
  58550. return this._invertedAbsoluteTransform;
  58551. };
  58552. Bone.prototype.getAbsoluteTransform = function () {
  58553. return this._absoluteTransform;
  58554. };
  58555. Object.defineProperty(Bone.prototype, "position", {
  58556. // Properties (matches AbstractMesh properties)
  58557. get: function () {
  58558. return this.getPosition();
  58559. },
  58560. set: function (newPosition) {
  58561. this.setPosition(newPosition);
  58562. },
  58563. enumerable: true,
  58564. configurable: true
  58565. });
  58566. Object.defineProperty(Bone.prototype, "rotation", {
  58567. get: function () {
  58568. return this.getRotation();
  58569. },
  58570. set: function (newRotation) {
  58571. this.setRotation(newRotation);
  58572. },
  58573. enumerable: true,
  58574. configurable: true
  58575. });
  58576. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  58577. get: function () {
  58578. return this.getRotationQuaternion();
  58579. },
  58580. set: function (newRotation) {
  58581. this.setRotationQuaternion(newRotation);
  58582. },
  58583. enumerable: true,
  58584. configurable: true
  58585. });
  58586. Object.defineProperty(Bone.prototype, "scaling", {
  58587. get: function () {
  58588. return this.getScale();
  58589. },
  58590. set: function (newScaling) {
  58591. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  58592. },
  58593. enumerable: true,
  58594. configurable: true
  58595. });
  58596. // Methods
  58597. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  58598. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58599. this._baseMatrix = matrix.clone();
  58600. this._localMatrix = matrix.clone();
  58601. this._skeleton._markAsDirty();
  58602. if (updateDifferenceMatrix) {
  58603. this._updateDifferenceMatrix();
  58604. }
  58605. };
  58606. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  58607. if (!rootMatrix) {
  58608. rootMatrix = this._baseMatrix;
  58609. }
  58610. if (this._parent) {
  58611. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  58612. }
  58613. else {
  58614. this._absoluteTransform.copyFrom(rootMatrix);
  58615. }
  58616. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  58617. for (var index = 0; index < this.children.length; index++) {
  58618. this.children[index]._updateDifferenceMatrix();
  58619. }
  58620. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  58621. };
  58622. Bone.prototype.markAsDirty = function () {
  58623. this._currentRenderId++;
  58624. this._skeleton._markAsDirty();
  58625. };
  58626. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  58627. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58628. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  58629. // all animation may be coming from a library skeleton, so may need to create animation
  58630. if (this.animations.length === 0) {
  58631. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  58632. this.animations[0].setKeys([]);
  58633. }
  58634. // get animation info / verify there is such a range from the source bone
  58635. var sourceRange = source.animations[0].getRange(rangeName);
  58636. if (!sourceRange) {
  58637. return false;
  58638. }
  58639. var from = sourceRange.from;
  58640. var to = sourceRange.to;
  58641. var sourceKeys = source.animations[0].getKeys();
  58642. // rescaling prep
  58643. var sourceBoneLength = source.length;
  58644. var sourceParent = source.getParent();
  58645. var parent = this.getParent();
  58646. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  58647. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  58648. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  58649. var destKeys = this.animations[0].getKeys();
  58650. // loop vars declaration
  58651. var orig;
  58652. var origTranslation;
  58653. var mat;
  58654. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  58655. orig = sourceKeys[key];
  58656. if (orig.frame >= from && orig.frame <= to) {
  58657. if (rescaleAsRequired) {
  58658. mat = orig.value.clone();
  58659. // scale based on parent ratio, when bone has parent
  58660. if (parentScalingReqd) {
  58661. origTranslation = mat.getTranslation();
  58662. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  58663. // scale based on skeleton dimension ratio when root bone, and value is passed
  58664. }
  58665. else if (dimensionsScalingReqd) {
  58666. origTranslation = mat.getTranslation();
  58667. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  58668. // use original when root bone, and no data for skelDimensionsRatio
  58669. }
  58670. else {
  58671. mat = orig.value;
  58672. }
  58673. }
  58674. else {
  58675. mat = orig.value;
  58676. }
  58677. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  58678. }
  58679. }
  58680. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  58681. return true;
  58682. };
  58683. /**
  58684. * Translate the bone in local or world space.
  58685. * @param vec The amount to translate the bone.
  58686. * @param space The space that the translation is in.
  58687. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58688. */
  58689. Bone.prototype.translate = function (vec, space, mesh) {
  58690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58691. var lm = this.getLocalMatrix();
  58692. if (space == BABYLON.Space.LOCAL) {
  58693. lm.m[12] += vec.x;
  58694. lm.m[13] += vec.y;
  58695. lm.m[14] += vec.z;
  58696. }
  58697. else {
  58698. var wm;
  58699. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58700. if (mesh) {
  58701. wm = mesh.getWorldMatrix();
  58702. }
  58703. this._skeleton.computeAbsoluteTransforms();
  58704. var tmat = Bone._tmpMats[0];
  58705. var tvec = Bone._tmpVecs[0];
  58706. if (mesh) {
  58707. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58708. tmat.multiplyToRef(wm, tmat);
  58709. }
  58710. else {
  58711. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58712. }
  58713. tmat.m[12] = 0;
  58714. tmat.m[13] = 0;
  58715. tmat.m[14] = 0;
  58716. tmat.invert();
  58717. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  58718. lm.m[12] += tvec.x;
  58719. lm.m[13] += tvec.y;
  58720. lm.m[14] += tvec.z;
  58721. }
  58722. this.markAsDirty();
  58723. };
  58724. /**
  58725. * Set the postion of the bone in local or world space.
  58726. * @param position The position to set the bone.
  58727. * @param space The space that the position is in.
  58728. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58729. */
  58730. Bone.prototype.setPosition = function (position, space, mesh) {
  58731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58732. var lm = this.getLocalMatrix();
  58733. if (space == BABYLON.Space.LOCAL) {
  58734. lm.m[12] = position.x;
  58735. lm.m[13] = position.y;
  58736. lm.m[14] = position.z;
  58737. }
  58738. else {
  58739. var wm;
  58740. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58741. if (mesh) {
  58742. wm = mesh.getWorldMatrix();
  58743. }
  58744. this._skeleton.computeAbsoluteTransforms();
  58745. var tmat = Bone._tmpMats[0];
  58746. var vec = Bone._tmpVecs[0];
  58747. if (mesh) {
  58748. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58749. tmat.multiplyToRef(wm, tmat);
  58750. }
  58751. else {
  58752. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58753. }
  58754. tmat.invert();
  58755. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  58756. lm.m[12] = vec.x;
  58757. lm.m[13] = vec.y;
  58758. lm.m[14] = vec.z;
  58759. }
  58760. this.markAsDirty();
  58761. };
  58762. /**
  58763. * Set the absolute postion of the bone (world space).
  58764. * @param position The position to set the bone.
  58765. * @param mesh The mesh that this bone is attached to.
  58766. */
  58767. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  58768. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  58769. };
  58770. /**
  58771. * Set the scale of the bone on the x, y and z axes.
  58772. * @param x The scale of the bone on the x axis.
  58773. * @param x The scale of the bone on the y axis.
  58774. * @param z The scale of the bone on the z axis.
  58775. * @param scaleChildren Set this to true if children of the bone should be scaled.
  58776. */
  58777. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  58778. if (scaleChildren === void 0) { scaleChildren = false; }
  58779. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  58780. if (!scaleChildren) {
  58781. this._negateScaleChildren.x = 1 / x;
  58782. this._negateScaleChildren.y = 1 / y;
  58783. this._negateScaleChildren.z = 1 / z;
  58784. }
  58785. this._syncScaleVector();
  58786. }
  58787. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  58788. };
  58789. /**
  58790. * Scale the bone on the x, y and z axes.
  58791. * @param x The amount to scale the bone on the x axis.
  58792. * @param x The amount to scale the bone on the y axis.
  58793. * @param z The amount to scale the bone on the z axis.
  58794. * @param scaleChildren Set this to true if children of the bone should be scaled.
  58795. */
  58796. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  58797. if (scaleChildren === void 0) { scaleChildren = false; }
  58798. var locMat = this.getLocalMatrix();
  58799. var origLocMat = Bone._tmpMats[0];
  58800. origLocMat.copyFrom(locMat);
  58801. var origLocMatInv = Bone._tmpMats[1];
  58802. origLocMatInv.copyFrom(origLocMat);
  58803. origLocMatInv.invert();
  58804. var scaleMat = Bone._tmpMats[2];
  58805. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  58806. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  58807. this._scaleVector.x *= x;
  58808. this._scaleVector.y *= y;
  58809. this._scaleVector.z *= z;
  58810. locMat.multiplyToRef(origLocMatInv, locMat);
  58811. locMat.multiplyToRef(scaleMat, locMat);
  58812. locMat.multiplyToRef(origLocMat, locMat);
  58813. var parent = this.getParent();
  58814. if (parent) {
  58815. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  58816. }
  58817. else {
  58818. this.getAbsoluteTransform().copyFrom(locMat);
  58819. }
  58820. var len = this.children.length;
  58821. scaleMat.invert();
  58822. for (var i = 0; i < len; i++) {
  58823. var child = this.children[i];
  58824. var cm = child.getLocalMatrix();
  58825. cm.multiplyToRef(scaleMat, cm);
  58826. var lm = child.getLocalMatrix();
  58827. lm.m[12] *= x;
  58828. lm.m[13] *= y;
  58829. lm.m[14] *= z;
  58830. }
  58831. this.computeAbsoluteTransforms();
  58832. if (scaleChildren) {
  58833. for (var i = 0; i < len; i++) {
  58834. this.children[i].scale(x, y, z, scaleChildren);
  58835. }
  58836. }
  58837. this.markAsDirty();
  58838. };
  58839. /**
  58840. * Set the yaw, pitch, and roll of the bone in local or world space.
  58841. * @param yaw The rotation of the bone on the y axis.
  58842. * @param pitch The rotation of the bone on the x axis.
  58843. * @param roll The rotation of the bone on the z axis.
  58844. * @param space The space that the axes of rotation are in.
  58845. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58846. */
  58847. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  58848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58849. var rotMat = Bone._tmpMats[0];
  58850. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  58851. var rotMatInv = Bone._tmpMats[1];
  58852. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58853. rotMatInv.multiplyToRef(rotMat, rotMat);
  58854. this._rotateWithMatrix(rotMat, space, mesh);
  58855. };
  58856. /**
  58857. * Rotate the bone on an axis in local or world space.
  58858. * @param axis The axis to rotate the bone on.
  58859. * @param amount The amount to rotate the bone.
  58860. * @param space The space that the axis is in.
  58861. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58862. */
  58863. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  58864. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58865. var rmat = Bone._tmpMats[0];
  58866. rmat.m[12] = 0;
  58867. rmat.m[13] = 0;
  58868. rmat.m[14] = 0;
  58869. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  58870. this._rotateWithMatrix(rmat, space, mesh);
  58871. };
  58872. /**
  58873. * Set the rotation of the bone to a particular axis angle in local or world space.
  58874. * @param axis The axis to rotate the bone on.
  58875. * @param angle The angle that the bone should be rotated to.
  58876. * @param space The space that the axis is in.
  58877. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58878. */
  58879. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  58880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58881. var rotMat = Bone._tmpMats[0];
  58882. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  58883. var rotMatInv = Bone._tmpMats[1];
  58884. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58885. rotMatInv.multiplyToRef(rotMat, rotMat);
  58886. this._rotateWithMatrix(rotMat, space, mesh);
  58887. };
  58888. /**
  58889. * Set the euler rotation of the bone in local of world space.
  58890. * @param rotation The euler rotation that the bone should be set to.
  58891. * @param space The space that the rotation is in.
  58892. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58893. */
  58894. Bone.prototype.setRotation = function (rotation, space, mesh) {
  58895. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58896. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  58897. };
  58898. /**
  58899. * Set the quaternion rotation of the bone in local of world space.
  58900. * @param quat The quaternion rotation that the bone should be set to.
  58901. * @param space The space that the rotation is in.
  58902. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58903. */
  58904. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  58905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58906. var rotMatInv = Bone._tmpMats[0];
  58907. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58908. var rotMat = Bone._tmpMats[1];
  58909. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  58910. rotMatInv.multiplyToRef(rotMat, rotMat);
  58911. this._rotateWithMatrix(rotMat, space, mesh);
  58912. };
  58913. /**
  58914. * Set the rotation matrix of the bone in local of world space.
  58915. * @param rotMat The rotation matrix that the bone should be set to.
  58916. * @param space The space that the rotation is in.
  58917. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58918. */
  58919. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  58920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58921. var rotMatInv = Bone._tmpMats[0];
  58922. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58923. var rotMat2 = Bone._tmpMats[1];
  58924. rotMat2.copyFrom(rotMat);
  58925. rotMatInv.multiplyToRef(rotMat, rotMat2);
  58926. this._rotateWithMatrix(rotMat2, space, mesh);
  58927. };
  58928. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  58929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58930. var lmat = this.getLocalMatrix();
  58931. var lx = lmat.m[12];
  58932. var ly = lmat.m[13];
  58933. var lz = lmat.m[14];
  58934. var parent = this.getParent();
  58935. var parentScale = Bone._tmpMats[3];
  58936. var parentScaleInv = Bone._tmpMats[4];
  58937. if (parent) {
  58938. if (space == BABYLON.Space.WORLD) {
  58939. if (mesh) {
  58940. parentScale.copyFrom(mesh.getWorldMatrix());
  58941. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  58942. }
  58943. else {
  58944. parentScale.copyFrom(parent.getAbsoluteTransform());
  58945. }
  58946. }
  58947. else {
  58948. parentScale = parent._scaleMatrix;
  58949. }
  58950. parentScaleInv.copyFrom(parentScale);
  58951. parentScaleInv.invert();
  58952. lmat.multiplyToRef(parentScale, lmat);
  58953. lmat.multiplyToRef(rmat, lmat);
  58954. lmat.multiplyToRef(parentScaleInv, lmat);
  58955. }
  58956. else {
  58957. if (space == BABYLON.Space.WORLD && mesh) {
  58958. parentScale.copyFrom(mesh.getWorldMatrix());
  58959. parentScaleInv.copyFrom(parentScale);
  58960. parentScaleInv.invert();
  58961. lmat.multiplyToRef(parentScale, lmat);
  58962. lmat.multiplyToRef(rmat, lmat);
  58963. lmat.multiplyToRef(parentScaleInv, lmat);
  58964. }
  58965. else {
  58966. lmat.multiplyToRef(rmat, lmat);
  58967. }
  58968. }
  58969. lmat.m[12] = lx;
  58970. lmat.m[13] = ly;
  58971. lmat.m[14] = lz;
  58972. this.computeAbsoluteTransforms();
  58973. this.markAsDirty();
  58974. };
  58975. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  58976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58977. if (space == BABYLON.Space.WORLD) {
  58978. var scaleMatrix = Bone._tmpMats[2];
  58979. scaleMatrix.copyFrom(this._scaleMatrix);
  58980. rotMatInv.copyFrom(this.getAbsoluteTransform());
  58981. if (mesh) {
  58982. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  58983. var meshScale = Bone._tmpMats[3];
  58984. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  58985. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  58986. }
  58987. rotMatInv.invert();
  58988. scaleMatrix.m[0] *= this._scalingDeterminant;
  58989. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  58990. }
  58991. else {
  58992. rotMatInv.copyFrom(this.getLocalMatrix());
  58993. rotMatInv.invert();
  58994. var scaleMatrix = Bone._tmpMats[2];
  58995. scaleMatrix.copyFrom(this._scaleMatrix);
  58996. if (this._parent) {
  58997. var pscaleMatrix = Bone._tmpMats[3];
  58998. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  58999. pscaleMatrix.invert();
  59000. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  59001. }
  59002. else {
  59003. scaleMatrix.m[0] *= this._scalingDeterminant;
  59004. }
  59005. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  59006. }
  59007. };
  59008. /**
  59009. * Get the scale of the bone
  59010. * @returns the scale of the bone
  59011. */
  59012. Bone.prototype.getScale = function () {
  59013. return this._scaleVector.clone();
  59014. };
  59015. /**
  59016. * Copy the scale of the bone to a vector3.
  59017. * @param result The vector3 to copy the scale to
  59018. */
  59019. Bone.prototype.getScaleToRef = function (result) {
  59020. result.copyFrom(this._scaleVector);
  59021. };
  59022. /**
  59023. * Get the position of the bone in local or world space.
  59024. * @param space The space that the returned position is in.
  59025. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59026. * @returns The position of the bone
  59027. */
  59028. Bone.prototype.getPosition = function (space, mesh) {
  59029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59030. var pos = BABYLON.Vector3.Zero();
  59031. this.getPositionToRef(space, mesh, pos);
  59032. return pos;
  59033. };
  59034. /**
  59035. * Copy the position of the bone to a vector3 in local or world space.
  59036. * @param space The space that the returned position is in.
  59037. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59038. * @param result The vector3 to copy the position to.
  59039. */
  59040. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  59041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59042. if (space == BABYLON.Space.LOCAL) {
  59043. var lm = this.getLocalMatrix();
  59044. result.x = lm.m[12];
  59045. result.y = lm.m[13];
  59046. result.z = lm.m[14];
  59047. }
  59048. else {
  59049. var wm;
  59050. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59051. if (mesh) {
  59052. wm = mesh.getWorldMatrix();
  59053. }
  59054. this._skeleton.computeAbsoluteTransforms();
  59055. var tmat = Bone._tmpMats[0];
  59056. if (mesh) {
  59057. tmat.copyFrom(this.getAbsoluteTransform());
  59058. tmat.multiplyToRef(wm, tmat);
  59059. }
  59060. else {
  59061. tmat = this.getAbsoluteTransform();
  59062. }
  59063. result.x = tmat.m[12];
  59064. result.y = tmat.m[13];
  59065. result.z = tmat.m[14];
  59066. }
  59067. };
  59068. /**
  59069. * Get the absolute position of the bone (world space).
  59070. * @param mesh The mesh that this bone is attached to.
  59071. * @returns The absolute position of the bone
  59072. */
  59073. Bone.prototype.getAbsolutePosition = function (mesh) {
  59074. var pos = BABYLON.Vector3.Zero();
  59075. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  59076. return pos;
  59077. };
  59078. /**
  59079. * Copy the absolute position of the bone (world space) to the result param.
  59080. * @param mesh The mesh that this bone is attached to.
  59081. * @param result The vector3 to copy the absolute position to.
  59082. */
  59083. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  59084. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  59085. };
  59086. /**
  59087. * Compute the absolute transforms of this bone and its children.
  59088. */
  59089. Bone.prototype.computeAbsoluteTransforms = function () {
  59090. if (this._parent) {
  59091. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  59092. }
  59093. else {
  59094. this._absoluteTransform.copyFrom(this._localMatrix);
  59095. var poseMatrix = this._skeleton.getPoseMatrix();
  59096. if (poseMatrix) {
  59097. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  59098. }
  59099. }
  59100. var children = this.children;
  59101. var len = children.length;
  59102. for (var i = 0; i < len; i++) {
  59103. children[i].computeAbsoluteTransforms();
  59104. }
  59105. };
  59106. Bone.prototype._syncScaleVector = function () {
  59107. var lm = this.getLocalMatrix();
  59108. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  59109. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  59110. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  59111. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  59112. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  59113. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  59114. this._scaleVector.x = xs * Math.sqrt(xsq);
  59115. this._scaleVector.y = ys * Math.sqrt(ysq);
  59116. this._scaleVector.z = zs * Math.sqrt(zsq);
  59117. if (this._parent) {
  59118. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  59119. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  59120. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  59121. }
  59122. 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);
  59123. };
  59124. /**
  59125. * Get the world direction from an axis that is in the local space of the bone.
  59126. * @param localAxis The local direction that is used to compute the world direction.
  59127. * @param mesh The mesh that this bone is attached to.
  59128. * @returns The world direction
  59129. */
  59130. Bone.prototype.getDirection = function (localAxis, mesh) {
  59131. var result = BABYLON.Vector3.Zero();
  59132. this.getDirectionToRef(localAxis, mesh, result);
  59133. return result;
  59134. };
  59135. /**
  59136. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  59137. * @param localAxis The local direction that is used to compute the world direction.
  59138. * @param mesh The mesh that this bone is attached to.
  59139. * @param result The vector3 that the world direction will be copied to.
  59140. */
  59141. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  59142. var wm;
  59143. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59144. if (mesh) {
  59145. wm = mesh.getWorldMatrix();
  59146. }
  59147. this._skeleton.computeAbsoluteTransforms();
  59148. var mat = Bone._tmpMats[0];
  59149. mat.copyFrom(this.getAbsoluteTransform());
  59150. if (mesh) {
  59151. mat.multiplyToRef(wm, mat);
  59152. }
  59153. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  59154. result.normalize();
  59155. };
  59156. /**
  59157. * Get the euler rotation of the bone in local or world space.
  59158. * @param space The space that the rotation should be in.
  59159. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59160. * @returns The euler rotation
  59161. */
  59162. Bone.prototype.getRotation = function (space, mesh) {
  59163. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59164. var result = BABYLON.Vector3.Zero();
  59165. this.getRotationToRef(space, mesh, result);
  59166. return result;
  59167. };
  59168. /**
  59169. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  59170. * @param space The space that the rotation should be in.
  59171. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59172. * @param result The vector3 that the rotation should be copied to.
  59173. */
  59174. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  59175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59176. var quat = Bone._tmpQuat;
  59177. this.getRotationQuaternionToRef(space, mesh, quat);
  59178. quat.toEulerAnglesToRef(result);
  59179. };
  59180. /**
  59181. * Get the quaternion rotation of the bone in either local or world space.
  59182. * @param space The space that the rotation should be in.
  59183. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59184. * @returns The quaternion rotation
  59185. */
  59186. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  59187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59188. var result = BABYLON.Quaternion.Identity();
  59189. this.getRotationQuaternionToRef(space, mesh, result);
  59190. return result;
  59191. };
  59192. /**
  59193. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  59194. * @param space The space that the rotation should be in.
  59195. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59196. * @param result The quaternion that the rotation should be copied to.
  59197. */
  59198. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  59199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59200. if (space == BABYLON.Space.LOCAL) {
  59201. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59202. }
  59203. else {
  59204. var mat = Bone._tmpMats[0];
  59205. var amat = this.getAbsoluteTransform();
  59206. if (mesh) {
  59207. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59208. }
  59209. else {
  59210. mat.copyFrom(amat);
  59211. }
  59212. mat.m[0] *= this._scalingDeterminant;
  59213. mat.m[1] *= this._scalingDeterminant;
  59214. mat.m[2] *= this._scalingDeterminant;
  59215. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59216. }
  59217. };
  59218. /**
  59219. * Get the rotation matrix of the bone in local or world space.
  59220. * @param space The space that the rotation should be in.
  59221. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59222. * @returns The rotation matrix
  59223. */
  59224. Bone.prototype.getRotationMatrix = function (space, mesh) {
  59225. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59226. var result = BABYLON.Matrix.Identity();
  59227. this.getRotationMatrixToRef(space, mesh, result);
  59228. return result;
  59229. };
  59230. /**
  59231. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  59232. * @param space The space that the rotation should be in.
  59233. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59234. * @param result The quaternion that the rotation should be copied to.
  59235. */
  59236. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  59237. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59238. if (space == BABYLON.Space.LOCAL) {
  59239. this.getLocalMatrix().getRotationMatrixToRef(result);
  59240. }
  59241. else {
  59242. var mat = Bone._tmpMats[0];
  59243. var amat = this.getAbsoluteTransform();
  59244. if (mesh) {
  59245. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59246. }
  59247. else {
  59248. mat.copyFrom(amat);
  59249. }
  59250. mat.m[0] *= this._scalingDeterminant;
  59251. mat.m[1] *= this._scalingDeterminant;
  59252. mat.m[2] *= this._scalingDeterminant;
  59253. mat.getRotationMatrixToRef(result);
  59254. }
  59255. };
  59256. /**
  59257. * Get the world position of a point that is in the local space of the bone.
  59258. * @param position The local position
  59259. * @param mesh The mesh that this bone is attached to.
  59260. * @returns The world position
  59261. */
  59262. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  59263. var result = BABYLON.Vector3.Zero();
  59264. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  59265. return result;
  59266. };
  59267. /**
  59268. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  59269. * @param position The local position
  59270. * @param mesh The mesh that this bone is attached to.
  59271. * @param result The vector3 that the world position should be copied to.
  59272. */
  59273. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  59274. var wm;
  59275. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59276. if (mesh) {
  59277. wm = mesh.getWorldMatrix();
  59278. }
  59279. this._skeleton.computeAbsoluteTransforms();
  59280. var tmat = Bone._tmpMats[0];
  59281. if (mesh) {
  59282. tmat.copyFrom(this.getAbsoluteTransform());
  59283. tmat.multiplyToRef(wm, tmat);
  59284. }
  59285. else {
  59286. tmat = this.getAbsoluteTransform();
  59287. }
  59288. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59289. };
  59290. /**
  59291. * Get the local position of a point that is in world space.
  59292. * @param position The world position
  59293. * @param mesh The mesh that this bone is attached to.
  59294. * @returns The local position
  59295. */
  59296. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  59297. var result = BABYLON.Vector3.Zero();
  59298. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  59299. return result;
  59300. };
  59301. /**
  59302. * Get the local position of a point that is in world space and copy it to the result param.
  59303. * @param position The world position
  59304. * @param mesh The mesh that this bone is attached to.
  59305. * @param result The vector3 that the local position should be copied to.
  59306. */
  59307. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  59308. var wm;
  59309. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59310. if (mesh) {
  59311. wm = mesh.getWorldMatrix();
  59312. }
  59313. this._skeleton.computeAbsoluteTransforms();
  59314. var tmat = Bone._tmpMats[0];
  59315. tmat.copyFrom(this.getAbsoluteTransform());
  59316. if (mesh) {
  59317. tmat.multiplyToRef(wm, tmat);
  59318. }
  59319. tmat.invert();
  59320. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59321. };
  59322. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59323. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  59324. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59325. return Bone;
  59326. }(BABYLON.Node));
  59327. BABYLON.Bone = Bone;
  59328. })(BABYLON || (BABYLON = {}));
  59329. //# sourceMappingURL=babylon.bone.js.map
  59330. var BABYLON;
  59331. (function (BABYLON) {
  59332. var BoneIKController = (function () {
  59333. function BoneIKController(mesh, bone, options) {
  59334. this.targetPosition = BABYLON.Vector3.Zero();
  59335. this.poleTargetPosition = BABYLON.Vector3.Zero();
  59336. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  59337. this.poleAngle = 0;
  59338. this.slerpAmount = 1;
  59339. this._bone1Quat = BABYLON.Quaternion.Identity();
  59340. this._bone1Mat = BABYLON.Matrix.Identity();
  59341. this._bone2Ang = Math.PI;
  59342. this._maxAngle = Math.PI;
  59343. this._rightHandedSystem = false;
  59344. this._bendAxis = BABYLON.Vector3.Right();
  59345. this._slerping = false;
  59346. this._adjustRoll = 0;
  59347. this._bone2 = bone;
  59348. this._bone1 = bone.getParent();
  59349. this.mesh = mesh;
  59350. var bonePos = bone.getPosition();
  59351. if (bone.getAbsoluteTransform().determinant() > 0) {
  59352. this._rightHandedSystem = true;
  59353. this._bendAxis.x = 0;
  59354. this._bendAxis.y = 0;
  59355. this._bendAxis.z = -1;
  59356. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  59357. this._adjustRoll = Math.PI * .5;
  59358. this._bendAxis.z = 1;
  59359. }
  59360. }
  59361. if (this._bone1.length) {
  59362. var boneScale1 = this._bone1.getScale();
  59363. var boneScale2 = this._bone2.getScale();
  59364. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  59365. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  59366. }
  59367. else if (this._bone1.children[0]) {
  59368. mesh.computeWorldMatrix(true);
  59369. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  59370. var pos2 = this._bone2.getAbsolutePosition(mesh);
  59371. var pos3 = this._bone1.getAbsolutePosition(mesh);
  59372. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  59373. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  59374. }
  59375. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  59376. this.maxAngle = Math.PI;
  59377. if (options) {
  59378. if (options.targetMesh) {
  59379. this.targetMesh = options.targetMesh;
  59380. this.targetMesh.computeWorldMatrix(true);
  59381. }
  59382. if (options.poleTargetMesh) {
  59383. this.poleTargetMesh = options.poleTargetMesh;
  59384. this.poleTargetMesh.computeWorldMatrix(true);
  59385. }
  59386. else if (options.poleTargetBone) {
  59387. this.poleTargetBone = options.poleTargetBone;
  59388. }
  59389. else if (this._bone1.getParent()) {
  59390. this.poleTargetBone = this._bone1.getParent();
  59391. }
  59392. if (options.poleTargetLocalOffset) {
  59393. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  59394. }
  59395. if (options.poleAngle) {
  59396. this.poleAngle = options.poleAngle;
  59397. }
  59398. if (options.bendAxis) {
  59399. this._bendAxis.copyFrom(options.bendAxis);
  59400. }
  59401. if (options.maxAngle) {
  59402. this.maxAngle = options.maxAngle;
  59403. }
  59404. if (options.slerpAmount) {
  59405. this.slerpAmount = options.slerpAmount;
  59406. }
  59407. }
  59408. }
  59409. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  59410. get: function () {
  59411. return this._maxAngle;
  59412. },
  59413. set: function (value) {
  59414. this._setMaxAngle(value);
  59415. },
  59416. enumerable: true,
  59417. configurable: true
  59418. });
  59419. BoneIKController.prototype._setMaxAngle = function (ang) {
  59420. if (ang < 0) {
  59421. ang = 0;
  59422. }
  59423. if (ang > Math.PI || ang == undefined) {
  59424. ang = Math.PI;
  59425. }
  59426. this._maxAngle = ang;
  59427. var a = this._bone1Length;
  59428. var b = this._bone2Length;
  59429. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  59430. };
  59431. BoneIKController.prototype.update = function () {
  59432. var bone1 = this._bone1;
  59433. var target = this.targetPosition;
  59434. var poleTarget = this.poleTargetPosition;
  59435. var mat1 = BoneIKController._tmpMats[0];
  59436. var mat2 = BoneIKController._tmpMats[1];
  59437. if (this.targetMesh) {
  59438. target.copyFrom(this.targetMesh.getAbsolutePosition());
  59439. }
  59440. if (this.poleTargetBone) {
  59441. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  59442. }
  59443. else if (this.poleTargetMesh) {
  59444. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  59445. }
  59446. var bonePos = BoneIKController._tmpVecs[0];
  59447. var zaxis = BoneIKController._tmpVecs[1];
  59448. var xaxis = BoneIKController._tmpVecs[2];
  59449. var yaxis = BoneIKController._tmpVecs[3];
  59450. var upAxis = BoneIKController._tmpVecs[4];
  59451. var _tmpQuat = BoneIKController._tmpQuat;
  59452. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  59453. poleTarget.subtractToRef(bonePos, upAxis);
  59454. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  59455. upAxis.y = 1;
  59456. }
  59457. else {
  59458. upAxis.normalize();
  59459. }
  59460. target.subtractToRef(bonePos, yaxis);
  59461. yaxis.normalize();
  59462. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  59463. zaxis.normalize();
  59464. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  59465. xaxis.normalize();
  59466. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  59467. var a = this._bone1Length;
  59468. var b = this._bone2Length;
  59469. var c = BABYLON.Vector3.Distance(bonePos, target);
  59470. if (this._maxReach > 0) {
  59471. c = Math.min(this._maxReach, c);
  59472. }
  59473. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  59474. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  59475. if (acosa > 1) {
  59476. acosa = 1;
  59477. }
  59478. if (acosb > 1) {
  59479. acosb = 1;
  59480. }
  59481. if (acosa < -1) {
  59482. acosa = -1;
  59483. }
  59484. if (acosb < -1) {
  59485. acosb = -1;
  59486. }
  59487. var angA = Math.acos(acosa);
  59488. var angB = Math.acos(acosb);
  59489. var angC = -angA - angB;
  59490. if (this._rightHandedSystem) {
  59491. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  59492. mat2.multiplyToRef(mat1, mat1);
  59493. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  59494. mat2.multiplyToRef(mat1, mat1);
  59495. }
  59496. else {
  59497. var _tmpVec = BoneIKController._tmpVecs[5];
  59498. _tmpVec.copyFrom(this._bendAxis);
  59499. _tmpVec.x *= -1;
  59500. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  59501. mat2.multiplyToRef(mat1, mat1);
  59502. }
  59503. if (this.poleAngle) {
  59504. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  59505. mat1.multiplyToRef(mat2, mat1);
  59506. }
  59507. if (this.slerpAmount < 1) {
  59508. if (!this._slerping) {
  59509. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  59510. }
  59511. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  59512. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  59513. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  59514. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  59515. this._slerping = true;
  59516. }
  59517. else {
  59518. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  59519. this._bone1Mat.copyFrom(mat1);
  59520. this._slerping = false;
  59521. }
  59522. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  59523. this._bone2Ang = angC;
  59524. };
  59525. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59526. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  59527. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59528. return BoneIKController;
  59529. }());
  59530. BABYLON.BoneIKController = BoneIKController;
  59531. })(BABYLON || (BABYLON = {}));
  59532. //# sourceMappingURL=babylon.boneIKController.js.map
  59533. var BABYLON;
  59534. (function (BABYLON) {
  59535. var BoneLookController = (function () {
  59536. /**
  59537. * Create a BoneLookController
  59538. * @param mesh the mesh that the bone belongs to
  59539. * @param bone the bone that will be looking to the target
  59540. * @param target the target Vector3 to look at
  59541. * @param settings optional settings:
  59542. * - maxYaw: the maximum angle the bone will yaw to
  59543. * - minYaw: the minimum angle the bone will yaw to
  59544. * - maxPitch: the maximum angle the bone will pitch to
  59545. * - minPitch: the minimum angle the bone will yaw to
  59546. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  59547. * - upAxis: the up axis of the coordinate system
  59548. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59549. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  59550. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  59551. * - adjustYaw: used to make an adjustment to the yaw of the bone
  59552. * - adjustPitch: used to make an adjustment to the pitch of the bone
  59553. * - adjustRoll: used to make an adjustment to the roll of the bone
  59554. **/
  59555. function BoneLookController(mesh, bone, target, options) {
  59556. /**
  59557. * The up axis of the coordinate system that is used when the bone is rotated.
  59558. */
  59559. this.upAxis = BABYLON.Vector3.Up();
  59560. /**
  59561. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59562. */
  59563. this.upAxisSpace = BABYLON.Space.LOCAL;
  59564. /**
  59565. * Used to make an adjustment to the yaw of the bone.
  59566. */
  59567. this.adjustYaw = 0;
  59568. /**
  59569. * Used to make an adjustment to the pitch of the bone.
  59570. */
  59571. this.adjustPitch = 0;
  59572. /**
  59573. * Used to make an adjustment to the roll of the bone.
  59574. */
  59575. this.adjustRoll = 0;
  59576. /**
  59577. * 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).
  59578. */
  59579. this.slerpAmount = 1;
  59580. this._boneQuat = BABYLON.Quaternion.Identity();
  59581. this._slerping = false;
  59582. this._firstFrameSkipped = false;
  59583. this._fowardAxis = BABYLON.Vector3.Forward();
  59584. this.mesh = mesh;
  59585. this.bone = bone;
  59586. this.target = target;
  59587. if (options) {
  59588. if (options.adjustYaw) {
  59589. this.adjustYaw = options.adjustYaw;
  59590. }
  59591. if (options.adjustPitch) {
  59592. this.adjustPitch = options.adjustPitch;
  59593. }
  59594. if (options.adjustRoll) {
  59595. this.adjustRoll = options.adjustRoll;
  59596. }
  59597. if (options.maxYaw != null) {
  59598. this.maxYaw = options.maxYaw;
  59599. }
  59600. else {
  59601. this.maxYaw = Math.PI;
  59602. }
  59603. if (options.minYaw != null) {
  59604. this.minYaw = options.minYaw;
  59605. }
  59606. else {
  59607. this.minYaw = -Math.PI;
  59608. }
  59609. if (options.maxPitch != null) {
  59610. this.maxPitch = options.maxPitch;
  59611. }
  59612. else {
  59613. this.maxPitch = Math.PI;
  59614. }
  59615. if (options.minPitch != null) {
  59616. this.minPitch = options.minPitch;
  59617. }
  59618. else {
  59619. this.minPitch = -Math.PI;
  59620. }
  59621. if (options.slerpAmount != null) {
  59622. this.slerpAmount = options.slerpAmount;
  59623. }
  59624. if (options.upAxis != null) {
  59625. this.upAxis = options.upAxis;
  59626. }
  59627. if (options.upAxisSpace != null) {
  59628. this.upAxisSpace = options.upAxisSpace;
  59629. }
  59630. if (options.yawAxis != null || options.pitchAxis != null) {
  59631. var newYawAxis = BABYLON.Axis.Y;
  59632. var newPitchAxis = BABYLON.Axis.X;
  59633. if (options.yawAxis != null) {
  59634. newYawAxis = options.yawAxis.clone();
  59635. newYawAxis.normalize();
  59636. }
  59637. if (options.pitchAxis != null) {
  59638. newPitchAxis = options.pitchAxis.clone();
  59639. newPitchAxis.normalize();
  59640. }
  59641. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  59642. this._transformYawPitch = BABYLON.Matrix.Identity();
  59643. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  59644. this._transformYawPitchInv = this._transformYawPitch.clone();
  59645. this._transformYawPitch.invert();
  59646. }
  59647. }
  59648. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  59649. this.upAxisSpace = BABYLON.Space.LOCAL;
  59650. }
  59651. }
  59652. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  59653. /**
  59654. * Get/set the minimum yaw angle that the bone can look to.
  59655. */
  59656. get: function () {
  59657. return this._minYaw;
  59658. },
  59659. set: function (value) {
  59660. this._minYaw = value;
  59661. this._minYawSin = Math.sin(value);
  59662. this._minYawCos = Math.cos(value);
  59663. if (this._maxYaw != null) {
  59664. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59665. this._yawRange = this._maxYaw - this._minYaw;
  59666. }
  59667. },
  59668. enumerable: true,
  59669. configurable: true
  59670. });
  59671. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  59672. /**
  59673. * Get/set the maximum yaw angle that the bone can look to.
  59674. */
  59675. get: function () {
  59676. return this._maxYaw;
  59677. },
  59678. set: function (value) {
  59679. this._maxYaw = value;
  59680. this._maxYawSin = Math.sin(value);
  59681. this._maxYawCos = Math.cos(value);
  59682. if (this._minYaw != null) {
  59683. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59684. this._yawRange = this._maxYaw - this._minYaw;
  59685. }
  59686. },
  59687. enumerable: true,
  59688. configurable: true
  59689. });
  59690. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  59691. /**
  59692. * Get/set the minimum pitch angle that the bone can look to.
  59693. */
  59694. get: function () {
  59695. return this._minPitch;
  59696. },
  59697. set: function (value) {
  59698. this._minPitch = value;
  59699. this._minPitchTan = Math.tan(value);
  59700. },
  59701. enumerable: true,
  59702. configurable: true
  59703. });
  59704. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  59705. /**
  59706. * Get/set the maximum pitch angle that the bone can look to.
  59707. */
  59708. get: function () {
  59709. return this._maxPitch;
  59710. },
  59711. set: function (value) {
  59712. this._maxPitch = value;
  59713. this._maxPitchTan = Math.tan(value);
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. /**
  59719. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  59720. */
  59721. BoneLookController.prototype.update = function () {
  59722. //skip the first frame when slerping so that the mesh rotation is correct
  59723. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  59724. this._firstFrameSkipped = true;
  59725. return;
  59726. }
  59727. var bone = this.bone;
  59728. var bonePos = BoneLookController._tmpVecs[0];
  59729. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  59730. var target = this.target;
  59731. var _tmpMat1 = BoneLookController._tmpMats[0];
  59732. var _tmpMat2 = BoneLookController._tmpMats[1];
  59733. var mesh = this.mesh;
  59734. var parentBone = bone.getParent();
  59735. var upAxis = BoneLookController._tmpVecs[1];
  59736. upAxis.copyFrom(this.upAxis);
  59737. if (this.upAxisSpace == BABYLON.Space.BONE) {
  59738. if (this._transformYawPitch) {
  59739. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  59740. }
  59741. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  59742. }
  59743. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  59744. mesh.getDirectionToRef(upAxis, upAxis);
  59745. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  59746. upAxis.normalize();
  59747. }
  59748. }
  59749. var checkYaw = false;
  59750. var checkPitch = false;
  59751. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  59752. checkYaw = true;
  59753. }
  59754. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  59755. checkPitch = true;
  59756. }
  59757. if (checkYaw || checkPitch) {
  59758. var spaceMat = BoneLookController._tmpMats[2];
  59759. var spaceMatInv = BoneLookController._tmpMats[3];
  59760. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  59761. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  59762. }
  59763. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  59764. spaceMat.copyFrom(mesh.getWorldMatrix());
  59765. }
  59766. else {
  59767. var forwardAxis = BoneLookController._tmpVecs[2];
  59768. forwardAxis.copyFrom(this._fowardAxis);
  59769. if (this._transformYawPitch) {
  59770. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  59771. }
  59772. if (parentBone) {
  59773. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  59774. }
  59775. else {
  59776. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  59777. }
  59778. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  59779. rightAxis.normalize();
  59780. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  59781. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  59782. }
  59783. spaceMat.invertToRef(spaceMatInv);
  59784. var xzlen;
  59785. if (checkPitch) {
  59786. var localTarget = BoneLookController._tmpVecs[3];
  59787. target.subtractToRef(bonePos, localTarget);
  59788. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  59789. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59790. var pitch = Math.atan2(localTarget.y, xzlen);
  59791. var newPitch = pitch;
  59792. if (pitch > this._maxPitch) {
  59793. localTarget.y = this._maxPitchTan * xzlen;
  59794. newPitch = this._maxPitch;
  59795. }
  59796. else if (pitch < this._minPitch) {
  59797. localTarget.y = this._minPitchTan * xzlen;
  59798. newPitch = this._minPitch;
  59799. }
  59800. if (pitch != newPitch) {
  59801. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  59802. localTarget.addInPlace(bonePos);
  59803. target = localTarget;
  59804. }
  59805. }
  59806. if (checkYaw) {
  59807. var localTarget = BoneLookController._tmpVecs[4];
  59808. target.subtractToRef(bonePos, localTarget);
  59809. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  59810. var yaw = Math.atan2(localTarget.x, localTarget.z);
  59811. var newYaw = yaw;
  59812. if (yaw > this._maxYaw || yaw < this._minYaw) {
  59813. if (xzlen == null) {
  59814. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59815. }
  59816. if (this._yawRange > Math.PI) {
  59817. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  59818. localTarget.z = this._maxYawCos * xzlen;
  59819. localTarget.x = this._maxYawSin * xzlen;
  59820. newYaw = this._maxYaw;
  59821. }
  59822. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  59823. localTarget.z = this._minYawCos * xzlen;
  59824. localTarget.x = this._minYawSin * xzlen;
  59825. newYaw = this._minYaw;
  59826. }
  59827. }
  59828. else {
  59829. if (yaw > this._maxYaw) {
  59830. localTarget.z = this._maxYawCos * xzlen;
  59831. localTarget.x = this._maxYawSin * xzlen;
  59832. newYaw = this._maxYaw;
  59833. }
  59834. else if (yaw < this._minYaw) {
  59835. localTarget.z = this._minYawCos * xzlen;
  59836. localTarget.x = this._minYawSin * xzlen;
  59837. newYaw = this._minYaw;
  59838. }
  59839. }
  59840. }
  59841. if (this._slerping && this._yawRange > Math.PI) {
  59842. //are we going to be crossing into the min/max region?
  59843. var boneFwd = BoneLookController._tmpVecs[8];
  59844. boneFwd.copyFrom(BABYLON.Axis.Z);
  59845. if (this._transformYawPitch) {
  59846. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  59847. }
  59848. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  59849. this._boneQuat.toRotationMatrix(boneRotMat);
  59850. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  59851. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  59852. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  59853. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  59854. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  59855. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  59856. if (angBtwTar > angBtwMidYaw) {
  59857. if (xzlen == null) {
  59858. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59859. }
  59860. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  59861. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  59862. if (angBtwMin < angBtwMax) {
  59863. newYaw = boneYaw + Math.PI * .75;
  59864. localTarget.z = Math.cos(newYaw) * xzlen;
  59865. localTarget.x = Math.sin(newYaw) * xzlen;
  59866. }
  59867. else {
  59868. newYaw = boneYaw - Math.PI * .75;
  59869. localTarget.z = Math.cos(newYaw) * xzlen;
  59870. localTarget.x = Math.sin(newYaw) * xzlen;
  59871. }
  59872. }
  59873. }
  59874. if (yaw != newYaw) {
  59875. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  59876. localTarget.addInPlace(bonePos);
  59877. target = localTarget;
  59878. }
  59879. }
  59880. }
  59881. var zaxis = BoneLookController._tmpVecs[5];
  59882. var xaxis = BoneLookController._tmpVecs[6];
  59883. var yaxis = BoneLookController._tmpVecs[7];
  59884. var _tmpQuat = BoneLookController._tmpQuat;
  59885. target.subtractToRef(bonePos, zaxis);
  59886. zaxis.normalize();
  59887. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  59888. xaxis.normalize();
  59889. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  59890. yaxis.normalize();
  59891. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  59892. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  59893. return;
  59894. }
  59895. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  59896. return;
  59897. }
  59898. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  59899. return;
  59900. }
  59901. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  59902. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  59903. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  59904. }
  59905. if (this.slerpAmount < 1) {
  59906. if (!this._slerping) {
  59907. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  59908. }
  59909. if (this._transformYawPitch) {
  59910. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  59911. }
  59912. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  59913. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  59914. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  59915. this._slerping = true;
  59916. }
  59917. else {
  59918. if (this._transformYawPitch) {
  59919. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  59920. }
  59921. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  59922. this._slerping = false;
  59923. }
  59924. };
  59925. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  59926. var angDiff = ang2 - ang1;
  59927. angDiff %= Math.PI * 2;
  59928. if (angDiff > Math.PI) {
  59929. angDiff -= Math.PI * 2;
  59930. }
  59931. else if (angDiff < -Math.PI) {
  59932. angDiff += Math.PI * 2;
  59933. }
  59934. return angDiff;
  59935. };
  59936. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  59937. ang1 %= (2 * Math.PI);
  59938. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  59939. ang2 %= (2 * Math.PI);
  59940. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  59941. var ab = 0;
  59942. if (ang1 < ang2) {
  59943. ab = ang2 - ang1;
  59944. }
  59945. else {
  59946. ab = ang1 - ang2;
  59947. }
  59948. if (ab > Math.PI) {
  59949. ab = Math.PI * 2 - ab;
  59950. }
  59951. return ab;
  59952. };
  59953. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  59954. ang %= (2 * Math.PI);
  59955. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  59956. ang1 %= (2 * Math.PI);
  59957. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  59958. ang2 %= (2 * Math.PI);
  59959. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  59960. if (ang1 < ang2) {
  59961. if (ang > ang1 && ang < ang2) {
  59962. return true;
  59963. }
  59964. }
  59965. else {
  59966. if (ang > ang2 && ang < ang1) {
  59967. return true;
  59968. }
  59969. }
  59970. return false;
  59971. };
  59972. 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()];
  59973. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  59974. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59975. return BoneLookController;
  59976. }());
  59977. BABYLON.BoneLookController = BoneLookController;
  59978. })(BABYLON || (BABYLON = {}));
  59979. //# sourceMappingURL=babylon.boneLookController.js.map
  59980. var BABYLON;
  59981. (function (BABYLON) {
  59982. var Skeleton = (function () {
  59983. function Skeleton(name, id, scene) {
  59984. this.name = name;
  59985. this.id = id;
  59986. this.bones = new Array();
  59987. this.needInitialSkinMatrix = false;
  59988. this._isDirty = true;
  59989. this._meshesWithPoseMatrix = new Array();
  59990. this._identity = BABYLON.Matrix.Identity();
  59991. this._ranges = {};
  59992. this._lastAbsoluteTransformsUpdateId = -1;
  59993. // Events
  59994. /**
  59995. * An event triggered before computing the skeleton's matrices
  59996. * @type {BABYLON.Observable}
  59997. */
  59998. this.onBeforeComputeObservable = new BABYLON.Observable();
  59999. this.bones = [];
  60000. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60001. scene.skeletons.push(this);
  60002. //make sure it will recalculate the matrix next time prepare is called.
  60003. this._isDirty = true;
  60004. }
  60005. // Members
  60006. Skeleton.prototype.getTransformMatrices = function (mesh) {
  60007. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  60008. return mesh._bonesTransformMatrices;
  60009. }
  60010. if (!this._transformMatrices) {
  60011. this.prepare();
  60012. }
  60013. return this._transformMatrices;
  60014. };
  60015. Skeleton.prototype.getScene = function () {
  60016. return this._scene;
  60017. };
  60018. // Methods
  60019. /**
  60020. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  60021. */
  60022. Skeleton.prototype.toString = function (fullDetails) {
  60023. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  60024. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  60025. if (fullDetails) {
  60026. ret += ", Ranges: {";
  60027. var first = true;
  60028. for (var name_1 in this._ranges) {
  60029. if (first) {
  60030. ret += ", ";
  60031. first = false;
  60032. }
  60033. ret += name_1;
  60034. }
  60035. ret += "}";
  60036. }
  60037. return ret;
  60038. };
  60039. /**
  60040. * Get bone's index searching by name
  60041. * @param {string} name is bone's name to search for
  60042. * @return {number} Indice of the bone. Returns -1 if not found
  60043. */
  60044. Skeleton.prototype.getBoneIndexByName = function (name) {
  60045. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  60046. if (this.bones[boneIndex].name === name) {
  60047. return boneIndex;
  60048. }
  60049. }
  60050. return -1;
  60051. };
  60052. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  60053. // check name not already in use
  60054. if (!this._ranges[name]) {
  60055. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  60056. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60057. if (this.bones[i].animations[0]) {
  60058. this.bones[i].animations[0].createRange(name, from, to);
  60059. }
  60060. }
  60061. }
  60062. };
  60063. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  60064. if (deleteFrames === void 0) { deleteFrames = true; }
  60065. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60066. if (this.bones[i].animations[0]) {
  60067. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  60068. }
  60069. }
  60070. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  60071. };
  60072. Skeleton.prototype.getAnimationRange = function (name) {
  60073. return this._ranges[name];
  60074. };
  60075. /**
  60076. * Returns as an Array, all AnimationRanges defined on this skeleton
  60077. */
  60078. Skeleton.prototype.getAnimationRanges = function () {
  60079. var animationRanges = [];
  60080. var name;
  60081. var i = 0;
  60082. for (name in this._ranges) {
  60083. animationRanges[i] = this._ranges[name];
  60084. i++;
  60085. }
  60086. return animationRanges;
  60087. };
  60088. /**
  60089. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  60090. */
  60091. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  60092. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60093. if (this._ranges[name] || !source.getAnimationRange(name)) {
  60094. return false;
  60095. }
  60096. var ret = true;
  60097. var frameOffset = this._getHighestAnimationFrame() + 1;
  60098. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  60099. var boneDict = {};
  60100. var sourceBones = source.bones;
  60101. var nBones;
  60102. var i;
  60103. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  60104. boneDict[sourceBones[i].name] = sourceBones[i];
  60105. }
  60106. if (this.bones.length !== sourceBones.length) {
  60107. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  60108. ret = false;
  60109. }
  60110. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  60111. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  60112. var boneName = this.bones[i].name;
  60113. var sourceBone = boneDict[boneName];
  60114. if (sourceBone) {
  60115. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  60116. }
  60117. else {
  60118. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  60119. ret = false;
  60120. }
  60121. }
  60122. // do not call createAnimationRange(), since it also is done to bones, which was already done
  60123. var range = source.getAnimationRange(name);
  60124. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  60125. return ret;
  60126. };
  60127. Skeleton.prototype.returnToRest = function () {
  60128. for (var index = 0; index < this.bones.length; index++) {
  60129. this.bones[index].returnToRest();
  60130. }
  60131. };
  60132. Skeleton.prototype._getHighestAnimationFrame = function () {
  60133. var ret = 0;
  60134. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60135. if (this.bones[i].animations[0]) {
  60136. var highest = this.bones[i].animations[0].getHighestFrame();
  60137. if (ret < highest) {
  60138. ret = highest;
  60139. }
  60140. }
  60141. }
  60142. return ret;
  60143. };
  60144. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  60145. var range = this.getAnimationRange(name);
  60146. if (!range) {
  60147. return null;
  60148. }
  60149. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  60150. };
  60151. Skeleton.prototype._markAsDirty = function () {
  60152. this._isDirty = true;
  60153. };
  60154. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  60155. this._meshesWithPoseMatrix.push(mesh);
  60156. };
  60157. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  60158. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  60159. if (index > -1) {
  60160. this._meshesWithPoseMatrix.splice(index, 1);
  60161. }
  60162. };
  60163. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  60164. this.onBeforeComputeObservable.notifyObservers(this);
  60165. for (var index = 0; index < this.bones.length; index++) {
  60166. var bone = this.bones[index];
  60167. var parentBone = bone.getParent();
  60168. if (parentBone) {
  60169. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  60170. }
  60171. else {
  60172. if (initialSkinMatrix) {
  60173. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  60174. }
  60175. else {
  60176. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  60177. }
  60178. }
  60179. if (bone._index !== -1) {
  60180. var mappedIndex = bone._index === undefined ? index : bone._index;
  60181. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  60182. }
  60183. }
  60184. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  60185. };
  60186. Skeleton.prototype.prepare = function () {
  60187. if (!this._isDirty) {
  60188. return;
  60189. }
  60190. if (this.needInitialSkinMatrix) {
  60191. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  60192. var mesh = this._meshesWithPoseMatrix[index];
  60193. var poseMatrix = mesh.getPoseMatrix();
  60194. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  60195. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60196. }
  60197. if (this._synchronizedWithMesh !== mesh) {
  60198. this._synchronizedWithMesh = mesh;
  60199. // Prepare bones
  60200. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  60201. var bone = this.bones[boneIndex];
  60202. if (!bone.getParent()) {
  60203. var matrix = bone.getBaseMatrix();
  60204. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  60205. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  60206. }
  60207. }
  60208. }
  60209. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  60210. }
  60211. }
  60212. else {
  60213. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  60214. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60215. }
  60216. this._computeTransformMatrices(this._transformMatrices, null);
  60217. }
  60218. this._isDirty = false;
  60219. this._scene._activeBones.addCount(this.bones.length, false);
  60220. };
  60221. Skeleton.prototype.getAnimatables = function () {
  60222. if (!this._animatables || this._animatables.length !== this.bones.length) {
  60223. this._animatables = [];
  60224. for (var index = 0; index < this.bones.length; index++) {
  60225. this._animatables.push(this.bones[index]);
  60226. }
  60227. }
  60228. return this._animatables;
  60229. };
  60230. Skeleton.prototype.clone = function (name, id) {
  60231. var result = new Skeleton(name, id || name, this._scene);
  60232. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60233. for (var index = 0; index < this.bones.length; index++) {
  60234. var source = this.bones[index];
  60235. var parentBone = null;
  60236. if (source.getParent()) {
  60237. var parentIndex = this.bones.indexOf(source.getParent());
  60238. parentBone = result.bones[parentIndex];
  60239. }
  60240. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  60241. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  60242. }
  60243. if (this._ranges) {
  60244. result._ranges = {};
  60245. for (var rangeName in this._ranges) {
  60246. result._ranges[rangeName] = this._ranges[rangeName].clone();
  60247. }
  60248. }
  60249. this._isDirty = true;
  60250. return result;
  60251. };
  60252. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  60253. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  60254. this.bones.forEach(function (bone) {
  60255. bone.animations.forEach(function (animation) {
  60256. animation.enableBlending = true;
  60257. animation.blendingSpeed = blendingSpeed;
  60258. });
  60259. });
  60260. };
  60261. Skeleton.prototype.dispose = function () {
  60262. this._meshesWithPoseMatrix = [];
  60263. // Animations
  60264. this.getScene().stopAnimation(this);
  60265. // Remove from scene
  60266. this.getScene().removeSkeleton(this);
  60267. };
  60268. Skeleton.prototype.serialize = function () {
  60269. var serializationObject = {};
  60270. serializationObject.name = this.name;
  60271. serializationObject.id = this.id;
  60272. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  60273. serializationObject.bones = [];
  60274. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60275. for (var index = 0; index < this.bones.length; index++) {
  60276. var bone = this.bones[index];
  60277. var serializedBone = {
  60278. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  60279. name: bone.name,
  60280. matrix: bone.getBaseMatrix().toArray(),
  60281. rest: bone.getRestPose().toArray()
  60282. };
  60283. serializationObject.bones.push(serializedBone);
  60284. if (bone.length) {
  60285. serializedBone.length = bone.length;
  60286. }
  60287. if (bone.animations && bone.animations.length > 0) {
  60288. serializedBone.animation = bone.animations[0].serialize();
  60289. }
  60290. serializationObject.ranges = [];
  60291. for (var name in this._ranges) {
  60292. var range = {};
  60293. range.name = name;
  60294. range.from = this._ranges[name].from;
  60295. range.to = this._ranges[name].to;
  60296. serializationObject.ranges.push(range);
  60297. }
  60298. }
  60299. return serializationObject;
  60300. };
  60301. Skeleton.Parse = function (parsedSkeleton, scene) {
  60302. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  60303. if (parsedSkeleton.dimensionsAtRest) {
  60304. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  60305. }
  60306. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  60307. var index;
  60308. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  60309. var parsedBone = parsedSkeleton.bones[index];
  60310. var parentBone = null;
  60311. if (parsedBone.parentBoneIndex > -1) {
  60312. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  60313. }
  60314. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  60315. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  60316. if (parsedBone.length) {
  60317. bone.length = parsedBone.length;
  60318. }
  60319. if (parsedBone.animation) {
  60320. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  60321. }
  60322. }
  60323. // placed after bones, so createAnimationRange can cascade down
  60324. if (parsedSkeleton.ranges) {
  60325. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  60326. var data = parsedSkeleton.ranges[index];
  60327. skeleton.createAnimationRange(data.name, data.from, data.to);
  60328. }
  60329. }
  60330. return skeleton;
  60331. };
  60332. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  60333. if (forceUpdate === void 0) { forceUpdate = false; }
  60334. var renderId = this._scene.getRenderId();
  60335. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  60336. this.bones[0].computeAbsoluteTransforms();
  60337. this._lastAbsoluteTransformsUpdateId = renderId;
  60338. }
  60339. };
  60340. Skeleton.prototype.getPoseMatrix = function () {
  60341. var poseMatrix;
  60342. if (this._meshesWithPoseMatrix.length > 0) {
  60343. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  60344. }
  60345. return poseMatrix;
  60346. };
  60347. Skeleton.prototype.sortBones = function () {
  60348. var bones = new Array();
  60349. var visited = new Array(this.bones.length);
  60350. for (var index = 0; index < this.bones.length; index++) {
  60351. this._sortBones(index, bones, visited);
  60352. }
  60353. this.bones = bones;
  60354. };
  60355. Skeleton.prototype._sortBones = function (index, bones, visited) {
  60356. if (visited[index]) {
  60357. return;
  60358. }
  60359. visited[index] = true;
  60360. var bone = this.bones[index];
  60361. if (bone._index === undefined) {
  60362. bone._index = index;
  60363. }
  60364. var parentBone = bone.getParent();
  60365. if (parentBone) {
  60366. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  60367. }
  60368. bones.push(bone);
  60369. };
  60370. return Skeleton;
  60371. }());
  60372. BABYLON.Skeleton = Skeleton;
  60373. })(BABYLON || (BABYLON = {}));
  60374. //# sourceMappingURL=babylon.skeleton.js.map
  60375. var BABYLON;
  60376. (function (BABYLON) {
  60377. var SphericalPolynomial = (function () {
  60378. function SphericalPolynomial() {
  60379. this.x = BABYLON.Vector3.Zero();
  60380. this.y = BABYLON.Vector3.Zero();
  60381. this.z = BABYLON.Vector3.Zero();
  60382. this.xx = BABYLON.Vector3.Zero();
  60383. this.yy = BABYLON.Vector3.Zero();
  60384. this.zz = BABYLON.Vector3.Zero();
  60385. this.xy = BABYLON.Vector3.Zero();
  60386. this.yz = BABYLON.Vector3.Zero();
  60387. this.zx = BABYLON.Vector3.Zero();
  60388. }
  60389. SphericalPolynomial.prototype.addAmbient = function (color) {
  60390. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60391. this.xx = this.xx.add(colorVector);
  60392. this.yy = this.yy.add(colorVector);
  60393. this.zz = this.zz.add(colorVector);
  60394. };
  60395. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  60396. var result = new SphericalPolynomial();
  60397. result.x = harmonics.L11.scale(1.02333);
  60398. result.y = harmonics.L1_1.scale(1.02333);
  60399. result.z = harmonics.L10.scale(1.02333);
  60400. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  60401. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  60402. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  60403. result.yz = harmonics.L2_1.scale(0.858086);
  60404. result.zx = harmonics.L21.scale(0.858086);
  60405. result.xy = harmonics.L2_2.scale(0.858086);
  60406. result.scale(1.0 / Math.PI);
  60407. return result;
  60408. };
  60409. SphericalPolynomial.prototype.scale = function (scale) {
  60410. this.x = this.x.scale(scale);
  60411. this.y = this.y.scale(scale);
  60412. this.z = this.z.scale(scale);
  60413. this.xx = this.xx.scale(scale);
  60414. this.yy = this.yy.scale(scale);
  60415. this.zz = this.zz.scale(scale);
  60416. this.yz = this.yz.scale(scale);
  60417. this.zx = this.zx.scale(scale);
  60418. this.xy = this.xy.scale(scale);
  60419. };
  60420. return SphericalPolynomial;
  60421. }());
  60422. BABYLON.SphericalPolynomial = SphericalPolynomial;
  60423. var SphericalHarmonics = (function () {
  60424. function SphericalHarmonics() {
  60425. this.L00 = BABYLON.Vector3.Zero();
  60426. this.L1_1 = BABYLON.Vector3.Zero();
  60427. this.L10 = BABYLON.Vector3.Zero();
  60428. this.L11 = BABYLON.Vector3.Zero();
  60429. this.L2_2 = BABYLON.Vector3.Zero();
  60430. this.L2_1 = BABYLON.Vector3.Zero();
  60431. this.L20 = BABYLON.Vector3.Zero();
  60432. this.L21 = BABYLON.Vector3.Zero();
  60433. this.L22 = BABYLON.Vector3.Zero();
  60434. }
  60435. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  60436. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60437. var c = colorVector.scale(deltaSolidAngle);
  60438. this.L00 = this.L00.add(c.scale(0.282095));
  60439. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  60440. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  60441. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  60442. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  60443. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  60444. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  60445. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  60446. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  60447. };
  60448. SphericalHarmonics.prototype.scale = function (scale) {
  60449. this.L00 = this.L00.scale(scale);
  60450. this.L1_1 = this.L1_1.scale(scale);
  60451. this.L10 = this.L10.scale(scale);
  60452. this.L11 = this.L11.scale(scale);
  60453. this.L2_2 = this.L2_2.scale(scale);
  60454. this.L2_1 = this.L2_1.scale(scale);
  60455. this.L20 = this.L20.scale(scale);
  60456. this.L21 = this.L21.scale(scale);
  60457. this.L22 = this.L22.scale(scale);
  60458. };
  60459. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  60460. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  60461. //
  60462. // E_lm = A_l * L_lm
  60463. //
  60464. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  60465. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  60466. // the scaling factors are given in equation 9.
  60467. // Constant (Band 0)
  60468. this.L00 = this.L00.scale(3.141593);
  60469. // Linear (Band 1)
  60470. this.L1_1 = this.L1_1.scale(2.094395);
  60471. this.L10 = this.L10.scale(2.094395);
  60472. this.L11 = this.L11.scale(2.094395);
  60473. // Quadratic (Band 2)
  60474. this.L2_2 = this.L2_2.scale(0.785398);
  60475. this.L2_1 = this.L2_1.scale(0.785398);
  60476. this.L20 = this.L20.scale(0.785398);
  60477. this.L21 = this.L21.scale(0.785398);
  60478. this.L22 = this.L22.scale(0.785398);
  60479. };
  60480. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  60481. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  60482. // L = (1/pi) * E * rho
  60483. //
  60484. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  60485. this.scale(1.0 / Math.PI);
  60486. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  60487. // (The pixel shader must apply albedo after texture fetches, etc).
  60488. };
  60489. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  60490. var result = new SphericalHarmonics();
  60491. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  60492. result.L1_1 = polynomial.y.scale(0.977204);
  60493. result.L10 = polynomial.z.scale(0.977204);
  60494. result.L11 = polynomial.x.scale(0.977204);
  60495. result.L2_2 = polynomial.xy.scale(1.16538);
  60496. result.L2_1 = polynomial.yz.scale(1.16538);
  60497. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  60498. result.L21 = polynomial.zx.scale(1.16538);
  60499. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  60500. result.scale(Math.PI);
  60501. return result;
  60502. };
  60503. return SphericalHarmonics;
  60504. }());
  60505. BABYLON.SphericalHarmonics = SphericalHarmonics;
  60506. })(BABYLON || (BABYLON = {}));
  60507. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  60508. var BABYLON;
  60509. (function (BABYLON) {
  60510. var Internals;
  60511. (function (Internals) {
  60512. var FileFaceOrientation = (function () {
  60513. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  60514. this.name = name;
  60515. this.worldAxisForNormal = worldAxisForNormal;
  60516. this.worldAxisForFileX = worldAxisForFileX;
  60517. this.worldAxisForFileY = worldAxisForFileY;
  60518. }
  60519. return FileFaceOrientation;
  60520. }());
  60521. ;
  60522. /**
  60523. * Helper class dealing with the extraction of spherical polynomial dataArray
  60524. * from a cube map.
  60525. */
  60526. var CubeMapToSphericalPolynomialTools = (function () {
  60527. function CubeMapToSphericalPolynomialTools() {
  60528. }
  60529. /**
  60530. * Converts a texture to the according Spherical Polynomial data.
  60531. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60532. *
  60533. * @param texture The texture to extract the information from.
  60534. * @return The Spherical Polynomial data.
  60535. */
  60536. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  60537. if (!texture.isCube) {
  60538. // Only supports cube Textures currently.
  60539. return null;
  60540. }
  60541. var size = texture.getSize().width;
  60542. var right = texture.readPixels(0);
  60543. var left = texture.readPixels(1);
  60544. var up;
  60545. var down;
  60546. if (texture.isRenderTarget) {
  60547. up = texture.readPixels(3);
  60548. down = texture.readPixels(2);
  60549. }
  60550. else {
  60551. up = texture.readPixels(2);
  60552. down = texture.readPixels(3);
  60553. }
  60554. var front = texture.readPixels(4);
  60555. var back = texture.readPixels(5);
  60556. var gammaSpace = texture.gammaSpace;
  60557. // Always read as RGBA.
  60558. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  60559. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60560. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60561. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60562. }
  60563. var cubeInfo = {
  60564. size: size,
  60565. right: right,
  60566. left: left,
  60567. up: up,
  60568. down: down,
  60569. front: front,
  60570. back: back,
  60571. format: format,
  60572. type: type,
  60573. gammaSpace: gammaSpace,
  60574. };
  60575. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  60576. };
  60577. /**
  60578. * Converts a cubemap to the according Spherical Polynomial data.
  60579. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60580. *
  60581. * @param cubeInfo The Cube map to extract the information from.
  60582. * @return The Spherical Polynomial data.
  60583. */
  60584. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  60585. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  60586. var totalSolidAngle = 0.0;
  60587. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  60588. var du = 2.0 / cubeInfo.size;
  60589. var dv = du;
  60590. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  60591. var minUV = du * 0.5 - 1.0;
  60592. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60593. var fileFace = this.FileFaces[faceIndex];
  60594. var dataArray = cubeInfo[fileFace.name];
  60595. var v = minUV;
  60596. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  60597. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  60598. // Because SP is still linear, so summation is fine in that basis.
  60599. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  60600. for (var y = 0; y < cubeInfo.size; y++) {
  60601. var u = minUV;
  60602. for (var x = 0; x < cubeInfo.size; x++) {
  60603. // World direction (not normalised)
  60604. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  60605. worldDirection.normalize();
  60606. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  60607. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  60608. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  60609. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  60610. // Handle Integer types.
  60611. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60612. r /= 255;
  60613. g /= 255;
  60614. b /= 255;
  60615. }
  60616. // Handle Gamma space textures.
  60617. if (cubeInfo.gammaSpace) {
  60618. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  60619. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  60620. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  60621. }
  60622. var color = new BABYLON.Color3(r, g, b);
  60623. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  60624. totalSolidAngle += deltaSolidAngle;
  60625. u += du;
  60626. }
  60627. v += dv;
  60628. }
  60629. }
  60630. // Solid angle for entire sphere is 4*pi
  60631. var sphereSolidAngle = 4.0 * Math.PI;
  60632. // Adjust the solid angle to allow for how many faces we processed.
  60633. var facesProcessed = 6.0;
  60634. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  60635. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  60636. // This is needed because the numerical integration over the cube uses a
  60637. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  60638. // and also to compensate for accumulative error due to float precision in the summation.
  60639. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  60640. sphericalHarmonics.scale(correctionFactor);
  60641. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  60642. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  60643. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  60644. };
  60645. CubeMapToSphericalPolynomialTools.FileFaces = [
  60646. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  60647. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  60648. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  60649. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  60650. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  60651. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  60652. ];
  60653. return CubeMapToSphericalPolynomialTools;
  60654. }());
  60655. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  60656. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60657. })(BABYLON || (BABYLON = {}));
  60658. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  60659. var BABYLON;
  60660. (function (BABYLON) {
  60661. var Internals;
  60662. (function (Internals) {
  60663. /**
  60664. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  60665. */
  60666. var PanoramaToCubeMapTools = (function () {
  60667. function PanoramaToCubeMapTools() {
  60668. }
  60669. /**
  60670. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  60671. *
  60672. * @param float32Array The source data.
  60673. * @param inputWidth The width of the input panorama.
  60674. * @param inputhHeight The height of the input panorama.
  60675. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  60676. * @return The cubemap data
  60677. */
  60678. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  60679. if (!float32Array) {
  60680. throw "ConvertPanoramaToCubemap: input cannot be null";
  60681. }
  60682. if (float32Array.length != inputWidth * inputHeight * 3) {
  60683. throw "ConvertPanoramaToCubemap: input size is wrong";
  60684. }
  60685. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  60686. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  60687. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  60688. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  60689. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  60690. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  60691. return {
  60692. front: textureFront,
  60693. back: textureBack,
  60694. left: textureLeft,
  60695. right: textureRight,
  60696. up: textureUp,
  60697. down: textureDown,
  60698. size: size,
  60699. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  60700. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  60701. gammaSpace: false,
  60702. };
  60703. };
  60704. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  60705. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  60706. var textureArray = new Float32Array(buffer);
  60707. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  60708. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  60709. var dy = 1 / texSize;
  60710. var fy = 0;
  60711. for (var y = 0; y < texSize; y++) {
  60712. var xv1 = faceData[0];
  60713. var xv2 = faceData[2];
  60714. for (var x = 0; x < texSize; x++) {
  60715. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  60716. v.normalize();
  60717. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  60718. // 3 channels per pixels
  60719. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  60720. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  60721. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  60722. xv1 = xv1.add(rotDX1);
  60723. xv2 = xv2.add(rotDX2);
  60724. }
  60725. fy += dy;
  60726. }
  60727. return textureArray;
  60728. };
  60729. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  60730. var theta = Math.atan2(vDir.z, vDir.x);
  60731. var phi = Math.acos(vDir.y);
  60732. while (theta < -Math.PI)
  60733. theta += 2 * Math.PI;
  60734. while (theta > Math.PI)
  60735. theta -= 2 * Math.PI;
  60736. var dx = theta / Math.PI;
  60737. var dy = phi / Math.PI;
  60738. // recenter.
  60739. dx = dx * 0.5 + 0.5;
  60740. var px = Math.round(dx * inputWidth);
  60741. if (px < 0)
  60742. px = 0;
  60743. else if (px >= inputWidth)
  60744. px = inputWidth - 1;
  60745. var py = Math.round(dy * inputHeight);
  60746. if (py < 0)
  60747. py = 0;
  60748. else if (py >= inputHeight)
  60749. py = inputHeight - 1;
  60750. var inputY = (inputHeight - py - 1);
  60751. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  60752. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  60753. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  60754. return {
  60755. r: r,
  60756. g: g,
  60757. b: b
  60758. };
  60759. };
  60760. PanoramaToCubeMapTools.FACE_FRONT = [
  60761. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60762. new BABYLON.Vector3(1.0, -1.0, -1.0),
  60763. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  60764. new BABYLON.Vector3(1.0, 1.0, -1.0)
  60765. ];
  60766. PanoramaToCubeMapTools.FACE_BACK = [
  60767. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60768. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60769. new BABYLON.Vector3(1.0, 1.0, 1.0),
  60770. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  60771. ];
  60772. PanoramaToCubeMapTools.FACE_RIGHT = [
  60773. new BABYLON.Vector3(1.0, -1.0, -1.0),
  60774. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60775. new BABYLON.Vector3(1.0, 1.0, -1.0),
  60776. new BABYLON.Vector3(1.0, 1.0, 1.0)
  60777. ];
  60778. PanoramaToCubeMapTools.FACE_LEFT = [
  60779. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60780. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60781. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  60782. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  60783. ];
  60784. PanoramaToCubeMapTools.FACE_DOWN = [
  60785. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  60786. new BABYLON.Vector3(1.0, 1.0, -1.0),
  60787. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  60788. new BABYLON.Vector3(1.0, 1.0, 1.0)
  60789. ];
  60790. PanoramaToCubeMapTools.FACE_UP = [
  60791. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60792. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60793. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60794. new BABYLON.Vector3(1.0, -1.0, -1.0)
  60795. ];
  60796. return PanoramaToCubeMapTools;
  60797. }());
  60798. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  60799. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60800. })(BABYLON || (BABYLON = {}));
  60801. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  60802. var BABYLON;
  60803. (function (BABYLON) {
  60804. var Internals;
  60805. (function (Internals) {
  60806. ;
  60807. /**
  60808. * This groups tools to convert HDR texture to native colors array.
  60809. */
  60810. var HDRTools = (function () {
  60811. function HDRTools() {
  60812. }
  60813. HDRTools.Ldexp = function (mantissa, exponent) {
  60814. if (exponent > 1023) {
  60815. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  60816. }
  60817. if (exponent < -1074) {
  60818. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  60819. }
  60820. return mantissa * Math.pow(2, exponent);
  60821. };
  60822. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  60823. if (exponent > 0) {
  60824. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  60825. float32array[index + 0] = red * exponent;
  60826. float32array[index + 1] = green * exponent;
  60827. float32array[index + 2] = blue * exponent;
  60828. }
  60829. else {
  60830. float32array[index + 0] = 0;
  60831. float32array[index + 1] = 0;
  60832. float32array[index + 2] = 0;
  60833. }
  60834. };
  60835. HDRTools.readStringLine = function (uint8array, startIndex) {
  60836. var line = "";
  60837. var character = "";
  60838. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  60839. character = String.fromCharCode(uint8array[i]);
  60840. if (character == "\n") {
  60841. break;
  60842. }
  60843. line += character;
  60844. }
  60845. return line;
  60846. };
  60847. /**
  60848. * Reads header information from an RGBE texture stored in a native array.
  60849. * More information on this format are available here:
  60850. * https://en.wikipedia.org/wiki/RGBE_image_format
  60851. *
  60852. * @param uint8array The binary file stored in native array.
  60853. * @return The header information.
  60854. */
  60855. HDRTools.RGBE_ReadHeader = function (uint8array) {
  60856. var height = 0;
  60857. var width = 0;
  60858. var line = this.readStringLine(uint8array, 0);
  60859. if (line[0] != '#' || line[1] != '?') {
  60860. throw "Bad HDR Format.";
  60861. }
  60862. var endOfHeader = false;
  60863. var findFormat = false;
  60864. var lineIndex = 0;
  60865. do {
  60866. lineIndex += (line.length + 1);
  60867. line = this.readStringLine(uint8array, lineIndex);
  60868. if (line == "FORMAT=32-bit_rle_rgbe") {
  60869. findFormat = true;
  60870. }
  60871. else if (line.length == 0) {
  60872. endOfHeader = true;
  60873. }
  60874. } while (!endOfHeader);
  60875. if (!findFormat) {
  60876. throw "HDR Bad header format, unsupported FORMAT";
  60877. }
  60878. lineIndex += (line.length + 1);
  60879. line = this.readStringLine(uint8array, lineIndex);
  60880. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  60881. var match = sizeRegexp.exec(line);
  60882. // TODO. Support +Y and -X if needed.
  60883. if (match.length < 3) {
  60884. throw "HDR Bad header format, no size";
  60885. }
  60886. width = parseInt(match[2]);
  60887. height = parseInt(match[1]);
  60888. if (width < 8 || width > 0x7fff) {
  60889. throw "HDR Bad header format, unsupported size";
  60890. }
  60891. lineIndex += (line.length + 1);
  60892. return {
  60893. height: height,
  60894. width: width,
  60895. dataPosition: lineIndex
  60896. };
  60897. };
  60898. /**
  60899. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  60900. * This RGBE texture needs to store the information as a panorama.
  60901. *
  60902. * More information on this format are available here:
  60903. * https://en.wikipedia.org/wiki/RGBE_image_format
  60904. *
  60905. * @param buffer The binary file stored in an array buffer.
  60906. * @param size The expected size of the extracted cubemap.
  60907. * @return The Cube Map information.
  60908. */
  60909. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  60910. var uint8array = new Uint8Array(buffer);
  60911. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  60912. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  60913. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  60914. return cubeMapData;
  60915. };
  60916. /**
  60917. * Returns the pixels data extracted from an RGBE texture.
  60918. * This pixels will be stored left to right up to down in the R G B order in one array.
  60919. *
  60920. * More information on this format are available here:
  60921. * https://en.wikipedia.org/wiki/RGBE_image_format
  60922. *
  60923. * @param uint8array The binary file stored in an array buffer.
  60924. * @param hdrInfo The header information of the file.
  60925. * @return The pixels data in RGB right to left up to down order.
  60926. */
  60927. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  60928. // Keep for multi format supports.
  60929. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  60930. };
  60931. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  60932. var num_scanlines = hdrInfo.height;
  60933. var scanline_width = hdrInfo.width;
  60934. var a, b, c, d, count;
  60935. var dataIndex = hdrInfo.dataPosition;
  60936. var index = 0, endIndex = 0, i = 0;
  60937. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  60938. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  60939. // 3 channels of 4 bytes per pixel in float.
  60940. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  60941. var resultArray = new Float32Array(resultBuffer);
  60942. // read in each successive scanline
  60943. while (num_scanlines > 0) {
  60944. a = uint8array[dataIndex++];
  60945. b = uint8array[dataIndex++];
  60946. c = uint8array[dataIndex++];
  60947. d = uint8array[dataIndex++];
  60948. if (a != 2 || b != 2 || (c & 0x80)) {
  60949. // this file is not run length encoded
  60950. throw "HDR Bad header format, not RLE";
  60951. }
  60952. if (((c << 8) | d) != scanline_width) {
  60953. throw "HDR Bad header format, wrong scan line width";
  60954. }
  60955. index = 0;
  60956. // read each of the four channels for the scanline into the buffer
  60957. for (i = 0; i < 4; i++) {
  60958. endIndex = (i + 1) * scanline_width;
  60959. while (index < endIndex) {
  60960. a = uint8array[dataIndex++];
  60961. b = uint8array[dataIndex++];
  60962. if (a > 128) {
  60963. // a run of the same value
  60964. count = a - 128;
  60965. if ((count == 0) || (count > endIndex - index)) {
  60966. throw "HDR Bad Format, bad scanline data (run)";
  60967. }
  60968. while (count-- > 0) {
  60969. scanLineArray[index++] = b;
  60970. }
  60971. }
  60972. else {
  60973. // a non-run
  60974. count = a;
  60975. if ((count == 0) || (count > endIndex - index)) {
  60976. throw "HDR Bad Format, bad scanline data (non-run)";
  60977. }
  60978. scanLineArray[index++] = b;
  60979. if (--count > 0) {
  60980. for (var j = 0; j < count; j++) {
  60981. scanLineArray[index++] = uint8array[dataIndex++];
  60982. }
  60983. }
  60984. }
  60985. }
  60986. }
  60987. // now convert data from buffer into floats
  60988. for (i = 0; i < scanline_width; i++) {
  60989. a = scanLineArray[i];
  60990. b = scanLineArray[i + scanline_width];
  60991. c = scanLineArray[i + 2 * scanline_width];
  60992. d = scanLineArray[i + 3 * scanline_width];
  60993. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  60994. }
  60995. num_scanlines--;
  60996. }
  60997. return resultArray;
  60998. };
  60999. return HDRTools;
  61000. }());
  61001. Internals.HDRTools = HDRTools;
  61002. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61003. })(BABYLON || (BABYLON = {}));
  61004. //# sourceMappingURL=babylon.hdr.js.map
  61005. var BABYLON;
  61006. (function (BABYLON) {
  61007. /**
  61008. * This represents a texture coming from an HDR input.
  61009. *
  61010. * The only supported format is currently panorama picture stored in RGBE format.
  61011. * Example of such files can be found on HDRLib: http://hdrlib.com/
  61012. */
  61013. var HDRCubeTexture = (function (_super) {
  61014. __extends(HDRCubeTexture, _super);
  61015. /**
  61016. * Instantiates an HDRTexture from the following parameters.
  61017. *
  61018. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  61019. * @param scene The scene the texture will be used in
  61020. * @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.
  61021. * @param noMipmap Forces to not generate the mipmap if true
  61022. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  61023. * @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)
  61024. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  61025. */
  61026. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  61027. if (noMipmap === void 0) { noMipmap = false; }
  61028. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61029. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61030. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61031. if (onLoad === void 0) { onLoad = null; }
  61032. if (onError === void 0) { onError = null; }
  61033. var _this = _super.call(this, scene) || this;
  61034. _this._useInGammaSpace = false;
  61035. _this._generateHarmonics = true;
  61036. _this._isBABYLONPreprocessed = false;
  61037. _this._onLoad = null;
  61038. _this._onError = null;
  61039. /**
  61040. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  61041. */
  61042. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61043. /**
  61044. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  61045. * This is usefull at run time to apply the good shader.
  61046. */
  61047. _this.isPMREM = false;
  61048. _this._isBlocking = true;
  61049. if (!url) {
  61050. return _this;
  61051. }
  61052. _this.name = url;
  61053. _this.url = url;
  61054. _this.hasAlpha = false;
  61055. _this.isCube = true;
  61056. _this._textureMatrix = BABYLON.Matrix.Identity();
  61057. _this._onLoad = onLoad;
  61058. _this._onError = onError;
  61059. _this.gammaSpace = false;
  61060. if (size) {
  61061. _this._isBABYLONPreprocessed = false;
  61062. _this._noMipmap = noMipmap;
  61063. _this._size = size;
  61064. _this._useInGammaSpace = useInGammaSpace;
  61065. _this._usePMREMGenerator = usePMREMGenerator &&
  61066. scene.getEngine().getCaps().textureLOD &&
  61067. _this.getScene().getEngine().getCaps().textureFloat &&
  61068. !_this._useInGammaSpace;
  61069. }
  61070. else {
  61071. _this._isBABYLONPreprocessed = true;
  61072. _this._noMipmap = false;
  61073. _this._useInGammaSpace = false;
  61074. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  61075. _this.getScene().getEngine().getCaps().textureFloat &&
  61076. !_this._useInGammaSpace;
  61077. }
  61078. _this.isPMREM = _this._usePMREMGenerator;
  61079. _this._texture = _this._getFromCache(url, _this._noMipmap);
  61080. if (!_this._texture) {
  61081. if (!scene.useDelayedTextureLoading) {
  61082. _this.loadTexture();
  61083. }
  61084. else {
  61085. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61086. }
  61087. }
  61088. return _this;
  61089. }
  61090. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  61091. /**
  61092. * Gets wether or not the texture is blocking during loading.
  61093. */
  61094. get: function () {
  61095. return this._isBlocking;
  61096. },
  61097. /**
  61098. * Sets wether or not the texture is blocking during loading.
  61099. */
  61100. set: function (value) {
  61101. this._isBlocking = value;
  61102. },
  61103. enumerable: true,
  61104. configurable: true
  61105. });
  61106. /**
  61107. * Occurs when the file is a preprocessed .babylon.hdr file.
  61108. */
  61109. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  61110. var _this = this;
  61111. var mipLevels = 0;
  61112. var floatArrayView = null;
  61113. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  61114. var mips = new Array();
  61115. var startIndex = 30;
  61116. for (var level = 0; level < mipLevels; level++) {
  61117. mips.push([]);
  61118. // Fill each pixel of the mip level.
  61119. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  61120. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61121. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  61122. mips[level].push(faceData);
  61123. startIndex += faceSize;
  61124. }
  61125. }
  61126. return mips;
  61127. } : null;
  61128. var callback = function (buffer) {
  61129. // Create Native Array Views
  61130. var intArrayView = new Int32Array(buffer);
  61131. floatArrayView = new Float32Array(buffer);
  61132. // Fill header.
  61133. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  61134. _this._size = intArrayView[1]; // CubeMap max mip face size.
  61135. // Update Texture Information.
  61136. _this._texture.updateSize(_this._size, _this._size);
  61137. // Fill polynomial information.
  61138. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  61139. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  61140. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  61141. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  61142. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  61143. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  61144. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  61145. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  61146. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  61147. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  61148. _this.sphericalPolynomial = sphericalPolynomial;
  61149. // Fill pixel data.
  61150. mipLevels = intArrayView[29]; // Number of mip levels.
  61151. var startIndex = 30;
  61152. var data = [];
  61153. var faceSize = Math.pow(_this._size, 2) * 3;
  61154. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61155. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  61156. startIndex += faceSize;
  61157. }
  61158. var results = [];
  61159. var byteArray = null;
  61160. // Push each faces.
  61161. for (var k = 0; k < 6; k++) {
  61162. var dataFace = null;
  61163. // To be deprecated.
  61164. if (version === 1) {
  61165. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  61166. dataFace = data[j];
  61167. }
  61168. // If special cases.
  61169. if (!mipmapGenerator) {
  61170. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61171. // 3 channels of 1 bytes per pixel in bytes.
  61172. var byteBuffer = new ArrayBuffer(faceSize);
  61173. byteArray = new Uint8Array(byteBuffer);
  61174. }
  61175. for (var i = 0; i < _this._size * _this._size; i++) {
  61176. // Put in gamma space if requested.
  61177. if (_this._useInGammaSpace) {
  61178. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61179. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61180. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61181. }
  61182. // Convert to int texture for fallback.
  61183. if (byteArray) {
  61184. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61185. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61186. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61187. // May use luminance instead if the result is not accurate.
  61188. var max = Math.max(Math.max(r, g), b);
  61189. if (max > 255) {
  61190. var scale = 255 / max;
  61191. r *= scale;
  61192. g *= scale;
  61193. b *= scale;
  61194. }
  61195. byteArray[(i * 3) + 0] = r;
  61196. byteArray[(i * 3) + 1] = g;
  61197. byteArray[(i * 3) + 2] = b;
  61198. }
  61199. }
  61200. }
  61201. // Fill the array accordingly.
  61202. if (byteArray) {
  61203. results.push(byteArray);
  61204. }
  61205. else {
  61206. results.push(dataFace);
  61207. }
  61208. }
  61209. return results;
  61210. };
  61211. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  61212. };
  61213. /**
  61214. * Occurs when the file is raw .hdr file.
  61215. */
  61216. HDRCubeTexture.prototype.loadHDRTexture = function () {
  61217. var _this = this;
  61218. var callback = function (buffer) {
  61219. // Extract the raw linear data.
  61220. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  61221. // Generate harmonics if needed.
  61222. if (_this._generateHarmonics) {
  61223. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  61224. _this.sphericalPolynomial = sphericalPolynomial;
  61225. }
  61226. var results = [];
  61227. var byteArray = null;
  61228. // Push each faces.
  61229. for (var j = 0; j < 6; j++) {
  61230. // Create uintarray fallback.
  61231. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61232. // 3 channels of 1 bytes per pixel in bytes.
  61233. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  61234. byteArray = new Uint8Array(byteBuffer);
  61235. }
  61236. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  61237. // If special cases.
  61238. if (_this._useInGammaSpace || byteArray) {
  61239. for (var i = 0; i < _this._size * _this._size; i++) {
  61240. // Put in gamma space if requested.
  61241. if (_this._useInGammaSpace) {
  61242. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61243. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61244. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61245. }
  61246. // Convert to int texture for fallback.
  61247. if (byteArray) {
  61248. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61249. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61250. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61251. // May use luminance instead if the result is not accurate.
  61252. var max = Math.max(Math.max(r, g), b);
  61253. if (max > 255) {
  61254. var scale = 255 / max;
  61255. r *= scale;
  61256. g *= scale;
  61257. b *= scale;
  61258. }
  61259. byteArray[(i * 3) + 0] = r;
  61260. byteArray[(i * 3) + 1] = g;
  61261. byteArray[(i * 3) + 2] = b;
  61262. }
  61263. }
  61264. }
  61265. if (byteArray) {
  61266. results.push(byteArray);
  61267. }
  61268. else {
  61269. results.push(dataFace);
  61270. }
  61271. }
  61272. return results;
  61273. };
  61274. var mipmapGenerator = null;
  61275. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  61276. // if (!this._noMipmap &&
  61277. // this._usePMREMGenerator) {
  61278. // mipmapGenerator = (data: ArrayBufferView[]) => {
  61279. // // Custom setup of the generator matching with the PBR shader values.
  61280. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  61281. // this._size,
  61282. // this._size,
  61283. // 0,
  61284. // 3,
  61285. // this.getScene().getEngine().getCaps().textureFloat,
  61286. // 2048,
  61287. // 0.25,
  61288. // false,
  61289. // true);
  61290. // return generator.filterCubeMap();
  61291. // };
  61292. // }
  61293. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  61294. };
  61295. /**
  61296. * Starts the loading process of the texture.
  61297. */
  61298. HDRCubeTexture.prototype.loadTexture = function () {
  61299. if (this._isBABYLONPreprocessed) {
  61300. this.loadBabylonTexture();
  61301. }
  61302. else {
  61303. this.loadHDRTexture();
  61304. }
  61305. };
  61306. HDRCubeTexture.prototype.clone = function () {
  61307. var size = this._isBABYLONPreprocessed ? null : this._size;
  61308. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  61309. // Base texture
  61310. newTexture.level = this.level;
  61311. newTexture.wrapU = this.wrapU;
  61312. newTexture.wrapV = this.wrapV;
  61313. newTexture.coordinatesIndex = this.coordinatesIndex;
  61314. newTexture.coordinatesMode = this.coordinatesMode;
  61315. return newTexture;
  61316. };
  61317. // Methods
  61318. HDRCubeTexture.prototype.delayLoad = function () {
  61319. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61320. return;
  61321. }
  61322. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61323. this._texture = this._getFromCache(this.url, this._noMipmap);
  61324. if (!this._texture) {
  61325. this.loadTexture();
  61326. }
  61327. };
  61328. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  61329. return this._textureMatrix;
  61330. };
  61331. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61332. this._textureMatrix = value;
  61333. };
  61334. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61335. var texture = null;
  61336. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61337. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  61338. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  61339. texture.name = parsedTexture.name;
  61340. texture.hasAlpha = parsedTexture.hasAlpha;
  61341. texture.level = parsedTexture.level;
  61342. texture.coordinatesMode = parsedTexture.coordinatesMode;
  61343. texture.isBlocking = parsedTexture.isBlocking;
  61344. }
  61345. return texture;
  61346. };
  61347. HDRCubeTexture.prototype.serialize = function () {
  61348. if (!this.name) {
  61349. return null;
  61350. }
  61351. var serializationObject = {};
  61352. serializationObject.name = this.name;
  61353. serializationObject.hasAlpha = this.hasAlpha;
  61354. serializationObject.isCube = true;
  61355. serializationObject.level = this.level;
  61356. serializationObject.size = this._size;
  61357. serializationObject.coordinatesMode = this.coordinatesMode;
  61358. serializationObject.useInGammaSpace = this._useInGammaSpace;
  61359. serializationObject.generateHarmonics = this._generateHarmonics;
  61360. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  61361. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  61362. serializationObject.customType = "BABYLON.HDRCubeTexture";
  61363. serializationObject.noMipmap = this._noMipmap;
  61364. serializationObject.isBlocking = this._isBlocking;
  61365. return serializationObject;
  61366. };
  61367. /**
  61368. * Saves as a file the data contained in the texture in a binary format.
  61369. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61370. * as the spherical used in the lighting.
  61371. * @param url The HDR file url.
  61372. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61373. * @param onError Method called if any error happens during download.
  61374. * @return The packed binary data.
  61375. */
  61376. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  61377. if (onError === void 0) { onError = null; }
  61378. var callback = function (buffer) {
  61379. var data = new Blob([buffer], { type: 'application/octet-stream' });
  61380. // Returns a URL you can use as a href.
  61381. var objUrl = window.URL.createObjectURL(data);
  61382. // Simulates a link to it and click to dowload.
  61383. var a = document.createElement("a");
  61384. document.body.appendChild(a);
  61385. a.style.display = "none";
  61386. a.href = objUrl;
  61387. a.download = "envmap.babylon.hdr";
  61388. a.click();
  61389. };
  61390. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  61391. };
  61392. /**
  61393. * Serializes the data contained in the texture in a binary format.
  61394. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61395. * as the spherical used in the lighting.
  61396. * @param url The HDR file url.
  61397. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61398. * @param onError Method called if any error happens during download.
  61399. * @return The packed binary data.
  61400. */
  61401. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  61402. if (onError === void 0) { onError = null; }
  61403. // Needs the url tho create the texture.
  61404. if (!url) {
  61405. return null;
  61406. }
  61407. // Check Power of two size.
  61408. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  61409. return null;
  61410. }
  61411. // Coming Back in 3.1.
  61412. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  61413. return null;
  61414. };
  61415. HDRCubeTexture._facesMapping = [
  61416. "right",
  61417. "left",
  61418. "up",
  61419. "down",
  61420. "front",
  61421. "back"
  61422. ];
  61423. return HDRCubeTexture;
  61424. }(BABYLON.BaseTexture));
  61425. BABYLON.HDRCubeTexture = HDRCubeTexture;
  61426. })(BABYLON || (BABYLON = {}));
  61427. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  61428. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  61429. // Huge respect for a such great lib.
  61430. // Earcut license:
  61431. // Copyright (c) 2016, Mapbox
  61432. //
  61433. // Permission to use, copy, modify, and/or distribute this software for any purpose
  61434. // with or without fee is hereby granted, provided that the above copyright notice
  61435. // and this permission notice appear in all copies.
  61436. //
  61437. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  61438. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  61439. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  61440. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  61441. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  61442. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  61443. // THIS SOFTWARE.
  61444. var Earcut;
  61445. (function (Earcut) {
  61446. /**
  61447. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  61448. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  61449. * @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).
  61450. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  61451. */
  61452. function earcut(data, holeIndices, dim) {
  61453. dim = dim || 2;
  61454. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  61455. if (!outerNode)
  61456. return triangles;
  61457. var minX, minY, maxX, maxY, x, y, size;
  61458. if (hasHoles)
  61459. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  61460. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  61461. if (data.length > 80 * dim) {
  61462. minX = maxX = data[0];
  61463. minY = maxY = data[1];
  61464. for (var i = dim; i < outerLen; i += dim) {
  61465. x = data[i];
  61466. y = data[i + 1];
  61467. if (x < minX)
  61468. minX = x;
  61469. if (y < minY)
  61470. minY = y;
  61471. if (x > maxX)
  61472. maxX = x;
  61473. if (y > maxY)
  61474. maxY = y;
  61475. }
  61476. // minX, minY and size are later used to transform coords into integers for z-order calculation
  61477. size = Math.max(maxX - minX, maxY - minY);
  61478. }
  61479. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  61480. return triangles;
  61481. }
  61482. Earcut.earcut = earcut;
  61483. var Node = (function () {
  61484. function Node(i, x, y) {
  61485. this.i = i;
  61486. this.x = x;
  61487. this.y = y;
  61488. this.prev = null;
  61489. this.next = null;
  61490. this.z = null;
  61491. this.prevZ = null;
  61492. this.nextZ = null;
  61493. this.steiner = false;
  61494. }
  61495. return Node;
  61496. }());
  61497. // create a circular doubly linked list from polygon points in the specified winding order
  61498. function linkedList(data, start, end, dim, clockwise) {
  61499. var i, last;
  61500. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  61501. for (i = start; i < end; i += dim)
  61502. last = insertNode(i, data[i], data[i + 1], last);
  61503. }
  61504. else {
  61505. for (i = end - dim; i >= start; i -= dim)
  61506. last = insertNode(i, data[i], data[i + 1], last);
  61507. }
  61508. if (last && equals(last, last.next)) {
  61509. removeNode(last);
  61510. last = last.next;
  61511. }
  61512. return last;
  61513. }
  61514. // eliminate colinear or duplicate points
  61515. function filterPoints(start, end) {
  61516. if (!start)
  61517. return start;
  61518. if (!end)
  61519. end = start;
  61520. var p = start, again;
  61521. do {
  61522. again = false;
  61523. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  61524. removeNode(p);
  61525. p = end = p.prev;
  61526. if (p === p.next)
  61527. return null;
  61528. again = true;
  61529. }
  61530. else {
  61531. p = p.next;
  61532. }
  61533. } while (again || p !== end);
  61534. return end;
  61535. }
  61536. // main ear slicing loop which triangulates a polygon (given as a linked list)
  61537. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  61538. if (!ear)
  61539. return;
  61540. // interlink polygon nodes in z-order
  61541. if (!pass && size)
  61542. indexCurve(ear, minX, minY, size);
  61543. var stop = ear, prev, next;
  61544. // iterate through ears, slicing them one by one
  61545. while (ear.prev !== ear.next) {
  61546. prev = ear.prev;
  61547. next = ear.next;
  61548. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  61549. // cut off the triangle
  61550. triangles.push(prev.i / dim);
  61551. triangles.push(ear.i / dim);
  61552. triangles.push(next.i / dim);
  61553. removeNode(ear);
  61554. // skipping the next vertice leads to less sliver triangles
  61555. ear = next.next;
  61556. stop = next.next;
  61557. continue;
  61558. }
  61559. ear = next;
  61560. // if we looped through the whole remaining polygon and can't find any more ears
  61561. if (ear === stop) {
  61562. // try filtering points and slicing again
  61563. if (!pass) {
  61564. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  61565. // if this didn't work, try curing all small self-intersections locally
  61566. }
  61567. else if (pass === 1) {
  61568. ear = cureLocalIntersections(ear, triangles, dim);
  61569. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  61570. // as a last resort, try splitting the remaining polygon into two
  61571. }
  61572. else if (pass === 2) {
  61573. splitEarcut(ear, triangles, dim, minX, minY, size);
  61574. }
  61575. break;
  61576. }
  61577. }
  61578. }
  61579. // check whether a polygon node forms a valid ear with adjacent nodes
  61580. function isEar(ear) {
  61581. var a = ear.prev, b = ear, c = ear.next;
  61582. if (area(a, b, c) >= 0)
  61583. return false; // reflex, can't be an ear
  61584. // now make sure we don't have other points inside the potential ear
  61585. var p = ear.next.next;
  61586. while (p !== ear.prev) {
  61587. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61588. area(p.prev, p, p.next) >= 0)
  61589. return false;
  61590. p = p.next;
  61591. }
  61592. return true;
  61593. }
  61594. function isEarHashed(ear, minX, minY, size) {
  61595. var a = ear.prev, b = ear, c = ear.next;
  61596. if (area(a, b, c) >= 0)
  61597. return false; // reflex, can't be an ear
  61598. // triangle bbox; min & max are calculated like this for speed
  61599. 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);
  61600. // z-order range for the current triangle bbox;
  61601. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  61602. // first look for points inside the triangle in increasing z-order
  61603. var p = ear.nextZ;
  61604. while (p && p.z <= maxZ) {
  61605. if (p !== ear.prev &&
  61606. p !== ear.next &&
  61607. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61608. area(p.prev, p, p.next) >= 0)
  61609. return false;
  61610. p = p.nextZ;
  61611. }
  61612. // then look for points in decreasing z-order
  61613. p = ear.prevZ;
  61614. while (p && p.z >= minZ) {
  61615. if (p !== ear.prev &&
  61616. p !== ear.next &&
  61617. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61618. area(p.prev, p, p.next) >= 0)
  61619. return false;
  61620. p = p.prevZ;
  61621. }
  61622. return true;
  61623. }
  61624. // go through all polygon nodes and cure small local self-intersections
  61625. function cureLocalIntersections(start, triangles, dim) {
  61626. var p = start;
  61627. do {
  61628. var a = p.prev, b = p.next.next;
  61629. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  61630. triangles.push(a.i / dim);
  61631. triangles.push(p.i / dim);
  61632. triangles.push(b.i / dim);
  61633. // remove two nodes involved
  61634. removeNode(p);
  61635. removeNode(p.next);
  61636. p = start = b;
  61637. }
  61638. p = p.next;
  61639. } while (p !== start);
  61640. return p;
  61641. }
  61642. // try splitting polygon into two and triangulate them independently
  61643. function splitEarcut(start, triangles, dim, minX, minY, size) {
  61644. // look for a valid diagonal that divides the polygon into two
  61645. var a = start;
  61646. do {
  61647. var b = a.next.next;
  61648. while (b !== a.prev) {
  61649. if (a.i !== b.i && isValidDiagonal(a, b)) {
  61650. // split the polygon in two by the diagonal
  61651. var c = splitPolygon(a, b);
  61652. // filter colinear points around the cuts
  61653. a = filterPoints(a, a.next);
  61654. c = filterPoints(c, c.next);
  61655. // run earcut on each half
  61656. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  61657. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  61658. return;
  61659. }
  61660. b = b.next;
  61661. }
  61662. a = a.next;
  61663. } while (a !== start);
  61664. }
  61665. // link every hole into the outer loop, producing a single-ring polygon without holes
  61666. function eliminateHoles(data, holeIndices, outerNode, dim) {
  61667. var queue = [], i, len, start, end, list;
  61668. for (i = 0, len = holeIndices.length; i < len; i++) {
  61669. start = holeIndices[i] * dim;
  61670. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  61671. list = linkedList(data, start, end, dim, false);
  61672. if (list === list.next)
  61673. list.steiner = true;
  61674. queue.push(getLeftmost(list));
  61675. }
  61676. queue.sort(compareX);
  61677. // process holes from left to right
  61678. for (i = 0; i < queue.length; i++) {
  61679. eliminateHole(queue[i], outerNode);
  61680. outerNode = filterPoints(outerNode, outerNode.next);
  61681. }
  61682. return outerNode;
  61683. }
  61684. function compareX(a, b) {
  61685. return a.x - b.x;
  61686. }
  61687. // find a bridge between vertices that connects hole with an outer ring and and link it
  61688. function eliminateHole(hole, outerNode) {
  61689. outerNode = findHoleBridge(hole, outerNode);
  61690. if (outerNode) {
  61691. var b = splitPolygon(outerNode, hole);
  61692. filterPoints(b, b.next);
  61693. }
  61694. }
  61695. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  61696. function findHoleBridge(hole, outerNode) {
  61697. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  61698. // find a segment intersected by a ray from the hole's leftmost point to the left;
  61699. // segment's endpoint with lesser x will be potential connection point
  61700. do {
  61701. if (hy <= p.y && hy >= p.next.y) {
  61702. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  61703. if (x <= hx && x > qx) {
  61704. qx = x;
  61705. if (x === hx) {
  61706. if (hy === p.y)
  61707. return p;
  61708. if (hy === p.next.y)
  61709. return p.next;
  61710. }
  61711. m = p.x < p.next.x ? p : p.next;
  61712. }
  61713. }
  61714. p = p.next;
  61715. } while (p !== outerNode);
  61716. if (!m)
  61717. return null;
  61718. if (hx === qx)
  61719. return m.prev; // hole touches outer segment; pick lower endpoint
  61720. // look for points inside the triangle of hole point, segment intersection and endpoint;
  61721. // if there are no points found, we have a valid connection;
  61722. // otherwise choose the point of the minimum angle with the ray as connection point
  61723. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  61724. p = m.next;
  61725. while (p !== stop) {
  61726. if (hx >= p.x &&
  61727. p.x >= mx &&
  61728. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  61729. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  61730. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  61731. m = p;
  61732. tanMin = tan;
  61733. }
  61734. }
  61735. p = p.next;
  61736. }
  61737. return m;
  61738. }
  61739. // interlink polygon nodes in z-order
  61740. function indexCurve(start, minX, minY, size) {
  61741. var p = start;
  61742. do {
  61743. if (p.z === null)
  61744. p.z = zOrder(p.x, p.y, minX, minY, size);
  61745. p.prevZ = p.prev;
  61746. p.nextZ = p.next;
  61747. p = p.next;
  61748. } while (p !== start);
  61749. p.prevZ.nextZ = null;
  61750. p.prevZ = null;
  61751. sortLinked(p);
  61752. }
  61753. // Simon Tatham's linked list merge sort algorithm
  61754. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  61755. function sortLinked(list) {
  61756. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  61757. do {
  61758. p = list;
  61759. list = null;
  61760. tail = null;
  61761. numMerges = 0;
  61762. while (p) {
  61763. numMerges++;
  61764. q = p;
  61765. pSize = 0;
  61766. for (i = 0; i < inSize; i++) {
  61767. pSize++;
  61768. q = q.nextZ;
  61769. if (!q)
  61770. break;
  61771. }
  61772. qSize = inSize;
  61773. while (pSize > 0 || (qSize > 0 && q)) {
  61774. if (pSize === 0) {
  61775. e = q;
  61776. q = q.nextZ;
  61777. qSize--;
  61778. }
  61779. else if (qSize === 0 || !q) {
  61780. e = p;
  61781. p = p.nextZ;
  61782. pSize--;
  61783. }
  61784. else if (p.z <= q.z) {
  61785. e = p;
  61786. p = p.nextZ;
  61787. pSize--;
  61788. }
  61789. else {
  61790. e = q;
  61791. q = q.nextZ;
  61792. qSize--;
  61793. }
  61794. if (tail)
  61795. tail.nextZ = e;
  61796. else
  61797. list = e;
  61798. e.prevZ = tail;
  61799. tail = e;
  61800. }
  61801. p = q;
  61802. }
  61803. tail.nextZ = null;
  61804. inSize *= 2;
  61805. } while (numMerges > 1);
  61806. return list;
  61807. }
  61808. // z-order of a point given coords and size of the data bounding box
  61809. function zOrder(x, y, minX, minY, size) {
  61810. // coords are transformed into non-negative 15-bit integer range
  61811. x = 32767 * (x - minX) / size;
  61812. y = 32767 * (y - minY) / size;
  61813. x = (x | (x << 8)) & 0x00FF00FF;
  61814. x = (x | (x << 4)) & 0x0F0F0F0F;
  61815. x = (x | (x << 2)) & 0x33333333;
  61816. x = (x | (x << 1)) & 0x55555555;
  61817. y = (y | (y << 8)) & 0x00FF00FF;
  61818. y = (y | (y << 4)) & 0x0F0F0F0F;
  61819. y = (y | (y << 2)) & 0x33333333;
  61820. y = (y | (y << 1)) & 0x55555555;
  61821. return x | (y << 1);
  61822. }
  61823. // find the leftmost node of a polygon ring
  61824. function getLeftmost(start) {
  61825. var p = start, leftmost = start;
  61826. do {
  61827. if (p.x < leftmost.x)
  61828. leftmost = p;
  61829. p = p.next;
  61830. } while (p !== start);
  61831. return leftmost;
  61832. }
  61833. // check if a point lies within a convex triangle
  61834. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  61835. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  61836. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  61837. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  61838. }
  61839. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  61840. function isValidDiagonal(a, b) {
  61841. return a.next.i !== b.i &&
  61842. a.prev.i !== b.i &&
  61843. !intersectsPolygon(a, b) &&
  61844. locallyInside(a, b) &&
  61845. locallyInside(b, a) &&
  61846. middleInside(a, b);
  61847. }
  61848. // signed area of a triangle
  61849. function area(p, q, r) {
  61850. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  61851. }
  61852. // check if two points are equal
  61853. function equals(p1, p2) {
  61854. return p1.x === p2.x && p1.y === p2.y;
  61855. }
  61856. // check if two segments intersect
  61857. function intersects(p1, q1, p2, q2) {
  61858. if ((equals(p1, q1) && equals(p2, q2)) ||
  61859. (equals(p1, q2) && equals(p2, q1)))
  61860. return true;
  61861. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  61862. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  61863. }
  61864. // check if a polygon diagonal intersects any polygon segments
  61865. function intersectsPolygon(a, b) {
  61866. var p = a;
  61867. do {
  61868. if (p.i !== a.i &&
  61869. p.next.i !== a.i &&
  61870. p.i !== b.i &&
  61871. p.next.i !== b.i &&
  61872. intersects(p, p.next, a, b))
  61873. return true;
  61874. p = p.next;
  61875. } while (p !== a);
  61876. return false;
  61877. }
  61878. // check if a polygon diagonal is locally inside the polygon
  61879. function locallyInside(a, b) {
  61880. return area(a.prev, a, a.next) < 0
  61881. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  61882. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  61883. }
  61884. // check if the middle point of a polygon diagonal is inside the polygon
  61885. function middleInside(a, b) {
  61886. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  61887. do {
  61888. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  61889. inside = !inside;
  61890. p = p.next;
  61891. } while (p !== a);
  61892. return inside;
  61893. }
  61894. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  61895. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  61896. function splitPolygon(a, b) {
  61897. 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;
  61898. a.next = b;
  61899. b.prev = a;
  61900. a2.next = an;
  61901. an.prev = a2;
  61902. b2.next = a2;
  61903. a2.prev = b2;
  61904. bp.next = b2;
  61905. b2.prev = bp;
  61906. return b2;
  61907. }
  61908. // create a node and optionally link it with previous one (in a circular doubly linked list)
  61909. function insertNode(i, x, y, last) {
  61910. var p = new Node(i, x, y);
  61911. if (!last) {
  61912. p.prev = p;
  61913. p.next = p;
  61914. }
  61915. else {
  61916. p.next = last.next;
  61917. p.prev = last;
  61918. last.next.prev = p;
  61919. last.next = p;
  61920. }
  61921. return p;
  61922. }
  61923. function removeNode(p) {
  61924. p.next.prev = p.prev;
  61925. p.prev.next = p.next;
  61926. if (p.prevZ)
  61927. p.prevZ.nextZ = p.nextZ;
  61928. if (p.nextZ)
  61929. p.nextZ.prevZ = p.prevZ;
  61930. }
  61931. /**
  61932. * return a percentage difference between the polygon area and its triangulation area;
  61933. * used to verify correctness of triangulation
  61934. */
  61935. function deviation(data, holeIndices, dim, triangles) {
  61936. var hasHoles = holeIndices && holeIndices.length;
  61937. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  61938. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  61939. if (hasHoles) {
  61940. for (var i = 0, len = holeIndices.length; i < len; i++) {
  61941. var start = holeIndices[i] * dim;
  61942. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  61943. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  61944. }
  61945. }
  61946. var trianglesArea = 0;
  61947. for (i = 0; i < triangles.length; i += 3) {
  61948. var a = triangles[i] * dim;
  61949. var b = triangles[i + 1] * dim;
  61950. var c = triangles[i + 2] * dim;
  61951. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  61952. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  61953. }
  61954. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  61955. }
  61956. Earcut.deviation = deviation;
  61957. ;
  61958. function signedArea(data, start, end, dim) {
  61959. var sum = 0;
  61960. for (var i = start, j = end - dim; i < end; i += dim) {
  61961. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  61962. j = i;
  61963. }
  61964. return sum;
  61965. }
  61966. /**
  61967. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  61968. */
  61969. function flatten(data) {
  61970. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  61971. for (var i = 0; i < data.length; i++) {
  61972. for (var j = 0; j < data[i].length; j++) {
  61973. for (var d = 0; d < dim; d++)
  61974. result.vertices.push(data[i][j][d]);
  61975. }
  61976. if (i > 0) {
  61977. holeIndex += data[i - 1].length;
  61978. result.holes.push(holeIndex);
  61979. }
  61980. }
  61981. return result;
  61982. }
  61983. Earcut.flatten = flatten;
  61984. ;
  61985. })(Earcut || (Earcut = {}));
  61986. //# sourceMappingURL=babylon.earcut.js.map
  61987. /// <reference path="..\Math\babylon.math.ts" />
  61988. var BABYLON;
  61989. (function (BABYLON) {
  61990. var IndexedVector2 = (function (_super) {
  61991. __extends(IndexedVector2, _super);
  61992. function IndexedVector2(original, index) {
  61993. var _this = _super.call(this, original.x, original.y) || this;
  61994. _this.index = index;
  61995. return _this;
  61996. }
  61997. return IndexedVector2;
  61998. }(BABYLON.Vector2));
  61999. var PolygonPoints = (function () {
  62000. function PolygonPoints() {
  62001. this.elements = new Array();
  62002. }
  62003. PolygonPoints.prototype.add = function (originalPoints) {
  62004. var _this = this;
  62005. var result = new Array();
  62006. originalPoints.forEach(function (point) {
  62007. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  62008. var newPoint = new IndexedVector2(point, _this.elements.length);
  62009. result.push(newPoint);
  62010. _this.elements.push(newPoint);
  62011. }
  62012. });
  62013. return result;
  62014. };
  62015. PolygonPoints.prototype.computeBounds = function () {
  62016. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  62017. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  62018. this.elements.forEach(function (point) {
  62019. // x
  62020. if (point.x < lmin.x) {
  62021. lmin.x = point.x;
  62022. }
  62023. else if (point.x > lmax.x) {
  62024. lmax.x = point.x;
  62025. }
  62026. // y
  62027. if (point.y < lmin.y) {
  62028. lmin.y = point.y;
  62029. }
  62030. else if (point.y > lmax.y) {
  62031. lmax.y = point.y;
  62032. }
  62033. });
  62034. return {
  62035. min: lmin,
  62036. max: lmax,
  62037. width: lmax.x - lmin.x,
  62038. height: lmax.y - lmin.y
  62039. };
  62040. };
  62041. return PolygonPoints;
  62042. }());
  62043. var Polygon = (function () {
  62044. function Polygon() {
  62045. }
  62046. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  62047. return [
  62048. new BABYLON.Vector2(xmin, ymin),
  62049. new BABYLON.Vector2(xmax, ymin),
  62050. new BABYLON.Vector2(xmax, ymax),
  62051. new BABYLON.Vector2(xmin, ymax)
  62052. ];
  62053. };
  62054. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  62055. if (cx === void 0) { cx = 0; }
  62056. if (cy === void 0) { cy = 0; }
  62057. if (numberOfSides === void 0) { numberOfSides = 32; }
  62058. var result = new Array();
  62059. var angle = 0;
  62060. var increment = (Math.PI * 2) / numberOfSides;
  62061. for (var i = 0; i < numberOfSides; i++) {
  62062. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  62063. angle -= increment;
  62064. }
  62065. return result;
  62066. };
  62067. Polygon.Parse = function (input) {
  62068. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  62069. var i, result = [];
  62070. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  62071. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  62072. }
  62073. return result;
  62074. };
  62075. Polygon.StartingAt = function (x, y) {
  62076. return BABYLON.Path2.StartingAt(x, y);
  62077. };
  62078. return Polygon;
  62079. }());
  62080. BABYLON.Polygon = Polygon;
  62081. var PolygonMeshBuilder = (function () {
  62082. function PolygonMeshBuilder(name, contours, scene) {
  62083. this._points = new PolygonPoints();
  62084. this._outlinepoints = new PolygonPoints();
  62085. this._holes = new Array();
  62086. this._epoints = new Array();
  62087. this._eholes = new Array();
  62088. this._name = name;
  62089. this._scene = scene;
  62090. var points;
  62091. if (contours instanceof BABYLON.Path2) {
  62092. points = contours.getPoints();
  62093. }
  62094. else {
  62095. points = contours;
  62096. }
  62097. this._addToepoint(points);
  62098. this._points.add(points);
  62099. this._outlinepoints.add(points);
  62100. }
  62101. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  62102. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  62103. var p = points_1[_i];
  62104. this._epoints.push(p.x, p.y);
  62105. }
  62106. };
  62107. PolygonMeshBuilder.prototype.addHole = function (hole) {
  62108. this._points.add(hole);
  62109. var holepoints = new PolygonPoints();
  62110. holepoints.add(hole);
  62111. this._holes.push(holepoints);
  62112. this._eholes.push(this._epoints.length / 2);
  62113. this._addToepoint(hole);
  62114. return this;
  62115. };
  62116. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  62117. var _this = this;
  62118. if (updatable === void 0) { updatable = false; }
  62119. var result = new BABYLON.Mesh(this._name, this._scene);
  62120. var normals = new Array();
  62121. var positions = new Array();
  62122. var uvs = new Array();
  62123. var bounds = this._points.computeBounds();
  62124. this._points.elements.forEach(function (p) {
  62125. normals.push(0, 1.0, 0);
  62126. positions.push(p.x, 0, p.y);
  62127. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  62128. });
  62129. var indices = new Array();
  62130. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  62131. for (var i = 0; i < res.length; i++) {
  62132. indices.push(res[i]);
  62133. }
  62134. if (depth > 0) {
  62135. var positionscount = (positions.length / 3); //get the current pointcount
  62136. this._points.elements.forEach(function (p) {
  62137. normals.push(0, -1.0, 0);
  62138. positions.push(p.x, -depth, p.y);
  62139. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  62140. });
  62141. var totalCount = indices.length;
  62142. for (var i = 0; i < totalCount; i += 3) {
  62143. var i0 = indices[i + 0];
  62144. var i1 = indices[i + 1];
  62145. var i2 = indices[i + 2];
  62146. indices.push(i2 + positionscount);
  62147. indices.push(i1 + positionscount);
  62148. indices.push(i0 + positionscount);
  62149. }
  62150. //Add the sides
  62151. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  62152. this._holes.forEach(function (hole) {
  62153. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  62154. });
  62155. }
  62156. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  62157. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  62158. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  62159. result.setIndices(indices);
  62160. return result;
  62161. };
  62162. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  62163. var StartIndex = positions.length / 3;
  62164. var ulength = 0;
  62165. for (var i = 0; i < points.elements.length; i++) {
  62166. var p = points.elements[i];
  62167. var p1;
  62168. if ((i + 1) > points.elements.length - 1) {
  62169. p1 = points.elements[0];
  62170. }
  62171. else {
  62172. p1 = points.elements[i + 1];
  62173. }
  62174. positions.push(p.x, 0, p.y);
  62175. positions.push(p.x, -depth, p.y);
  62176. positions.push(p1.x, 0, p1.y);
  62177. positions.push(p1.x, -depth, p1.y);
  62178. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  62179. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  62180. var v3 = v2.subtract(v1);
  62181. var v4 = new BABYLON.Vector3(0, 1, 0);
  62182. var vn = BABYLON.Vector3.Cross(v3, v4);
  62183. vn = vn.normalize();
  62184. uvs.push(ulength / bounds.width, 0);
  62185. uvs.push(ulength / bounds.width, 1);
  62186. ulength += v3.length();
  62187. uvs.push((ulength / bounds.width), 0);
  62188. uvs.push((ulength / bounds.width), 1);
  62189. if (!flip) {
  62190. normals.push(-vn.x, -vn.y, -vn.z);
  62191. normals.push(-vn.x, -vn.y, -vn.z);
  62192. normals.push(-vn.x, -vn.y, -vn.z);
  62193. normals.push(-vn.x, -vn.y, -vn.z);
  62194. indices.push(StartIndex);
  62195. indices.push(StartIndex + 1);
  62196. indices.push(StartIndex + 2);
  62197. indices.push(StartIndex + 1);
  62198. indices.push(StartIndex + 3);
  62199. indices.push(StartIndex + 2);
  62200. }
  62201. else {
  62202. normals.push(vn.x, vn.y, vn.z);
  62203. normals.push(vn.x, vn.y, vn.z);
  62204. normals.push(vn.x, vn.y, vn.z);
  62205. normals.push(vn.x, vn.y, vn.z);
  62206. indices.push(StartIndex);
  62207. indices.push(StartIndex + 2);
  62208. indices.push(StartIndex + 1);
  62209. indices.push(StartIndex + 1);
  62210. indices.push(StartIndex + 2);
  62211. indices.push(StartIndex + 3);
  62212. }
  62213. StartIndex += 4;
  62214. }
  62215. ;
  62216. };
  62217. return PolygonMeshBuilder;
  62218. }());
  62219. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  62220. })(BABYLON || (BABYLON = {}));
  62221. //# sourceMappingURL=babylon.polygonMesh.js.map
  62222. var BABYLON;
  62223. (function (BABYLON) {
  62224. // Unique ID when we import meshes from Babylon to CSG
  62225. var currentCSGMeshId = 0;
  62226. // # class Vertex
  62227. // Represents a vertex of a polygon. Use your own vertex class instead of this
  62228. // one to provide additional features like texture coordinates and vertex
  62229. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  62230. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  62231. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  62232. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  62233. // is not used anywhere else.
  62234. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  62235. var Vertex = (function () {
  62236. function Vertex(pos, normal, uv) {
  62237. this.pos = pos;
  62238. this.normal = normal;
  62239. this.uv = uv;
  62240. }
  62241. Vertex.prototype.clone = function () {
  62242. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  62243. };
  62244. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  62245. // orientation of a polygon is flipped.
  62246. Vertex.prototype.flip = function () {
  62247. this.normal = this.normal.scale(-1);
  62248. };
  62249. // Create a new vertex between this vertex and `other` by linearly
  62250. // interpolating all properties using a parameter of `t`. Subclasses should
  62251. // override this to interpolate additional properties.
  62252. Vertex.prototype.interpolate = function (other, t) {
  62253. 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));
  62254. };
  62255. return Vertex;
  62256. }());
  62257. // # class Plane
  62258. // Represents a plane in 3D space.
  62259. var Plane = (function () {
  62260. function Plane(normal, w) {
  62261. this.normal = normal;
  62262. this.w = w;
  62263. }
  62264. Plane.FromPoints = function (a, b, c) {
  62265. var v0 = c.subtract(a);
  62266. var v1 = b.subtract(a);
  62267. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  62268. return null;
  62269. }
  62270. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  62271. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  62272. };
  62273. Plane.prototype.clone = function () {
  62274. return new Plane(this.normal.clone(), this.w);
  62275. };
  62276. Plane.prototype.flip = function () {
  62277. this.normal.scaleInPlace(-1);
  62278. this.w = -this.w;
  62279. };
  62280. // Split `polygon` by this plane if needed, then put the polygon or polygon
  62281. // fragments in the appropriate lists. Coplanar polygons go into either
  62282. // `coplanarFront` or `coplanarBack` depending on their orientation with
  62283. // respect to this plane. Polygons in front or in back of this plane go into
  62284. // either `front` or `back`.
  62285. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  62286. var COPLANAR = 0;
  62287. var FRONT = 1;
  62288. var BACK = 2;
  62289. var SPANNING = 3;
  62290. // Classify each point as well as the entire polygon into one of the above
  62291. // four classes.
  62292. var polygonType = 0;
  62293. var types = [];
  62294. var i;
  62295. var t;
  62296. for (i = 0; i < polygon.vertices.length; i++) {
  62297. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  62298. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  62299. polygonType |= type;
  62300. types.push(type);
  62301. }
  62302. // Put the polygon in the correct list, splitting it when necessary.
  62303. switch (polygonType) {
  62304. case COPLANAR:
  62305. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  62306. break;
  62307. case FRONT:
  62308. front.push(polygon);
  62309. break;
  62310. case BACK:
  62311. back.push(polygon);
  62312. break;
  62313. case SPANNING:
  62314. var f = [], b = [];
  62315. for (i = 0; i < polygon.vertices.length; i++) {
  62316. var j = (i + 1) % polygon.vertices.length;
  62317. var ti = types[i], tj = types[j];
  62318. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  62319. if (ti !== BACK)
  62320. f.push(vi);
  62321. if (ti !== FRONT)
  62322. b.push(ti !== BACK ? vi.clone() : vi);
  62323. if ((ti | tj) === SPANNING) {
  62324. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  62325. var v = vi.interpolate(vj, t);
  62326. f.push(v);
  62327. b.push(v.clone());
  62328. }
  62329. }
  62330. var poly;
  62331. if (f.length >= 3) {
  62332. poly = new Polygon(f, polygon.shared);
  62333. if (poly.plane)
  62334. front.push(poly);
  62335. }
  62336. if (b.length >= 3) {
  62337. poly = new Polygon(b, polygon.shared);
  62338. if (poly.plane)
  62339. back.push(poly);
  62340. }
  62341. break;
  62342. }
  62343. };
  62344. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  62345. // point is on the plane.
  62346. Plane.EPSILON = 1e-5;
  62347. return Plane;
  62348. }());
  62349. // # class Polygon
  62350. // Represents a convex polygon. The vertices used to initialize a polygon must
  62351. // be coplanar and form a convex loop.
  62352. //
  62353. // Each convex polygon has a `shared` property, which is shared between all
  62354. // polygons that are clones of each other or were split from the same polygon.
  62355. // This can be used to define per-polygon properties (such as surface color).
  62356. var Polygon = (function () {
  62357. function Polygon(vertices, shared) {
  62358. this.vertices = vertices;
  62359. this.shared = shared;
  62360. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  62361. }
  62362. Polygon.prototype.clone = function () {
  62363. var vertices = this.vertices.map(function (v) { return v.clone(); });
  62364. return new Polygon(vertices, this.shared);
  62365. };
  62366. Polygon.prototype.flip = function () {
  62367. this.vertices.reverse().map(function (v) { v.flip(); });
  62368. this.plane.flip();
  62369. };
  62370. return Polygon;
  62371. }());
  62372. // # class Node
  62373. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  62374. // by picking a polygon to split along. That polygon (and all other coplanar
  62375. // polygons) are added directly to that node and the other polygons are added to
  62376. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  62377. // no distinction between internal and leaf nodes.
  62378. var Node = (function () {
  62379. function Node(polygons) {
  62380. this.plane = null;
  62381. this.front = null;
  62382. this.back = null;
  62383. this.polygons = new Array();
  62384. if (polygons) {
  62385. this.build(polygons);
  62386. }
  62387. }
  62388. Node.prototype.clone = function () {
  62389. var node = new Node();
  62390. node.plane = this.plane && this.plane.clone();
  62391. node.front = this.front && this.front.clone();
  62392. node.back = this.back && this.back.clone();
  62393. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  62394. return node;
  62395. };
  62396. // Convert solid space to empty space and empty space to solid space.
  62397. Node.prototype.invert = function () {
  62398. for (var i = 0; i < this.polygons.length; i++) {
  62399. this.polygons[i].flip();
  62400. }
  62401. if (this.plane) {
  62402. this.plane.flip();
  62403. }
  62404. if (this.front) {
  62405. this.front.invert();
  62406. }
  62407. if (this.back) {
  62408. this.back.invert();
  62409. }
  62410. var temp = this.front;
  62411. this.front = this.back;
  62412. this.back = temp;
  62413. };
  62414. // Recursively remove all polygons in `polygons` that are inside this BSP
  62415. // tree.
  62416. Node.prototype.clipPolygons = function (polygons) {
  62417. if (!this.plane)
  62418. return polygons.slice();
  62419. var front = new Array(), back = new Array();
  62420. for (var i = 0; i < polygons.length; i++) {
  62421. this.plane.splitPolygon(polygons[i], front, back, front, back);
  62422. }
  62423. if (this.front) {
  62424. front = this.front.clipPolygons(front);
  62425. }
  62426. if (this.back) {
  62427. back = this.back.clipPolygons(back);
  62428. }
  62429. else {
  62430. back = [];
  62431. }
  62432. return front.concat(back);
  62433. };
  62434. // Remove all polygons in this BSP tree that are inside the other BSP tree
  62435. // `bsp`.
  62436. Node.prototype.clipTo = function (bsp) {
  62437. this.polygons = bsp.clipPolygons(this.polygons);
  62438. if (this.front)
  62439. this.front.clipTo(bsp);
  62440. if (this.back)
  62441. this.back.clipTo(bsp);
  62442. };
  62443. // Return a list of all polygons in this BSP tree.
  62444. Node.prototype.allPolygons = function () {
  62445. var polygons = this.polygons.slice();
  62446. if (this.front)
  62447. polygons = polygons.concat(this.front.allPolygons());
  62448. if (this.back)
  62449. polygons = polygons.concat(this.back.allPolygons());
  62450. return polygons;
  62451. };
  62452. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  62453. // new polygons are filtered down to the bottom of the tree and become new
  62454. // nodes there. Each set of polygons is partitioned using the first polygon
  62455. // (no heuristic is used to pick a good split).
  62456. Node.prototype.build = function (polygons) {
  62457. if (!polygons.length)
  62458. return;
  62459. if (!this.plane)
  62460. this.plane = polygons[0].plane.clone();
  62461. var front = new Array(), back = new Array();
  62462. for (var i = 0; i < polygons.length; i++) {
  62463. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  62464. }
  62465. if (front.length) {
  62466. if (!this.front)
  62467. this.front = new Node();
  62468. this.front.build(front);
  62469. }
  62470. if (back.length) {
  62471. if (!this.back)
  62472. this.back = new Node();
  62473. this.back.build(back);
  62474. }
  62475. };
  62476. return Node;
  62477. }());
  62478. var CSG = (function () {
  62479. function CSG() {
  62480. this.polygons = new Array();
  62481. }
  62482. // Convert BABYLON.Mesh to BABYLON.CSG
  62483. CSG.FromMesh = function (mesh) {
  62484. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  62485. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  62486. if (mesh instanceof BABYLON.Mesh) {
  62487. mesh.computeWorldMatrix(true);
  62488. matrix = mesh.getWorldMatrix();
  62489. meshPosition = mesh.position.clone();
  62490. meshRotation = mesh.rotation.clone();
  62491. if (mesh.rotationQuaternion) {
  62492. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  62493. }
  62494. meshScaling = mesh.scaling.clone();
  62495. }
  62496. else {
  62497. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  62498. }
  62499. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62500. var subMeshes = mesh.subMeshes;
  62501. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  62502. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  62503. vertices = [];
  62504. for (var j = 0; j < 3; j++) {
  62505. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  62506. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  62507. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  62508. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  62509. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  62510. vertex = new Vertex(position, normal, uv);
  62511. vertices.push(vertex);
  62512. }
  62513. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  62514. // To handle the case of degenerated triangle
  62515. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  62516. if (polygon.plane)
  62517. polygons.push(polygon);
  62518. }
  62519. }
  62520. var csg = CSG.FromPolygons(polygons);
  62521. csg.matrix = matrix;
  62522. csg.position = meshPosition;
  62523. csg.rotation = meshRotation;
  62524. csg.scaling = meshScaling;
  62525. csg.rotationQuaternion = meshRotationQuaternion;
  62526. currentCSGMeshId++;
  62527. return csg;
  62528. };
  62529. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  62530. CSG.FromPolygons = function (polygons) {
  62531. var csg = new CSG();
  62532. csg.polygons = polygons;
  62533. return csg;
  62534. };
  62535. CSG.prototype.clone = function () {
  62536. var csg = new CSG();
  62537. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  62538. csg.copyTransformAttributes(this);
  62539. return csg;
  62540. };
  62541. CSG.prototype.toPolygons = function () {
  62542. return this.polygons;
  62543. };
  62544. CSG.prototype.union = function (csg) {
  62545. var a = new Node(this.clone().polygons);
  62546. var b = new Node(csg.clone().polygons);
  62547. a.clipTo(b);
  62548. b.clipTo(a);
  62549. b.invert();
  62550. b.clipTo(a);
  62551. b.invert();
  62552. a.build(b.allPolygons());
  62553. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62554. };
  62555. CSG.prototype.unionInPlace = function (csg) {
  62556. var a = new Node(this.polygons);
  62557. var b = new Node(csg.polygons);
  62558. a.clipTo(b);
  62559. b.clipTo(a);
  62560. b.invert();
  62561. b.clipTo(a);
  62562. b.invert();
  62563. a.build(b.allPolygons());
  62564. this.polygons = a.allPolygons();
  62565. };
  62566. CSG.prototype.subtract = function (csg) {
  62567. var a = new Node(this.clone().polygons);
  62568. var b = new Node(csg.clone().polygons);
  62569. a.invert();
  62570. a.clipTo(b);
  62571. b.clipTo(a);
  62572. b.invert();
  62573. b.clipTo(a);
  62574. b.invert();
  62575. a.build(b.allPolygons());
  62576. a.invert();
  62577. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62578. };
  62579. CSG.prototype.subtractInPlace = function (csg) {
  62580. var a = new Node(this.polygons);
  62581. var b = new Node(csg.polygons);
  62582. a.invert();
  62583. a.clipTo(b);
  62584. b.clipTo(a);
  62585. b.invert();
  62586. b.clipTo(a);
  62587. b.invert();
  62588. a.build(b.allPolygons());
  62589. a.invert();
  62590. this.polygons = a.allPolygons();
  62591. };
  62592. CSG.prototype.intersect = function (csg) {
  62593. var a = new Node(this.clone().polygons);
  62594. var b = new Node(csg.clone().polygons);
  62595. a.invert();
  62596. b.clipTo(a);
  62597. b.invert();
  62598. a.clipTo(b);
  62599. b.clipTo(a);
  62600. a.build(b.allPolygons());
  62601. a.invert();
  62602. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62603. };
  62604. CSG.prototype.intersectInPlace = function (csg) {
  62605. var a = new Node(this.polygons);
  62606. var b = new Node(csg.polygons);
  62607. a.invert();
  62608. b.clipTo(a);
  62609. b.invert();
  62610. a.clipTo(b);
  62611. b.clipTo(a);
  62612. a.build(b.allPolygons());
  62613. a.invert();
  62614. this.polygons = a.allPolygons();
  62615. };
  62616. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  62617. // not modified.
  62618. CSG.prototype.inverse = function () {
  62619. var csg = this.clone();
  62620. csg.inverseInPlace();
  62621. return csg;
  62622. };
  62623. CSG.prototype.inverseInPlace = function () {
  62624. this.polygons.map(function (p) { p.flip(); });
  62625. };
  62626. // This is used to keep meshes transformations so they can be restored
  62627. // when we build back a Babylon Mesh
  62628. // NB : All CSG operations are performed in world coordinates
  62629. CSG.prototype.copyTransformAttributes = function (csg) {
  62630. this.matrix = csg.matrix;
  62631. this.position = csg.position;
  62632. this.rotation = csg.rotation;
  62633. this.scaling = csg.scaling;
  62634. this.rotationQuaternion = csg.rotationQuaternion;
  62635. return this;
  62636. };
  62637. // Build Raw mesh from CSG
  62638. // Coordinates here are in world space
  62639. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  62640. var matrix = this.matrix.clone();
  62641. matrix.invert();
  62642. 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;
  62643. if (keepSubMeshes) {
  62644. // Sort Polygons, since subMeshes are indices range
  62645. polygons.sort(function (a, b) {
  62646. if (a.shared.meshId === b.shared.meshId) {
  62647. return a.shared.subMeshId - b.shared.subMeshId;
  62648. }
  62649. else {
  62650. return a.shared.meshId - b.shared.meshId;
  62651. }
  62652. });
  62653. }
  62654. for (var i = 0, il = polygons.length; i < il; i++) {
  62655. polygon = polygons[i];
  62656. // Building SubMeshes
  62657. if (!subMesh_dict[polygon.shared.meshId]) {
  62658. subMesh_dict[polygon.shared.meshId] = {};
  62659. }
  62660. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  62661. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  62662. indexStart: +Infinity,
  62663. indexEnd: -Infinity,
  62664. materialIndex: polygon.shared.materialIndex
  62665. };
  62666. }
  62667. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  62668. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  62669. polygonIndices[0] = 0;
  62670. polygonIndices[1] = j - 1;
  62671. polygonIndices[2] = j;
  62672. for (var k = 0; k < 3; k++) {
  62673. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  62674. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  62675. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  62676. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  62677. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  62678. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  62679. // Check if 2 points can be merged
  62680. if (!(typeof vertex_idx !== 'undefined' &&
  62681. normals[vertex_idx * 3] === localNormal.x &&
  62682. normals[vertex_idx * 3 + 1] === localNormal.y &&
  62683. normals[vertex_idx * 3 + 2] === localNormal.z &&
  62684. uvs[vertex_idx * 2] === uv.x &&
  62685. uvs[vertex_idx * 2 + 1] === uv.y)) {
  62686. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  62687. uvs.push(uv.x, uv.y);
  62688. normals.push(normal.x, normal.y, normal.z);
  62689. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  62690. }
  62691. indices.push(vertex_idx);
  62692. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  62693. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  62694. currentIndex++;
  62695. }
  62696. }
  62697. }
  62698. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  62699. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  62700. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  62701. mesh.setIndices(indices);
  62702. if (keepSubMeshes) {
  62703. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  62704. var materialIndexOffset = 0, materialMaxIndex;
  62705. mesh.subMeshes = new Array();
  62706. for (var m in subMesh_dict) {
  62707. materialMaxIndex = -1;
  62708. for (var sm in subMesh_dict[m]) {
  62709. subMesh_obj = subMesh_dict[m][sm];
  62710. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  62711. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  62712. }
  62713. materialIndexOffset += ++materialMaxIndex;
  62714. }
  62715. }
  62716. return mesh;
  62717. };
  62718. // Build Mesh from CSG taking material and transforms into account
  62719. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  62720. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  62721. mesh.material = material;
  62722. mesh.position.copyFrom(this.position);
  62723. mesh.rotation.copyFrom(this.rotation);
  62724. if (this.rotationQuaternion) {
  62725. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  62726. }
  62727. mesh.scaling.copyFrom(this.scaling);
  62728. mesh.computeWorldMatrix(true);
  62729. return mesh;
  62730. };
  62731. return CSG;
  62732. }());
  62733. BABYLON.CSG = CSG;
  62734. })(BABYLON || (BABYLON = {}));
  62735. //# sourceMappingURL=babylon.csg.js.map
  62736. var BABYLON;
  62737. (function (BABYLON) {
  62738. var LensFlare = (function () {
  62739. function LensFlare(size, position, color, imgUrl, system) {
  62740. this.size = size;
  62741. this.position = position;
  62742. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  62743. this.dispose = function () {
  62744. if (this.texture) {
  62745. this.texture.dispose();
  62746. }
  62747. // Remove from scene
  62748. var index = this._system.lensFlares.indexOf(this);
  62749. this._system.lensFlares.splice(index, 1);
  62750. };
  62751. this.color = color || new BABYLON.Color3(1, 1, 1);
  62752. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  62753. this._system = system;
  62754. system.lensFlares.push(this);
  62755. }
  62756. return LensFlare;
  62757. }());
  62758. BABYLON.LensFlare = LensFlare;
  62759. })(BABYLON || (BABYLON = {}));
  62760. //# sourceMappingURL=babylon.lensFlare.js.map
  62761. var BABYLON;
  62762. (function (BABYLON) {
  62763. var LensFlareSystem = (function () {
  62764. function LensFlareSystem(name, emitter, scene) {
  62765. this.name = name;
  62766. this.lensFlares = new Array();
  62767. this.borderLimit = 300;
  62768. this.viewportBorder = 0;
  62769. this.layerMask = 0x0FFFFFFF;
  62770. this._vertexBuffers = {};
  62771. this._isEnabled = true;
  62772. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62773. this._emitter = emitter;
  62774. this.id = name;
  62775. scene.lensFlareSystems.push(this);
  62776. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  62777. var engine = scene.getEngine();
  62778. // VBO
  62779. var vertices = [];
  62780. vertices.push(1, 1);
  62781. vertices.push(-1, 1);
  62782. vertices.push(-1, -1);
  62783. vertices.push(1, -1);
  62784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62785. // Indices
  62786. var indices = [];
  62787. indices.push(0);
  62788. indices.push(1);
  62789. indices.push(2);
  62790. indices.push(0);
  62791. indices.push(2);
  62792. indices.push(3);
  62793. this._indexBuffer = engine.createIndexBuffer(indices);
  62794. // Effects
  62795. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  62796. }
  62797. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  62798. get: function () {
  62799. return this._isEnabled;
  62800. },
  62801. set: function (value) {
  62802. this._isEnabled = value;
  62803. },
  62804. enumerable: true,
  62805. configurable: true
  62806. });
  62807. LensFlareSystem.prototype.getScene = function () {
  62808. return this._scene;
  62809. };
  62810. LensFlareSystem.prototype.getEmitter = function () {
  62811. return this._emitter;
  62812. };
  62813. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  62814. this._emitter = newEmitter;
  62815. };
  62816. LensFlareSystem.prototype.getEmitterPosition = function () {
  62817. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  62818. };
  62819. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  62820. var position = this.getEmitterPosition();
  62821. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  62822. this._positionX = position.x;
  62823. this._positionY = position.y;
  62824. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  62825. if (this.viewportBorder > 0) {
  62826. globalViewport.x -= this.viewportBorder;
  62827. globalViewport.y -= this.viewportBorder;
  62828. globalViewport.width += this.viewportBorder * 2;
  62829. globalViewport.height += this.viewportBorder * 2;
  62830. position.x += this.viewportBorder;
  62831. position.y += this.viewportBorder;
  62832. this._positionX += this.viewportBorder;
  62833. this._positionY += this.viewportBorder;
  62834. }
  62835. if (position.z > 0) {
  62836. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  62837. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  62838. return true;
  62839. }
  62840. return true;
  62841. }
  62842. return false;
  62843. };
  62844. LensFlareSystem.prototype._isVisible = function () {
  62845. if (!this._isEnabled) {
  62846. return false;
  62847. }
  62848. var emitterPosition = this.getEmitterPosition();
  62849. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  62850. var distance = direction.length();
  62851. direction.normalize();
  62852. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  62853. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  62854. return !pickInfo.hit || pickInfo.distance > distance;
  62855. };
  62856. LensFlareSystem.prototype.render = function () {
  62857. if (!this._effect.isReady())
  62858. return false;
  62859. var engine = this._scene.getEngine();
  62860. var viewport = this._scene.activeCamera.viewport;
  62861. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  62862. // Position
  62863. if (!this.computeEffectivePosition(globalViewport)) {
  62864. return false;
  62865. }
  62866. // Visibility
  62867. if (!this._isVisible()) {
  62868. return false;
  62869. }
  62870. // Intensity
  62871. var awayX;
  62872. var awayY;
  62873. if (this._positionX < this.borderLimit + globalViewport.x) {
  62874. awayX = this.borderLimit + globalViewport.x - this._positionX;
  62875. }
  62876. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  62877. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  62878. }
  62879. else {
  62880. awayX = 0;
  62881. }
  62882. if (this._positionY < this.borderLimit + globalViewport.y) {
  62883. awayY = this.borderLimit + globalViewport.y - this._positionY;
  62884. }
  62885. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  62886. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  62887. }
  62888. else {
  62889. awayY = 0;
  62890. }
  62891. var away = (awayX > awayY) ? awayX : awayY;
  62892. away -= this.viewportBorder;
  62893. if (away > this.borderLimit) {
  62894. away = this.borderLimit;
  62895. }
  62896. var intensity = 1.0 - (away / this.borderLimit);
  62897. if (intensity < 0) {
  62898. return false;
  62899. }
  62900. if (intensity > 1.0) {
  62901. intensity = 1.0;
  62902. }
  62903. if (this.viewportBorder > 0) {
  62904. globalViewport.x += this.viewportBorder;
  62905. globalViewport.y += this.viewportBorder;
  62906. globalViewport.width -= this.viewportBorder * 2;
  62907. globalViewport.height -= this.viewportBorder * 2;
  62908. this._positionX -= this.viewportBorder;
  62909. this._positionY -= this.viewportBorder;
  62910. }
  62911. // Position
  62912. var centerX = globalViewport.x + globalViewport.width / 2;
  62913. var centerY = globalViewport.y + globalViewport.height / 2;
  62914. var distX = centerX - this._positionX;
  62915. var distY = centerY - this._positionY;
  62916. // Effects
  62917. engine.enableEffect(this._effect);
  62918. engine.setState(false);
  62919. engine.setDepthBuffer(false);
  62920. // VBOs
  62921. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62922. // Flares
  62923. for (var index = 0; index < this.lensFlares.length; index++) {
  62924. var flare = this.lensFlares[index];
  62925. engine.setAlphaMode(flare.alphaMode);
  62926. var x = centerX - (distX * flare.position);
  62927. var y = centerY - (distY * flare.position);
  62928. var cw = flare.size;
  62929. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  62930. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  62931. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  62932. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  62933. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  62934. // Texture
  62935. this._effect.setTexture("textureSampler", flare.texture);
  62936. // Color
  62937. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  62938. // Draw order
  62939. engine.draw(true, 0, 6);
  62940. }
  62941. engine.setDepthBuffer(true);
  62942. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62943. return true;
  62944. };
  62945. LensFlareSystem.prototype.dispose = function () {
  62946. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62947. if (vertexBuffer) {
  62948. vertexBuffer.dispose();
  62949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62950. }
  62951. if (this._indexBuffer) {
  62952. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62953. this._indexBuffer = null;
  62954. }
  62955. while (this.lensFlares.length) {
  62956. this.lensFlares[0].dispose();
  62957. }
  62958. // Remove from scene
  62959. var index = this._scene.lensFlareSystems.indexOf(this);
  62960. this._scene.lensFlareSystems.splice(index, 1);
  62961. };
  62962. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  62963. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  62964. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  62965. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  62966. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  62967. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  62968. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  62969. var parsedFlare = parsedLensFlareSystem.flares[index];
  62970. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  62971. }
  62972. return lensFlareSystem;
  62973. };
  62974. LensFlareSystem.prototype.serialize = function () {
  62975. var serializationObject = {};
  62976. serializationObject.id = this.id;
  62977. serializationObject.name = this.name;
  62978. serializationObject.emitterId = this.getEmitter().id;
  62979. serializationObject.borderLimit = this.borderLimit;
  62980. serializationObject.flares = [];
  62981. for (var index = 0; index < this.lensFlares.length; index++) {
  62982. var flare = this.lensFlares[index];
  62983. serializationObject.flares.push({
  62984. size: flare.size,
  62985. position: flare.position,
  62986. color: flare.color.asArray(),
  62987. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  62988. });
  62989. }
  62990. return serializationObject;
  62991. };
  62992. return LensFlareSystem;
  62993. }());
  62994. BABYLON.LensFlareSystem = LensFlareSystem;
  62995. })(BABYLON || (BABYLON = {}));
  62996. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  62997. var BABYLON;
  62998. (function (BABYLON) {
  62999. /**
  63000. * This is a holder class for the physics joint created by the physics plugin.
  63001. * It holds a set of functions to control the underlying joint.
  63002. */
  63003. var PhysicsJoint = (function () {
  63004. function PhysicsJoint(type, jointData) {
  63005. this.type = type;
  63006. this.jointData = jointData;
  63007. jointData.nativeParams = jointData.nativeParams || {};
  63008. }
  63009. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  63010. get: function () {
  63011. return this._physicsJoint;
  63012. },
  63013. set: function (newJoint) {
  63014. if (this._physicsJoint) {
  63015. //remove from the wolrd
  63016. }
  63017. this._physicsJoint = newJoint;
  63018. },
  63019. enumerable: true,
  63020. configurable: true
  63021. });
  63022. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  63023. set: function (physicsPlugin) {
  63024. this._physicsPlugin = physicsPlugin;
  63025. },
  63026. enumerable: true,
  63027. configurable: true
  63028. });
  63029. /**
  63030. * Execute a function that is physics-plugin specific.
  63031. * @param {Function} func the function that will be executed.
  63032. * It accepts two parameters: the physics world and the physics joint.
  63033. */
  63034. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  63035. func(this._physicsPlugin.world, this._physicsJoint);
  63036. };
  63037. //TODO check if the native joints are the same
  63038. //Joint Types
  63039. PhysicsJoint.DistanceJoint = 0;
  63040. PhysicsJoint.HingeJoint = 1;
  63041. PhysicsJoint.BallAndSocketJoint = 2;
  63042. PhysicsJoint.WheelJoint = 3;
  63043. PhysicsJoint.SliderJoint = 4;
  63044. //OIMO
  63045. PhysicsJoint.PrismaticJoint = 5;
  63046. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  63047. PhysicsJoint.UniversalJoint = 6;
  63048. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  63049. //Cannon
  63050. //Similar to a Ball-Joint. Different in params
  63051. PhysicsJoint.PointToPointJoint = 8;
  63052. //Cannon only at the moment
  63053. PhysicsJoint.SpringJoint = 9;
  63054. PhysicsJoint.LockJoint = 10;
  63055. return PhysicsJoint;
  63056. }());
  63057. BABYLON.PhysicsJoint = PhysicsJoint;
  63058. /**
  63059. * A class representing a physics distance joint.
  63060. */
  63061. var DistanceJoint = (function (_super) {
  63062. __extends(DistanceJoint, _super);
  63063. function DistanceJoint(jointData) {
  63064. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  63065. }
  63066. /**
  63067. * Update the predefined distance.
  63068. */
  63069. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  63070. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  63071. };
  63072. return DistanceJoint;
  63073. }(PhysicsJoint));
  63074. BABYLON.DistanceJoint = DistanceJoint;
  63075. var MotorEnabledJoint = (function (_super) {
  63076. __extends(MotorEnabledJoint, _super);
  63077. function MotorEnabledJoint(type, jointData) {
  63078. return _super.call(this, type, jointData) || this;
  63079. }
  63080. /**
  63081. * Set the motor values.
  63082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63083. * @param {number} force the force to apply
  63084. * @param {number} maxForce max force for this motor.
  63085. */
  63086. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  63087. this._physicsPlugin.setMotor(this, force, maxForce);
  63088. };
  63089. /**
  63090. * Set the motor's limits.
  63091. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63092. */
  63093. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63094. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63095. };
  63096. return MotorEnabledJoint;
  63097. }(PhysicsJoint));
  63098. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  63099. /**
  63100. * This class represents a single hinge physics joint
  63101. */
  63102. var HingeJoint = (function (_super) {
  63103. __extends(HingeJoint, _super);
  63104. function HingeJoint(jointData) {
  63105. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  63106. }
  63107. /**
  63108. * Set the motor values.
  63109. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63110. * @param {number} force the force to apply
  63111. * @param {number} maxForce max force for this motor.
  63112. */
  63113. HingeJoint.prototype.setMotor = function (force, maxForce) {
  63114. this._physicsPlugin.setMotor(this, force, maxForce);
  63115. };
  63116. /**
  63117. * Set the motor's limits.
  63118. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63119. */
  63120. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63121. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63122. };
  63123. return HingeJoint;
  63124. }(MotorEnabledJoint));
  63125. BABYLON.HingeJoint = HingeJoint;
  63126. /**
  63127. * This class represents a dual hinge physics joint (same as wheel joint)
  63128. */
  63129. var Hinge2Joint = (function (_super) {
  63130. __extends(Hinge2Joint, _super);
  63131. function Hinge2Joint(jointData) {
  63132. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  63133. }
  63134. /**
  63135. * Set the motor values.
  63136. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63137. * @param {number} force the force to apply
  63138. * @param {number} maxForce max force for this motor.
  63139. * @param {motorIndex} the motor's index, 0 or 1.
  63140. */
  63141. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  63142. if (motorIndex === void 0) { motorIndex = 0; }
  63143. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  63144. };
  63145. /**
  63146. * Set the motor limits.
  63147. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63148. * @param {number} upperLimit the upper limit
  63149. * @param {number} lowerLimit lower limit
  63150. * @param {motorIndex} the motor's index, 0 or 1.
  63151. */
  63152. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  63153. if (motorIndex === void 0) { motorIndex = 0; }
  63154. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  63155. };
  63156. return Hinge2Joint;
  63157. }(MotorEnabledJoint));
  63158. BABYLON.Hinge2Joint = Hinge2Joint;
  63159. })(BABYLON || (BABYLON = {}));
  63160. //# sourceMappingURL=babylon.physicsJoint.js.map
  63161. var BABYLON;
  63162. (function (BABYLON) {
  63163. var PhysicsImpostor = (function () {
  63164. function PhysicsImpostor(object, type, _options, _scene) {
  63165. if (_options === void 0) { _options = { mass: 0 }; }
  63166. var _this = this;
  63167. this.object = object;
  63168. this.type = type;
  63169. this._options = _options;
  63170. this._scene = _scene;
  63171. this._bodyUpdateRequired = false;
  63172. this._onBeforePhysicsStepCallbacks = new Array();
  63173. this._onAfterPhysicsStepCallbacks = new Array();
  63174. this._onPhysicsCollideCallbacks = [];
  63175. this._deltaPosition = BABYLON.Vector3.Zero();
  63176. this._isDisposed = false;
  63177. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  63178. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  63179. /**
  63180. * this function is executed by the physics engine.
  63181. */
  63182. this.beforeStep = function () {
  63183. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  63184. //conjugate deltaRotation
  63185. if (_this._deltaRotationConjugated) {
  63186. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  63187. }
  63188. else {
  63189. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  63190. }
  63191. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  63192. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  63193. func(_this);
  63194. });
  63195. };
  63196. /**
  63197. * this function is executed by the physics engine.
  63198. */
  63199. this.afterStep = function () {
  63200. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  63201. func(_this);
  63202. });
  63203. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  63204. _this.object.position.addInPlace(_this._deltaPosition);
  63205. if (_this._deltaRotation) {
  63206. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  63207. }
  63208. };
  63209. /**
  63210. * Legacy collision detection event support
  63211. */
  63212. this.onCollideEvent = null;
  63213. //event and body object due to cannon's event-based architecture.
  63214. this.onCollide = function (e) {
  63215. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  63216. return;
  63217. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  63218. if (otherImpostor) {
  63219. // Legacy collision detection event support
  63220. if (_this.onCollideEvent) {
  63221. _this.onCollideEvent(_this, otherImpostor);
  63222. }
  63223. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  63224. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  63225. }).forEach(function (obj) {
  63226. obj.callback(_this, otherImpostor);
  63227. });
  63228. }
  63229. };
  63230. //sanity check!
  63231. if (!this.object) {
  63232. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  63233. return;
  63234. }
  63235. //legacy support for old syntax.
  63236. if (!this._scene && object.getScene) {
  63237. this._scene = object.getScene();
  63238. }
  63239. this._physicsEngine = this._scene.getPhysicsEngine();
  63240. if (!this._physicsEngine) {
  63241. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  63242. }
  63243. else {
  63244. //set the object's quaternion, if not set
  63245. if (!this.object.rotationQuaternion) {
  63246. if (this.object.rotation) {
  63247. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  63248. }
  63249. else {
  63250. this.object.rotationQuaternion = new BABYLON.Quaternion();
  63251. }
  63252. }
  63253. //default options params
  63254. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  63255. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  63256. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  63257. this._joints = [];
  63258. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  63259. if (!this.object.parent) {
  63260. this._init();
  63261. }
  63262. else if (this.object.parent.physicsImpostor) {
  63263. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  63264. }
  63265. }
  63266. }
  63267. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  63268. get: function () {
  63269. return this._isDisposed;
  63270. },
  63271. enumerable: true,
  63272. configurable: true
  63273. });
  63274. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  63275. get: function () {
  63276. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  63277. },
  63278. set: function (value) {
  63279. this.setMass(value);
  63280. },
  63281. enumerable: true,
  63282. configurable: true
  63283. });
  63284. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  63285. get: function () {
  63286. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  63287. },
  63288. set: function (value) {
  63289. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  63290. },
  63291. enumerable: true,
  63292. configurable: true
  63293. });
  63294. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  63295. get: function () {
  63296. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  63297. },
  63298. set: function (value) {
  63299. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  63300. },
  63301. enumerable: true,
  63302. configurable: true
  63303. });
  63304. /**
  63305. * This function will completly initialize this impostor.
  63306. * It will create a new body - but only if this mesh has no parent.
  63307. * If it has, this impostor will not be used other than to define the impostor
  63308. * of the child mesh.
  63309. */
  63310. PhysicsImpostor.prototype._init = function () {
  63311. this._physicsEngine.removeImpostor(this);
  63312. this.physicsBody = null;
  63313. this._parent = this._parent || this._getPhysicsParent();
  63314. if (!this.parent) {
  63315. this._physicsEngine.addImpostor(this);
  63316. }
  63317. };
  63318. PhysicsImpostor.prototype._getPhysicsParent = function () {
  63319. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  63320. var parentMesh = this.object.parent;
  63321. return parentMesh.physicsImpostor;
  63322. }
  63323. return;
  63324. };
  63325. /**
  63326. * Should a new body be generated.
  63327. */
  63328. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  63329. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  63330. };
  63331. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  63332. this.forceUpdate();
  63333. };
  63334. /**
  63335. * Force a regeneration of this or the parent's impostor's body.
  63336. * Use under cautious - This will remove all joints already implemented.
  63337. */
  63338. PhysicsImpostor.prototype.forceUpdate = function () {
  63339. this._init();
  63340. if (this.parent) {
  63341. this.parent.forceUpdate();
  63342. }
  63343. };
  63344. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  63345. /*public get mesh(): AbstractMesh {
  63346. return this._mesh;
  63347. }*/
  63348. /**
  63349. * Gets the body that holds this impostor. Either its own, or its parent.
  63350. */
  63351. get: function () {
  63352. return this._parent ? this._parent.physicsBody : this._physicsBody;
  63353. },
  63354. /**
  63355. * Set the physics body. Used mainly by the physics engine/plugin
  63356. */
  63357. set: function (physicsBody) {
  63358. if (this._physicsBody) {
  63359. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  63360. }
  63361. this._physicsBody = physicsBody;
  63362. this.resetUpdateFlags();
  63363. },
  63364. enumerable: true,
  63365. configurable: true
  63366. });
  63367. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  63368. get: function () {
  63369. return this._parent;
  63370. },
  63371. set: function (value) {
  63372. this._parent = value;
  63373. },
  63374. enumerable: true,
  63375. configurable: true
  63376. });
  63377. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  63378. this._bodyUpdateRequired = false;
  63379. };
  63380. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  63381. if (this.object.getBoundingInfo) {
  63382. var q = this.object.rotationQuaternion;
  63383. //reset rotation
  63384. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  63385. //calculate the world matrix with no rotation
  63386. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63387. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  63388. //bring back the rotation
  63389. this.object.rotationQuaternion = q;
  63390. //calculate the world matrix with the new rotation
  63391. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63392. return size;
  63393. }
  63394. else {
  63395. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  63396. }
  63397. };
  63398. PhysicsImpostor.prototype.getObjectCenter = function () {
  63399. if (this.object.getBoundingInfo) {
  63400. return this.object.getBoundingInfo().boundingBox.centerWorld;
  63401. }
  63402. else {
  63403. return this.object.position;
  63404. }
  63405. };
  63406. /**
  63407. * Get a specific parametes from the options parameter.
  63408. */
  63409. PhysicsImpostor.prototype.getParam = function (paramName) {
  63410. return this._options[paramName];
  63411. };
  63412. /**
  63413. * Sets a specific parameter in the options given to the physics plugin
  63414. */
  63415. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  63416. this._options[paramName] = value;
  63417. this._bodyUpdateRequired = true;
  63418. };
  63419. /**
  63420. * Specifically change the body's mass option. Won't recreate the physics body object
  63421. */
  63422. PhysicsImpostor.prototype.setMass = function (mass) {
  63423. if (this.getParam("mass") !== mass) {
  63424. this.setParam("mass", mass);
  63425. }
  63426. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  63427. };
  63428. PhysicsImpostor.prototype.getLinearVelocity = function () {
  63429. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  63430. };
  63431. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  63432. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  63433. };
  63434. PhysicsImpostor.prototype.getAngularVelocity = function () {
  63435. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  63436. };
  63437. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  63438. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  63439. };
  63440. /**
  63441. * Execute a function with the physics plugin native code.
  63442. * Provide a function the will have two variables - the world object and the physics body object.
  63443. */
  63444. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  63445. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  63446. };
  63447. /**
  63448. * Register a function that will be executed before the physics world is stepping forward.
  63449. */
  63450. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  63451. this._onBeforePhysicsStepCallbacks.push(func);
  63452. };
  63453. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  63454. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  63455. if (index > -1) {
  63456. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  63457. }
  63458. else {
  63459. BABYLON.Tools.Warn("Function to remove was not found");
  63460. }
  63461. };
  63462. /**
  63463. * Register a function that will be executed after the physics step
  63464. */
  63465. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  63466. this._onAfterPhysicsStepCallbacks.push(func);
  63467. };
  63468. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  63469. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  63470. if (index > -1) {
  63471. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  63472. }
  63473. else {
  63474. BABYLON.Tools.Warn("Function to remove was not found");
  63475. }
  63476. };
  63477. /**
  63478. * register a function that will be executed when this impostor collides against a different body.
  63479. */
  63480. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  63481. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63482. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  63483. };
  63484. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  63485. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63486. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  63487. if (index > -1) {
  63488. this._onPhysicsCollideCallbacks.splice(index, 1);
  63489. }
  63490. else {
  63491. BABYLON.Tools.Warn("Function to remove was not found");
  63492. }
  63493. };
  63494. /**
  63495. * Apply a force
  63496. */
  63497. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  63498. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  63499. };
  63500. /**
  63501. * Apply an impulse
  63502. */
  63503. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  63504. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  63505. };
  63506. /**
  63507. * A help function to create a joint.
  63508. */
  63509. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  63510. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  63511. this.addJoint(otherImpostor, joint);
  63512. };
  63513. /**
  63514. * Add a joint to this impostor with a different impostor.
  63515. */
  63516. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  63517. this._joints.push({
  63518. otherImpostor: otherImpostor,
  63519. joint: joint
  63520. });
  63521. this._physicsEngine.addJoint(this, otherImpostor, joint);
  63522. };
  63523. /**
  63524. * Will keep this body still, in a sleep mode.
  63525. */
  63526. PhysicsImpostor.prototype.sleep = function () {
  63527. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  63528. };
  63529. /**
  63530. * Wake the body up.
  63531. */
  63532. PhysicsImpostor.prototype.wakeUp = function () {
  63533. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  63534. };
  63535. PhysicsImpostor.prototype.clone = function (newObject) {
  63536. if (!newObject)
  63537. return null;
  63538. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  63539. };
  63540. PhysicsImpostor.prototype.dispose = function () {
  63541. var _this = this;
  63542. //no dispose if no physics engine is available.
  63543. if (!this._physicsEngine) {
  63544. return;
  63545. }
  63546. this._joints.forEach(function (j) {
  63547. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  63548. });
  63549. //dispose the physics body
  63550. this._physicsEngine.removeImpostor(this);
  63551. if (this.parent) {
  63552. this.parent.forceUpdate();
  63553. }
  63554. else {
  63555. /*this._object.getChildMeshes().forEach(function(mesh) {
  63556. if (mesh.physicsImpostor) {
  63557. if (disposeChildren) {
  63558. mesh.physicsImpostor.dispose();
  63559. mesh.physicsImpostor = null;
  63560. }
  63561. }
  63562. })*/
  63563. }
  63564. this._isDisposed = true;
  63565. };
  63566. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  63567. this._deltaPosition.copyFrom(position);
  63568. };
  63569. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  63570. if (!this._deltaRotation) {
  63571. this._deltaRotation = new BABYLON.Quaternion();
  63572. }
  63573. this._deltaRotation.copyFrom(rotation);
  63574. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  63575. };
  63576. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  63577. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  63578. };
  63579. PhysicsImpostor.prototype.getRadius = function () {
  63580. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  63581. };
  63582. /**
  63583. * Sync a bone with this impostor
  63584. * @param bone The bone to sync to the impostor.
  63585. * @param boneMesh The mesh that the bone is influencing.
  63586. * @param jointPivot The pivot of the joint / bone in local space.
  63587. * @param distToJoint Optional distance from the impostor to the joint.
  63588. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63589. */
  63590. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  63591. var tempVec = PhysicsImpostor._tmpVecs[0];
  63592. var mesh = this.object;
  63593. if (adjustRotation) {
  63594. var tempQuat = PhysicsImpostor._tmpQuat;
  63595. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  63596. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  63597. }
  63598. else {
  63599. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  63600. }
  63601. tempVec.x = 0;
  63602. tempVec.y = 0;
  63603. tempVec.z = 0;
  63604. if (jointPivot) {
  63605. tempVec.x = jointPivot.x;
  63606. tempVec.y = jointPivot.y;
  63607. tempVec.z = jointPivot.z;
  63608. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  63609. if (distToJoint === undefined || distToJoint === null) {
  63610. distToJoint = jointPivot.length();
  63611. }
  63612. tempVec.x *= distToJoint;
  63613. tempVec.y *= distToJoint;
  63614. tempVec.z *= distToJoint;
  63615. }
  63616. if (bone.getParent()) {
  63617. tempVec.addInPlace(mesh.getAbsolutePosition());
  63618. bone.setAbsolutePosition(tempVec, boneMesh);
  63619. }
  63620. else {
  63621. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  63622. boneMesh.position.x -= tempVec.x;
  63623. boneMesh.position.y -= tempVec.y;
  63624. boneMesh.position.z -= tempVec.z;
  63625. }
  63626. };
  63627. /**
  63628. * Sync impostor to a bone
  63629. * @param bone The bone that the impostor will be synced to.
  63630. * @param boneMesh The mesh that the bone is influencing.
  63631. * @param jointPivot The pivot of the joint / bone in local space.
  63632. * @param distToJoint Optional distance from the impostor to the joint.
  63633. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63634. * @param boneAxis Optional vector3 axis the bone is aligned with
  63635. */
  63636. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  63637. var mesh = this.object;
  63638. if (adjustRotation) {
  63639. var tempQuat = PhysicsImpostor._tmpQuat;
  63640. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  63641. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  63642. }
  63643. else {
  63644. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  63645. }
  63646. var pos = PhysicsImpostor._tmpVecs[0];
  63647. var boneDir = PhysicsImpostor._tmpVecs[1];
  63648. if (!boneAxis) {
  63649. boneAxis = PhysicsImpostor._tmpVecs[2];
  63650. boneAxis.x = 0;
  63651. boneAxis.y = 1;
  63652. boneAxis.z = 0;
  63653. }
  63654. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  63655. bone.getAbsolutePositionToRef(boneMesh, pos);
  63656. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  63657. distToJoint = jointPivot.length();
  63658. }
  63659. if (distToJoint !== undefined && distToJoint !== null) {
  63660. pos.x += boneDir.x * distToJoint;
  63661. pos.y += boneDir.y * distToJoint;
  63662. pos.z += boneDir.z * distToJoint;
  63663. }
  63664. mesh.setAbsolutePosition(pos);
  63665. };
  63666. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  63667. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  63668. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63669. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  63670. //Impostor types
  63671. PhysicsImpostor.NoImpostor = 0;
  63672. PhysicsImpostor.SphereImpostor = 1;
  63673. PhysicsImpostor.BoxImpostor = 2;
  63674. PhysicsImpostor.PlaneImpostor = 3;
  63675. PhysicsImpostor.MeshImpostor = 4;
  63676. PhysicsImpostor.CylinderImpostor = 7;
  63677. PhysicsImpostor.ParticleImpostor = 8;
  63678. PhysicsImpostor.HeightmapImpostor = 9;
  63679. return PhysicsImpostor;
  63680. }());
  63681. BABYLON.PhysicsImpostor = PhysicsImpostor;
  63682. })(BABYLON || (BABYLON = {}));
  63683. //# sourceMappingURL=babylon.physicsImpostor.js.map
  63684. var BABYLON;
  63685. (function (BABYLON) {
  63686. var PhysicsEngine = (function () {
  63687. function PhysicsEngine(gravity, _physicsPlugin) {
  63688. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  63689. this._physicsPlugin = _physicsPlugin;
  63690. //new methods and parameters
  63691. this._impostors = [];
  63692. this._joints = [];
  63693. if (!this._physicsPlugin.isSupported()) {
  63694. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  63695. + "Please make sure it is included.");
  63696. }
  63697. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  63698. this.setGravity(gravity);
  63699. this.setTimeStep();
  63700. }
  63701. PhysicsEngine.prototype.setGravity = function (gravity) {
  63702. this.gravity = gravity;
  63703. this._physicsPlugin.setGravity(this.gravity);
  63704. };
  63705. /**
  63706. * Set the time step of the physics engine.
  63707. * default is 1/60.
  63708. * To slow it down, enter 1/600 for example.
  63709. * To speed it up, 1/30
  63710. * @param {number} newTimeStep the new timestep to apply to this world.
  63711. */
  63712. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  63713. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  63714. this._physicsPlugin.setTimeStep(newTimeStep);
  63715. };
  63716. /**
  63717. * Get the time step of the physics engine.
  63718. */
  63719. PhysicsEngine.prototype.getTimeStep = function () {
  63720. return this._physicsPlugin.getTimeStep();
  63721. };
  63722. PhysicsEngine.prototype.dispose = function () {
  63723. this._impostors.forEach(function (impostor) {
  63724. impostor.dispose();
  63725. });
  63726. this._physicsPlugin.dispose();
  63727. };
  63728. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  63729. return this._physicsPlugin.name;
  63730. };
  63731. /**
  63732. * Adding a new impostor for the impostor tracking.
  63733. * This will be done by the impostor itself.
  63734. * @param {PhysicsImpostor} impostor the impostor to add
  63735. */
  63736. PhysicsEngine.prototype.addImpostor = function (impostor) {
  63737. impostor.uniqueId = this._impostors.push(impostor);
  63738. //if no parent, generate the body
  63739. if (!impostor.parent) {
  63740. this._physicsPlugin.generatePhysicsBody(impostor);
  63741. }
  63742. };
  63743. /**
  63744. * Remove an impostor from the engine.
  63745. * This impostor and its mesh will not longer be updated by the physics engine.
  63746. * @param {PhysicsImpostor} impostor the impostor to remove
  63747. */
  63748. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  63749. var index = this._impostors.indexOf(impostor);
  63750. if (index > -1) {
  63751. var removed = this._impostors.splice(index, 1);
  63752. //Is it needed?
  63753. if (removed.length) {
  63754. //this will also remove it from the world.
  63755. removed[0].physicsBody = null;
  63756. }
  63757. }
  63758. };
  63759. /**
  63760. * Add a joint to the physics engine
  63761. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  63762. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  63763. * @param {PhysicsJoint} the joint that will connect both impostors.
  63764. */
  63765. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  63766. var impostorJoint = {
  63767. mainImpostor: mainImpostor,
  63768. connectedImpostor: connectedImpostor,
  63769. joint: joint
  63770. };
  63771. joint.physicsPlugin = this._physicsPlugin;
  63772. this._joints.push(impostorJoint);
  63773. this._physicsPlugin.generateJoint(impostorJoint);
  63774. };
  63775. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  63776. var matchingJoints = this._joints.filter(function (impostorJoint) {
  63777. return (impostorJoint.connectedImpostor === connectedImpostor
  63778. && impostorJoint.joint === joint
  63779. && impostorJoint.mainImpostor === mainImpostor);
  63780. });
  63781. if (matchingJoints.length) {
  63782. this._physicsPlugin.removeJoint(matchingJoints[0]);
  63783. //TODO remove it from the list as well
  63784. }
  63785. };
  63786. /**
  63787. * Called by the scene. no need to call it.
  63788. */
  63789. PhysicsEngine.prototype._step = function (delta) {
  63790. var _this = this;
  63791. //check if any mesh has no body / requires an update
  63792. this._impostors.forEach(function (impostor) {
  63793. if (impostor.isBodyInitRequired()) {
  63794. _this._physicsPlugin.generatePhysicsBody(impostor);
  63795. }
  63796. });
  63797. if (delta > 0.1) {
  63798. delta = 0.1;
  63799. }
  63800. else if (delta <= 0) {
  63801. delta = 1.0 / 60.0;
  63802. }
  63803. this._physicsPlugin.executeStep(delta, this._impostors);
  63804. };
  63805. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  63806. return this._physicsPlugin;
  63807. };
  63808. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  63809. for (var i = 0; i < this._impostors.length; ++i) {
  63810. if (this._impostors[i].object === object) {
  63811. return this._impostors[i];
  63812. }
  63813. }
  63814. };
  63815. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  63816. for (var i = 0; i < this._impostors.length; ++i) {
  63817. if (this._impostors[i].physicsBody === body) {
  63818. return this._impostors[i];
  63819. }
  63820. }
  63821. };
  63822. // Statics
  63823. PhysicsEngine.Epsilon = 0.001;
  63824. return PhysicsEngine;
  63825. }());
  63826. BABYLON.PhysicsEngine = PhysicsEngine;
  63827. })(BABYLON || (BABYLON = {}));
  63828. //# sourceMappingURL=babylon.physicsEngine.js.map
  63829. var BABYLON;
  63830. (function (BABYLON) {
  63831. var CannonJSPlugin = (function () {
  63832. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  63833. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  63834. if (iterations === void 0) { iterations = 10; }
  63835. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  63836. this.name = "CannonJSPlugin";
  63837. this._physicsMaterials = new Array();
  63838. this._fixedTimeStep = 1 / 60;
  63839. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  63840. this._currentCollisionGroup = 2;
  63841. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  63842. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  63843. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  63844. this._tmpPosition = BABYLON.Vector3.Zero();
  63845. this._tmpQuaternion = new BABYLON.Quaternion();
  63846. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  63847. this._tmpDeltaRotation = new BABYLON.Quaternion();
  63848. this._tmpUnityRotation = new BABYLON.Quaternion();
  63849. if (!this.isSupported()) {
  63850. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  63851. return;
  63852. }
  63853. this.world = new this.BJSCANNON.World();
  63854. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  63855. this.world.solver.iterations = iterations;
  63856. }
  63857. CannonJSPlugin.prototype.setGravity = function (gravity) {
  63858. this.world.gravity.copy(gravity);
  63859. };
  63860. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  63861. this._fixedTimeStep = timeStep;
  63862. };
  63863. CannonJSPlugin.prototype.getTimeStep = function () {
  63864. return this._fixedTimeStep;
  63865. };
  63866. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  63867. // Delta is in seconds, should be provided in milliseconds
  63868. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  63869. };
  63870. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  63871. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  63872. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  63873. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  63874. };
  63875. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  63876. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  63877. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  63878. impostor.physicsBody.applyForce(impulse, worldPoint);
  63879. };
  63880. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  63881. //parent-child relationship. Does this impostor has a parent impostor?
  63882. if (impostor.parent) {
  63883. if (impostor.physicsBody) {
  63884. this.removePhysicsBody(impostor);
  63885. //TODO is that needed?
  63886. impostor.forceUpdate();
  63887. }
  63888. return;
  63889. }
  63890. //should a new body be created for this impostor?
  63891. if (impostor.isBodyInitRequired()) {
  63892. var shape = this._createShape(impostor);
  63893. //unregister events, if body is being changed
  63894. var oldBody = impostor.physicsBody;
  63895. if (oldBody) {
  63896. this.removePhysicsBody(impostor);
  63897. }
  63898. //create the body and material
  63899. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  63900. var bodyCreationObject = {
  63901. mass: impostor.getParam("mass"),
  63902. material: material
  63903. };
  63904. // A simple extend, in case native options were used.
  63905. var nativeOptions = impostor.getParam("nativeOptions");
  63906. for (var key in nativeOptions) {
  63907. if (nativeOptions.hasOwnProperty(key)) {
  63908. bodyCreationObject[key] = nativeOptions[key];
  63909. }
  63910. }
  63911. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  63912. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  63913. this.world.addEventListener("preStep", impostor.beforeStep);
  63914. this.world.addEventListener("postStep", impostor.afterStep);
  63915. impostor.physicsBody.addShape(shape);
  63916. this.world.add(impostor.physicsBody);
  63917. //try to keep the body moving in the right direction by taking old properties.
  63918. //Should be tested!
  63919. if (oldBody) {
  63920. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  63921. impostor.physicsBody[param].copy(oldBody[param]);
  63922. });
  63923. }
  63924. this._processChildMeshes(impostor);
  63925. }
  63926. //now update the body's transformation
  63927. this._updatePhysicsBodyTransformation(impostor);
  63928. };
  63929. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  63930. var _this = this;
  63931. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  63932. var currentRotation = mainImpostor.object.rotationQuaternion;
  63933. if (meshChildren.length) {
  63934. var processMesh = function (localPosition, mesh) {
  63935. var childImpostor = mesh.getPhysicsImpostor();
  63936. if (childImpostor) {
  63937. var parent = childImpostor.parent;
  63938. if (parent !== mainImpostor) {
  63939. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  63940. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  63941. if (childImpostor.physicsBody) {
  63942. _this.removePhysicsBody(childImpostor);
  63943. childImpostor.physicsBody = null;
  63944. }
  63945. childImpostor.parent = mainImpostor;
  63946. childImpostor.resetUpdateFlags();
  63947. 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));
  63948. //Add the mass of the children.
  63949. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  63950. }
  63951. }
  63952. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  63953. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  63954. };
  63955. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  63956. }
  63957. };
  63958. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  63959. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  63960. this.world.removeEventListener("preStep", impostor.beforeStep);
  63961. this.world.removeEventListener("postStep", impostor.afterStep);
  63962. this.world.remove(impostor.physicsBody);
  63963. };
  63964. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  63965. var mainBody = impostorJoint.mainImpostor.physicsBody;
  63966. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  63967. if (!mainBody || !connectedBody) {
  63968. return;
  63969. }
  63970. var constraint;
  63971. var jointData = impostorJoint.joint.jointData;
  63972. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  63973. var constraintData = {
  63974. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  63975. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  63976. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  63977. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  63978. maxForce: jointData.nativeParams.maxForce,
  63979. collideConnected: !!jointData.collision
  63980. };
  63981. switch (impostorJoint.joint.type) {
  63982. case BABYLON.PhysicsJoint.HingeJoint:
  63983. case BABYLON.PhysicsJoint.Hinge2Joint:
  63984. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  63985. break;
  63986. case BABYLON.PhysicsJoint.DistanceJoint:
  63987. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  63988. break;
  63989. case BABYLON.PhysicsJoint.SpringJoint:
  63990. var springData = jointData;
  63991. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  63992. restLength: springData.length,
  63993. stiffness: springData.stiffness,
  63994. damping: springData.damping,
  63995. localAnchorA: constraintData.pivotA,
  63996. localAnchorB: constraintData.pivotB
  63997. });
  63998. break;
  63999. case BABYLON.PhysicsJoint.LockJoint:
  64000. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  64001. break;
  64002. case BABYLON.PhysicsJoint.PointToPointJoint:
  64003. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64004. default:
  64005. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  64006. break;
  64007. }
  64008. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  64009. constraint.collideConnected = !!jointData.collision;
  64010. impostorJoint.joint.physicsJoint = constraint;
  64011. //don't add spring as constraint, as it is not one.
  64012. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  64013. this.world.addConstraint(constraint);
  64014. }
  64015. else {
  64016. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  64017. constraint.applyForce();
  64018. });
  64019. }
  64020. };
  64021. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  64022. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  64023. };
  64024. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  64025. var index;
  64026. var mat;
  64027. for (index = 0; index < this._physicsMaterials.length; index++) {
  64028. mat = this._physicsMaterials[index];
  64029. if (mat.friction === friction && mat.restitution === restitution) {
  64030. return mat;
  64031. }
  64032. }
  64033. var currentMat = new this.BJSCANNON.Material(name);
  64034. currentMat.friction = friction;
  64035. currentMat.restitution = restitution;
  64036. this._physicsMaterials.push(currentMat);
  64037. return currentMat;
  64038. };
  64039. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  64040. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  64041. };
  64042. CannonJSPlugin.prototype._createShape = function (impostor) {
  64043. var object = impostor.object;
  64044. var returnValue;
  64045. var extendSize = impostor.getObjectExtendSize();
  64046. switch (impostor.type) {
  64047. case BABYLON.PhysicsImpostor.SphereImpostor:
  64048. var radiusX = extendSize.x;
  64049. var radiusY = extendSize.y;
  64050. var radiusZ = extendSize.z;
  64051. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  64052. break;
  64053. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  64054. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64055. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  64056. break;
  64057. case BABYLON.PhysicsImpostor.BoxImpostor:
  64058. var box = extendSize.scale(0.5);
  64059. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  64060. break;
  64061. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64062. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  64063. returnValue = new this.BJSCANNON.Plane();
  64064. break;
  64065. case BABYLON.PhysicsImpostor.MeshImpostor:
  64066. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  64067. var rawFaces = object.getIndices ? object.getIndices() : [];
  64068. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  64069. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  64070. break;
  64071. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  64072. returnValue = this._createHeightmap(object);
  64073. break;
  64074. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64075. returnValue = new this.BJSCANNON.Particle();
  64076. break;
  64077. }
  64078. return returnValue;
  64079. };
  64080. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  64081. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64082. var matrix = new Array();
  64083. //For now pointDepth will not be used and will be automatically calculated.
  64084. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  64085. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  64086. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64087. var elementSize = dim * 2 / arraySize;
  64088. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64089. for (var i = 0; i < pos.length; i = i + 3) {
  64090. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  64091. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  64092. var y = pos[i + 1] + minY;
  64093. if (!matrix[x]) {
  64094. matrix[x] = [];
  64095. }
  64096. if (!matrix[x][z]) {
  64097. matrix[x][z] = y;
  64098. }
  64099. matrix[x][z] = Math.max(y, matrix[x][z]);
  64100. }
  64101. for (var x = 0; x <= arraySize; ++x) {
  64102. if (!matrix[x]) {
  64103. var loc = 1;
  64104. while (!matrix[(x + loc) % arraySize]) {
  64105. loc++;
  64106. }
  64107. matrix[x] = matrix[(x + loc) % arraySize].slice();
  64108. //console.log("missing x", x);
  64109. }
  64110. for (var z = 0; z <= arraySize; ++z) {
  64111. if (!matrix[x][z]) {
  64112. var loc = 1;
  64113. var newValue;
  64114. while (newValue === undefined) {
  64115. newValue = matrix[x][(z + loc++) % arraySize];
  64116. }
  64117. matrix[x][z] = newValue;
  64118. }
  64119. }
  64120. }
  64121. var shape = new this.BJSCANNON.Heightfield(matrix, {
  64122. elementSize: elementSize
  64123. });
  64124. //For future reference, needed for body transformation
  64125. shape.minY = minY;
  64126. return shape;
  64127. };
  64128. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  64129. var object = impostor.object;
  64130. //make sure it is updated...
  64131. object.computeWorldMatrix && object.computeWorldMatrix(true);
  64132. // The delta between the mesh position and the mesh bounding box center
  64133. var center = impostor.getObjectCenter();
  64134. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  64135. this._tmpPosition.copyFrom(center);
  64136. var quaternion = object.rotationQuaternion;
  64137. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  64138. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  64139. //-90 DEG in X, precalculated
  64140. quaternion = quaternion.multiply(this._minus90X);
  64141. //Invert! (Precalculated, 90 deg in X)
  64142. //No need to clone. this will never change.
  64143. impostor.setDeltaRotation(this._plus90X);
  64144. }
  64145. //If it is a heightfield, if should be centered.
  64146. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  64147. var mesh = object;
  64148. //calculate the correct body position:
  64149. var rotationQuaternion = mesh.rotationQuaternion;
  64150. mesh.rotationQuaternion = this._tmpUnityRotation;
  64151. mesh.computeWorldMatrix(true);
  64152. //get original center with no rotation
  64153. var c = center.clone();
  64154. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  64155. //rotation is back
  64156. mesh.rotationQuaternion = rotationQuaternion;
  64157. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  64158. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64159. mesh.setPivotMatrix(p);
  64160. mesh.computeWorldMatrix(true);
  64161. //calculate the translation
  64162. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  64163. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  64164. //add it inverted to the delta
  64165. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  64166. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64167. mesh.setPivotMatrix(oldPivot);
  64168. mesh.computeWorldMatrix(true);
  64169. }
  64170. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  64171. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  64172. this._tmpPosition.copyFrom(object.position);
  64173. }
  64174. impostor.setDeltaPosition(this._tmpDeltaPosition);
  64175. //Now update the impostor object
  64176. impostor.physicsBody.position.copy(this._tmpPosition);
  64177. impostor.physicsBody.quaternion.copy(quaternion);
  64178. };
  64179. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64180. impostor.object.position.copyFrom(impostor.physicsBody.position);
  64181. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  64182. };
  64183. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64184. impostor.physicsBody.position.copy(newPosition);
  64185. impostor.physicsBody.quaternion.copy(newRotation);
  64186. };
  64187. CannonJSPlugin.prototype.isSupported = function () {
  64188. return this.BJSCANNON !== undefined;
  64189. };
  64190. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64191. impostor.physicsBody.velocity.copy(velocity);
  64192. };
  64193. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64194. impostor.physicsBody.angularVelocity.copy(velocity);
  64195. };
  64196. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64197. var v = impostor.physicsBody.velocity;
  64198. if (!v)
  64199. return null;
  64200. return new BABYLON.Vector3(v.x, v.y, v.z);
  64201. };
  64202. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64203. var v = impostor.physicsBody.angularVelocity;
  64204. if (!v)
  64205. return null;
  64206. return new BABYLON.Vector3(v.x, v.y, v.z);
  64207. };
  64208. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64209. impostor.physicsBody.mass = mass;
  64210. impostor.physicsBody.updateMassProperties();
  64211. };
  64212. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  64213. return impostor.physicsBody.mass;
  64214. };
  64215. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  64216. return impostor.physicsBody.material.friction;
  64217. };
  64218. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64219. impostor.physicsBody.material.friction = friction;
  64220. };
  64221. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64222. return impostor.physicsBody.material.restitution;
  64223. };
  64224. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64225. impostor.physicsBody.material.restitution = restitution;
  64226. };
  64227. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  64228. impostor.physicsBody.sleep();
  64229. };
  64230. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  64231. impostor.physicsBody.wakeUp();
  64232. };
  64233. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64234. joint.physicsJoint.distance = maxDistance;
  64235. };
  64236. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  64237. if (!motorIndex) {
  64238. joint.physicsJoint.enableMotor();
  64239. }
  64240. };
  64241. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  64242. if (!motorIndex) {
  64243. joint.physicsJoint.disableMotor();
  64244. }
  64245. };
  64246. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64247. if (!motorIndex) {
  64248. joint.physicsJoint.enableMotor();
  64249. joint.physicsJoint.setMotorSpeed(speed);
  64250. if (maxForce) {
  64251. this.setLimit(joint, maxForce);
  64252. }
  64253. }
  64254. };
  64255. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  64256. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  64257. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  64258. };
  64259. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64260. var body = impostor.physicsBody;
  64261. mesh.position.x = body.position.x;
  64262. mesh.position.y = body.position.y;
  64263. mesh.position.z = body.position.z;
  64264. mesh.rotationQuaternion.x = body.quaternion.x;
  64265. mesh.rotationQuaternion.y = body.quaternion.y;
  64266. mesh.rotationQuaternion.z = body.quaternion.z;
  64267. mesh.rotationQuaternion.w = body.quaternion.w;
  64268. };
  64269. CannonJSPlugin.prototype.getRadius = function (impostor) {
  64270. var shape = impostor.physicsBody.shapes[0];
  64271. return shape.boundingSphereRadius;
  64272. };
  64273. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64274. var shape = impostor.physicsBody.shapes[0];
  64275. result.x = shape.halfExtents.x * 2;
  64276. result.y = shape.halfExtents.y * 2;
  64277. result.z = shape.halfExtents.z * 2;
  64278. };
  64279. CannonJSPlugin.prototype.dispose = function () {
  64280. };
  64281. return CannonJSPlugin;
  64282. }());
  64283. BABYLON.CannonJSPlugin = CannonJSPlugin;
  64284. })(BABYLON || (BABYLON = {}));
  64285. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  64286. var BABYLON;
  64287. (function (BABYLON) {
  64288. var OimoJSPlugin = (function () {
  64289. function OimoJSPlugin(iterations) {
  64290. this.name = "OimoJSPlugin";
  64291. this._tmpImpostorsArray = [];
  64292. this._tmpPositionVector = BABYLON.Vector3.Zero();
  64293. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  64294. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  64295. this.world.worldscale(1);
  64296. this.world.clear();
  64297. //making sure no stats are calculated
  64298. this.world.isNoStat = true;
  64299. }
  64300. OimoJSPlugin.prototype.setGravity = function (gravity) {
  64301. this.world.gravity.copy(gravity);
  64302. };
  64303. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  64304. this.world.timeStep = timeStep;
  64305. };
  64306. OimoJSPlugin.prototype.getTimeStep = function () {
  64307. return this.world.timeStep;
  64308. };
  64309. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  64310. var _this = this;
  64311. impostors.forEach(function (impostor) {
  64312. impostor.beforeStep();
  64313. });
  64314. this.world.step();
  64315. impostors.forEach(function (impostor) {
  64316. impostor.afterStep();
  64317. //update the ordered impostors array
  64318. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  64319. });
  64320. //check for collisions
  64321. var contact = this.world.contacts;
  64322. while (contact !== null) {
  64323. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  64324. contact = contact.next;
  64325. continue;
  64326. }
  64327. //is this body colliding with any other? get the impostor
  64328. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  64329. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  64330. if (!mainImpostor || !collidingImpostor) {
  64331. contact = contact.next;
  64332. continue;
  64333. }
  64334. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  64335. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  64336. contact = contact.next;
  64337. }
  64338. };
  64339. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  64340. var mass = impostor.physicsBody.massInfo.mass;
  64341. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  64342. };
  64343. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  64344. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  64345. this.applyImpulse(impostor, force, contactPoint);
  64346. };
  64347. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  64348. var _this = this;
  64349. //parent-child relationship. Does this impostor has a parent impostor?
  64350. if (impostor.parent) {
  64351. if (impostor.physicsBody) {
  64352. this.removePhysicsBody(impostor);
  64353. //TODO is that needed?
  64354. impostor.forceUpdate();
  64355. }
  64356. return;
  64357. }
  64358. if (impostor.isBodyInitRequired()) {
  64359. var bodyConfig = {
  64360. name: impostor.uniqueId,
  64361. //Oimo must have mass, also for static objects.
  64362. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  64363. size: [],
  64364. type: [],
  64365. pos: [],
  64366. rot: [],
  64367. move: impostor.getParam("mass") !== 0,
  64368. //Supporting older versions of Oimo
  64369. world: this.world
  64370. };
  64371. var impostors = [impostor];
  64372. var addToArray = function (parent) {
  64373. if (!parent.getChildMeshes)
  64374. return;
  64375. parent.getChildMeshes().forEach(function (m) {
  64376. if (m.physicsImpostor) {
  64377. impostors.push(m.physicsImpostor);
  64378. //m.physicsImpostor._init();
  64379. }
  64380. });
  64381. };
  64382. addToArray(impostor.object);
  64383. var checkWithEpsilon_1 = function (value) {
  64384. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  64385. };
  64386. impostors.forEach(function (i) {
  64387. //get the correct bounding box
  64388. var oldQuaternion = i.object.rotationQuaternion;
  64389. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  64390. x: impostor.object.rotationQuaternion.x,
  64391. y: impostor.object.rotationQuaternion.y,
  64392. z: impostor.object.rotationQuaternion.z,
  64393. s: impostor.object.rotationQuaternion.w
  64394. });
  64395. var extendSize = i.getObjectExtendSize();
  64396. if (i === impostor) {
  64397. var center = impostor.getObjectCenter();
  64398. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  64399. //Can also use Array.prototype.push.apply
  64400. bodyConfig.pos.push(center.x);
  64401. bodyConfig.pos.push(center.y);
  64402. bodyConfig.pos.push(center.z);
  64403. //tmp solution
  64404. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64405. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64406. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64407. }
  64408. else {
  64409. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  64410. bodyConfig.pos.push(localPosition.x);
  64411. bodyConfig.pos.push(localPosition.y);
  64412. bodyConfig.pos.push(localPosition.z);
  64413. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  64414. bodyConfig.rot.push(0);
  64415. bodyConfig.rot.push(0);
  64416. bodyConfig.rot.push(0);
  64417. }
  64418. // register mesh
  64419. switch (i.type) {
  64420. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64421. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  64422. case BABYLON.PhysicsImpostor.SphereImpostor:
  64423. var radiusX = extendSize.x;
  64424. var radiusY = extendSize.y;
  64425. var radiusZ = extendSize.z;
  64426. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  64427. bodyConfig.type.push('sphere');
  64428. //due to the way oimo works with compounds, add 3 times
  64429. bodyConfig.size.push(size);
  64430. bodyConfig.size.push(size);
  64431. bodyConfig.size.push(size);
  64432. break;
  64433. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64434. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  64435. var sizeY = checkWithEpsilon_1(extendSize.y);
  64436. bodyConfig.type.push('cylinder');
  64437. bodyConfig.size.push(sizeX);
  64438. bodyConfig.size.push(sizeY);
  64439. //due to the way oimo works with compounds, add one more value.
  64440. bodyConfig.size.push(sizeY);
  64441. break;
  64442. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64443. case BABYLON.PhysicsImpostor.BoxImpostor:
  64444. default:
  64445. var sizeX = checkWithEpsilon_1(extendSize.x);
  64446. var sizeY = checkWithEpsilon_1(extendSize.y);
  64447. var sizeZ = checkWithEpsilon_1(extendSize.z);
  64448. bodyConfig.type.push('box');
  64449. bodyConfig.size.push(sizeX);
  64450. bodyConfig.size.push(sizeY);
  64451. bodyConfig.size.push(sizeZ);
  64452. break;
  64453. }
  64454. //actually not needed, but hey...
  64455. i.object.rotationQuaternion = oldQuaternion;
  64456. });
  64457. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  64458. }
  64459. else {
  64460. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  64461. }
  64462. impostor.setDeltaPosition(this._tmpPositionVector);
  64463. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  64464. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  64465. };
  64466. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  64467. //impostor.physicsBody.dispose();
  64468. //Same as : (older oimo versions)
  64469. this.world.removeRigidBody(impostor.physicsBody);
  64470. };
  64471. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  64472. var mainBody = impostorJoint.mainImpostor.physicsBody;
  64473. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  64474. if (!mainBody || !connectedBody) {
  64475. return;
  64476. }
  64477. var jointData = impostorJoint.joint.jointData;
  64478. var options = jointData.nativeParams || {};
  64479. var type;
  64480. var nativeJointData = {
  64481. body1: mainBody,
  64482. body2: connectedBody,
  64483. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  64484. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  64485. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  64486. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  64487. min: options.min,
  64488. max: options.max,
  64489. collision: options.collision || jointData.collision,
  64490. spring: options.spring,
  64491. //supporting older version of Oimo
  64492. world: this.world
  64493. };
  64494. switch (impostorJoint.joint.type) {
  64495. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64496. type = "jointBall";
  64497. break;
  64498. case BABYLON.PhysicsJoint.SpringJoint:
  64499. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  64500. var springData = jointData;
  64501. nativeJointData.min = springData.length || nativeJointData.min;
  64502. //Max should also be set, just make sure it is at least min
  64503. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  64504. case BABYLON.PhysicsJoint.DistanceJoint:
  64505. type = "jointDistance";
  64506. nativeJointData.max = jointData.maxDistance;
  64507. break;
  64508. case BABYLON.PhysicsJoint.PrismaticJoint:
  64509. type = "jointPrisme";
  64510. break;
  64511. case BABYLON.PhysicsJoint.SliderJoint:
  64512. type = "jointSlide";
  64513. break;
  64514. case BABYLON.PhysicsJoint.WheelJoint:
  64515. type = "jointWheel";
  64516. break;
  64517. case BABYLON.PhysicsJoint.HingeJoint:
  64518. default:
  64519. type = "jointHinge";
  64520. break;
  64521. }
  64522. nativeJointData.type = type;
  64523. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  64524. };
  64525. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  64526. //Bug in Oimo prevents us from disposing a joint in the playground
  64527. //joint.joint.physicsJoint.dispose();
  64528. //So we will bruteforce it!
  64529. try {
  64530. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  64531. }
  64532. catch (e) {
  64533. BABYLON.Tools.Warn(e);
  64534. }
  64535. };
  64536. OimoJSPlugin.prototype.isSupported = function () {
  64537. return this.BJSOIMO !== undefined;
  64538. };
  64539. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64540. if (!impostor.physicsBody.sleeping) {
  64541. //TODO check that
  64542. if (impostor.physicsBody.shapes.next) {
  64543. var parentShape = this._getLastShape(impostor.physicsBody);
  64544. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  64545. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  64546. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  64547. }
  64548. else {
  64549. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  64550. }
  64551. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  64552. impostor.object.rotationQuaternion.normalize();
  64553. }
  64554. };
  64555. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64556. var body = impostor.physicsBody;
  64557. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  64558. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  64559. body.syncShapes();
  64560. body.awake();
  64561. };
  64562. OimoJSPlugin.prototype._getLastShape = function (body) {
  64563. var lastShape = body.shapes;
  64564. while (lastShape.next) {
  64565. lastShape = lastShape.next;
  64566. }
  64567. return lastShape;
  64568. };
  64569. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64570. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  64571. };
  64572. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64573. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  64574. };
  64575. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64576. var v = impostor.physicsBody.linearVelocity;
  64577. if (!v)
  64578. return null;
  64579. return new BABYLON.Vector3(v.x, v.y, v.z);
  64580. };
  64581. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64582. var v = impostor.physicsBody.angularVelocity;
  64583. if (!v)
  64584. return null;
  64585. return new BABYLON.Vector3(v.x, v.y, v.z);
  64586. };
  64587. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64588. var staticBody = mass === 0;
  64589. //this will actually set the body's density and not its mass.
  64590. //But this is how oimo treats the mass variable.
  64591. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  64592. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  64593. };
  64594. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  64595. return impostor.physicsBody.shapes.density;
  64596. };
  64597. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  64598. return impostor.physicsBody.shapes.friction;
  64599. };
  64600. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64601. impostor.physicsBody.shapes.friction = friction;
  64602. };
  64603. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64604. return impostor.physicsBody.shapes.restitution;
  64605. };
  64606. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64607. impostor.physicsBody.shapes.restitution = restitution;
  64608. };
  64609. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  64610. impostor.physicsBody.sleep();
  64611. };
  64612. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  64613. impostor.physicsBody.awake();
  64614. };
  64615. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64616. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  64617. if (minDistance !== void 0) {
  64618. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  64619. }
  64620. };
  64621. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64622. //TODO separate rotational and transational motors.
  64623. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64624. if (motor) {
  64625. motor.setMotor(speed, maxForce);
  64626. }
  64627. };
  64628. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  64629. //TODO separate rotational and transational motors.
  64630. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64631. if (motor) {
  64632. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  64633. }
  64634. };
  64635. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64636. var body = impostor.physicsBody;
  64637. mesh.position.x = body.position.x;
  64638. mesh.position.y = body.position.y;
  64639. mesh.position.z = body.position.z;
  64640. mesh.rotationQuaternion.x = body.orientation.x;
  64641. mesh.rotationQuaternion.y = body.orientation.y;
  64642. mesh.rotationQuaternion.z = body.orientation.z;
  64643. mesh.rotationQuaternion.w = body.orientation.s;
  64644. };
  64645. OimoJSPlugin.prototype.getRadius = function (impostor) {
  64646. return impostor.physicsBody.shapes.radius;
  64647. };
  64648. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64649. var shape = impostor.physicsBody.shapes;
  64650. result.x = shape.halfWidth * 2;
  64651. result.y = shape.halfHeight * 2;
  64652. result.z = shape.halfDepth * 2;
  64653. };
  64654. OimoJSPlugin.prototype.dispose = function () {
  64655. this.world.clear();
  64656. };
  64657. return OimoJSPlugin;
  64658. }());
  64659. BABYLON.OimoJSPlugin = OimoJSPlugin;
  64660. })(BABYLON || (BABYLON = {}));
  64661. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  64662. var BABYLON;
  64663. (function (BABYLON) {
  64664. var Internals;
  64665. (function (Internals) {
  64666. /*
  64667. * Based on jsTGALoader - Javascript loader for TGA file
  64668. * By Vincent Thibault
  64669. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  64670. */
  64671. var TGATools = (function () {
  64672. function TGATools() {
  64673. }
  64674. TGATools.GetTGAHeader = function (data) {
  64675. var offset = 0;
  64676. var header = {
  64677. id_length: data[offset++],
  64678. colormap_type: data[offset++],
  64679. image_type: data[offset++],
  64680. colormap_index: data[offset++] | data[offset++] << 8,
  64681. colormap_length: data[offset++] | data[offset++] << 8,
  64682. colormap_size: data[offset++],
  64683. origin: [
  64684. data[offset++] | data[offset++] << 8,
  64685. data[offset++] | data[offset++] << 8
  64686. ],
  64687. width: data[offset++] | data[offset++] << 8,
  64688. height: data[offset++] | data[offset++] << 8,
  64689. pixel_size: data[offset++],
  64690. flags: data[offset++]
  64691. };
  64692. return header;
  64693. };
  64694. TGATools.UploadContent = function (gl, data) {
  64695. // Not enough data to contain header ?
  64696. if (data.length < 19) {
  64697. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  64698. return;
  64699. }
  64700. // Read Header
  64701. var offset = 18;
  64702. var header = TGATools.GetTGAHeader(data);
  64703. // Assume it's a valid Targa file.
  64704. if (header.id_length + offset > data.length) {
  64705. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  64706. return;
  64707. }
  64708. // Skip not needed data
  64709. offset += header.id_length;
  64710. var use_rle = false;
  64711. var use_pal = false;
  64712. var use_rgb = false;
  64713. var use_grey = false;
  64714. // Get some informations.
  64715. switch (header.image_type) {
  64716. case TGATools._TYPE_RLE_INDEXED:
  64717. use_rle = true;
  64718. case TGATools._TYPE_INDEXED:
  64719. use_pal = true;
  64720. break;
  64721. case TGATools._TYPE_RLE_RGB:
  64722. use_rle = true;
  64723. case TGATools._TYPE_RGB:
  64724. use_rgb = true;
  64725. break;
  64726. case TGATools._TYPE_RLE_GREY:
  64727. use_rle = true;
  64728. case TGATools._TYPE_GREY:
  64729. use_grey = true;
  64730. break;
  64731. }
  64732. var pixel_data;
  64733. var numAlphaBits = header.flags & 0xf;
  64734. var pixel_size = header.pixel_size >> 3;
  64735. var pixel_total = header.width * header.height * pixel_size;
  64736. // Read palettes
  64737. var palettes;
  64738. if (use_pal) {
  64739. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  64740. }
  64741. // Read LRE
  64742. if (use_rle) {
  64743. pixel_data = new Uint8Array(pixel_total);
  64744. var c, count, i;
  64745. var localOffset = 0;
  64746. var pixels = new Uint8Array(pixel_size);
  64747. while (offset < pixel_total && localOffset < pixel_total) {
  64748. c = data[offset++];
  64749. count = (c & 0x7f) + 1;
  64750. // RLE pixels
  64751. if (c & 0x80) {
  64752. // Bind pixel tmp array
  64753. for (i = 0; i < pixel_size; ++i) {
  64754. pixels[i] = data[offset++];
  64755. }
  64756. // Copy pixel array
  64757. for (i = 0; i < count; ++i) {
  64758. pixel_data.set(pixels, localOffset + i * pixel_size);
  64759. }
  64760. localOffset += pixel_size * count;
  64761. }
  64762. else {
  64763. count *= pixel_size;
  64764. for (i = 0; i < count; ++i) {
  64765. pixel_data[localOffset + i] = data[offset++];
  64766. }
  64767. localOffset += count;
  64768. }
  64769. }
  64770. }
  64771. else {
  64772. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  64773. }
  64774. // Load to texture
  64775. var x_start, y_start, x_step, y_step, y_end, x_end;
  64776. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  64777. default:
  64778. case TGATools._ORIGIN_UL:
  64779. x_start = 0;
  64780. x_step = 1;
  64781. x_end = header.width;
  64782. y_start = 0;
  64783. y_step = 1;
  64784. y_end = header.height;
  64785. break;
  64786. case TGATools._ORIGIN_BL:
  64787. x_start = 0;
  64788. x_step = 1;
  64789. x_end = header.width;
  64790. y_start = header.height - 1;
  64791. y_step = -1;
  64792. y_end = -1;
  64793. break;
  64794. case TGATools._ORIGIN_UR:
  64795. x_start = header.width - 1;
  64796. x_step = -1;
  64797. x_end = -1;
  64798. y_start = 0;
  64799. y_step = 1;
  64800. y_end = header.height;
  64801. break;
  64802. case TGATools._ORIGIN_BR:
  64803. x_start = header.width - 1;
  64804. x_step = -1;
  64805. x_end = -1;
  64806. y_start = header.height - 1;
  64807. y_step = -1;
  64808. y_end = -1;
  64809. break;
  64810. }
  64811. // Load the specify method
  64812. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  64813. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  64814. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  64815. };
  64816. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64817. var image = pixel_data, colormap = palettes;
  64818. var width = header.width, height = header.height;
  64819. var color, i = 0, x, y;
  64820. var imageData = new Uint8Array(width * height * 4);
  64821. for (y = y_start; y !== y_end; y += y_step) {
  64822. for (x = x_start; x !== x_end; x += x_step, i++) {
  64823. color = image[i];
  64824. imageData[(x + width * y) * 4 + 3] = 255;
  64825. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  64826. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  64827. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  64828. }
  64829. }
  64830. return imageData;
  64831. };
  64832. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64833. var image = pixel_data;
  64834. var width = header.width, height = header.height;
  64835. var color, i = 0, x, y;
  64836. var imageData = new Uint8Array(width * height * 4);
  64837. for (y = y_start; y !== y_end; y += y_step) {
  64838. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  64839. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  64840. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  64841. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  64842. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  64843. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  64844. }
  64845. }
  64846. return imageData;
  64847. };
  64848. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64849. var image = pixel_data;
  64850. var width = header.width, height = header.height;
  64851. var i = 0, x, y;
  64852. var imageData = new Uint8Array(width * height * 4);
  64853. for (y = y_start; y !== y_end; y += y_step) {
  64854. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  64855. imageData[(x + width * y) * 4 + 3] = 255;
  64856. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64857. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  64858. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  64859. }
  64860. }
  64861. return imageData;
  64862. };
  64863. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64864. var image = pixel_data;
  64865. var width = header.width, height = header.height;
  64866. var i = 0, x, y;
  64867. var imageData = new Uint8Array(width * height * 4);
  64868. for (y = y_start; y !== y_end; y += y_step) {
  64869. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  64870. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64871. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  64872. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  64873. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  64874. }
  64875. }
  64876. return imageData;
  64877. };
  64878. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64879. var image = pixel_data;
  64880. var width = header.width, height = header.height;
  64881. var color, i = 0, x, y;
  64882. var imageData = new Uint8Array(width * height * 4);
  64883. for (y = y_start; y !== y_end; y += y_step) {
  64884. for (x = x_start; x !== x_end; x += x_step, i++) {
  64885. color = image[i];
  64886. imageData[(x + width * y) * 4 + 0] = color;
  64887. imageData[(x + width * y) * 4 + 1] = color;
  64888. imageData[(x + width * y) * 4 + 2] = color;
  64889. imageData[(x + width * y) * 4 + 3] = 255;
  64890. }
  64891. }
  64892. return imageData;
  64893. };
  64894. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64895. var image = pixel_data;
  64896. var width = header.width, height = header.height;
  64897. var i = 0, x, y;
  64898. var imageData = new Uint8Array(width * height * 4);
  64899. for (y = y_start; y !== y_end; y += y_step) {
  64900. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  64901. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  64902. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  64903. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64904. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  64905. }
  64906. }
  64907. return imageData;
  64908. };
  64909. TGATools._TYPE_NO_DATA = 0;
  64910. TGATools._TYPE_INDEXED = 1;
  64911. TGATools._TYPE_RGB = 2;
  64912. TGATools._TYPE_GREY = 3;
  64913. TGATools._TYPE_RLE_INDEXED = 9;
  64914. TGATools._TYPE_RLE_RGB = 10;
  64915. TGATools._TYPE_RLE_GREY = 11;
  64916. TGATools._ORIGIN_MASK = 0x30;
  64917. TGATools._ORIGIN_SHIFT = 0x04;
  64918. TGATools._ORIGIN_BL = 0x00;
  64919. TGATools._ORIGIN_BR = 0x01;
  64920. TGATools._ORIGIN_UL = 0x02;
  64921. TGATools._ORIGIN_UR = 0x03;
  64922. return TGATools;
  64923. }());
  64924. Internals.TGATools = TGATools;
  64925. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64926. })(BABYLON || (BABYLON = {}));
  64927. //# sourceMappingURL=babylon.tga.js.map
  64928. var BABYLON;
  64929. (function (BABYLON) {
  64930. var Internals;
  64931. (function (Internals) {
  64932. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  64933. // All values and structures referenced from:
  64934. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  64935. var DDS_MAGIC = 0x20534444;
  64936. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  64937. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  64938. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  64939. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  64940. function FourCCToInt32(value) {
  64941. return value.charCodeAt(0) +
  64942. (value.charCodeAt(1) << 8) +
  64943. (value.charCodeAt(2) << 16) +
  64944. (value.charCodeAt(3) << 24);
  64945. }
  64946. function Int32ToFourCC(value) {
  64947. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  64948. }
  64949. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  64950. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  64951. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  64952. var FOURCC_DX10 = FourCCToInt32("DX10");
  64953. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  64954. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  64955. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  64956. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  64957. var headerLengthInt = 31; // The header length in 32 bit ints
  64958. // Offsets into the header array
  64959. var off_magic = 0;
  64960. var off_size = 1;
  64961. var off_flags = 2;
  64962. var off_height = 3;
  64963. var off_width = 4;
  64964. var off_mipmapCount = 7;
  64965. var off_pfFlags = 20;
  64966. var off_pfFourCC = 21;
  64967. var off_RGBbpp = 22;
  64968. var off_RMask = 23;
  64969. var off_GMask = 24;
  64970. var off_BMask = 25;
  64971. var off_AMask = 26;
  64972. var off_caps1 = 27;
  64973. var off_caps2 = 28;
  64974. var off_caps3 = 29;
  64975. var off_caps4 = 30;
  64976. var off_dxgiFormat = 32;
  64977. ;
  64978. var DDSTools = (function () {
  64979. function DDSTools() {
  64980. }
  64981. DDSTools.GetDDSInfo = function (arrayBuffer) {
  64982. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  64983. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  64984. var mipmapCount = 1;
  64985. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  64986. mipmapCount = Math.max(1, header[off_mipmapCount]);
  64987. }
  64988. var fourCC = header[off_pfFourCC];
  64989. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  64990. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64991. switch (fourCC) {
  64992. case FOURCC_D3DFMT_R16G16B16A16F:
  64993. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64994. break;
  64995. case FOURCC_D3DFMT_R32G32B32A32F:
  64996. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64997. break;
  64998. case FOURCC_DX10:
  64999. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  65000. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65001. break;
  65002. }
  65003. }
  65004. return {
  65005. width: header[off_width],
  65006. height: header[off_height],
  65007. mipmapCount: mipmapCount,
  65008. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  65009. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  65010. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  65011. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  65012. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  65013. dxgiFormat: dxgiFormat,
  65014. textureType: textureType
  65015. };
  65016. };
  65017. DDSTools._ToHalfFloat = function (value) {
  65018. if (!DDSTools._FloatView) {
  65019. DDSTools._FloatView = new Float32Array(1);
  65020. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  65021. }
  65022. DDSTools._FloatView[0] = value;
  65023. var x = DDSTools._Int32View[0];
  65024. var bits = (x >> 16) & 0x8000; /* Get the sign */
  65025. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  65026. var e = (x >> 23) & 0xff; /* Using int is faster here */
  65027. /* If zero, or denormal, or exponent underflows too much for a denormal
  65028. * half, return signed zero. */
  65029. if (e < 103) {
  65030. return bits;
  65031. }
  65032. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  65033. if (e > 142) {
  65034. bits |= 0x7c00;
  65035. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  65036. * not Inf, so make sure we set one mantissa bit too. */
  65037. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  65038. return bits;
  65039. }
  65040. /* If exponent underflows but not too much, return a denormal */
  65041. if (e < 113) {
  65042. m |= 0x0800;
  65043. /* Extra rounding may overflow and set mantissa to 0 and exponent
  65044. * to 1, which is OK. */
  65045. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  65046. return bits;
  65047. }
  65048. bits |= ((e - 112) << 10) | (m >> 1);
  65049. bits += m & 1;
  65050. return bits;
  65051. };
  65052. DDSTools._FromHalfFloat = function (value) {
  65053. var s = (value & 0x8000) >> 15;
  65054. var e = (value & 0x7C00) >> 10;
  65055. var f = value & 0x03FF;
  65056. if (e === 0) {
  65057. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  65058. }
  65059. else if (e == 0x1F) {
  65060. return f ? NaN : ((s ? -1 : 1) * Infinity);
  65061. }
  65062. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  65063. };
  65064. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65065. var destArray = new Float32Array(dataLength);
  65066. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65067. var index = 0;
  65068. for (var y = 0; y < height; y++) {
  65069. for (var x = 0; x < width; x++) {
  65070. var srcPos = (x + y * width) * 4;
  65071. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  65072. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  65073. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  65074. if (DDSTools.StoreLODInAlphaChannel) {
  65075. destArray[index + 3] = lod;
  65076. }
  65077. else {
  65078. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  65079. }
  65080. index += 4;
  65081. }
  65082. }
  65083. return destArray;
  65084. };
  65085. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65086. if (DDSTools.StoreLODInAlphaChannel) {
  65087. var destArray = new Uint16Array(dataLength);
  65088. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65089. var index = 0;
  65090. for (var y = 0; y < height; y++) {
  65091. for (var x = 0; x < width; x++) {
  65092. var srcPos = (x + y * width) * 4;
  65093. destArray[index] = srcData[srcPos];
  65094. destArray[index + 1] = srcData[srcPos + 1];
  65095. destArray[index + 2] = srcData[srcPos + 2];
  65096. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  65097. index += 4;
  65098. }
  65099. }
  65100. return destArray;
  65101. }
  65102. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  65103. };
  65104. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65105. if (DDSTools.StoreLODInAlphaChannel) {
  65106. var destArray = new Float32Array(dataLength);
  65107. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65108. var index = 0;
  65109. for (var y = 0; y < height; y++) {
  65110. for (var x = 0; x < width; x++) {
  65111. var srcPos = (x + y * width) * 4;
  65112. destArray[index] = srcData[srcPos];
  65113. destArray[index + 1] = srcData[srcPos + 1];
  65114. destArray[index + 2] = srcData[srcPos + 2];
  65115. destArray[index + 3] = lod;
  65116. index += 4;
  65117. }
  65118. }
  65119. return destArray;
  65120. }
  65121. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  65122. };
  65123. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65124. var destArray = new Uint8Array(dataLength);
  65125. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65126. var index = 0;
  65127. for (var y = 0; y < height; y++) {
  65128. for (var x = 0; x < width; x++) {
  65129. var srcPos = (x + y * width) * 4;
  65130. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  65131. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  65132. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  65133. if (DDSTools.StoreLODInAlphaChannel) {
  65134. destArray[index + 3] = lod;
  65135. }
  65136. else {
  65137. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  65138. }
  65139. index += 4;
  65140. }
  65141. }
  65142. return destArray;
  65143. };
  65144. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65145. var destArray = new Uint8Array(dataLength);
  65146. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65147. var index = 0;
  65148. for (var y = 0; y < height; y++) {
  65149. for (var x = 0; x < width; x++) {
  65150. var srcPos = (x + y * width) * 4;
  65151. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  65152. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  65153. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  65154. if (DDSTools.StoreLODInAlphaChannel) {
  65155. destArray[index + 3] = lod;
  65156. }
  65157. else {
  65158. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  65159. }
  65160. index += 4;
  65161. }
  65162. }
  65163. return destArray;
  65164. };
  65165. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65166. var byteArray = new Uint8Array(dataLength);
  65167. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65168. var index = 0;
  65169. for (var y = 0; y < height; y++) {
  65170. for (var x = 0; x < width; x++) {
  65171. var srcPos = (x + y * width) * 4;
  65172. byteArray[index] = srcData[srcPos + 2];
  65173. byteArray[index + 1] = srcData[srcPos + 1];
  65174. byteArray[index + 2] = srcData[srcPos];
  65175. byteArray[index + 3] = srcData[srcPos + 3];
  65176. index += 4;
  65177. }
  65178. }
  65179. return byteArray;
  65180. };
  65181. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65182. var byteArray = new Uint8Array(dataLength);
  65183. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65184. var index = 0;
  65185. for (var y = 0; y < height; y++) {
  65186. for (var x = 0; x < width; x++) {
  65187. var srcPos = (x + y * width) * 3;
  65188. byteArray[index] = srcData[srcPos + 2];
  65189. byteArray[index + 1] = srcData[srcPos + 1];
  65190. byteArray[index + 2] = srcData[srcPos];
  65191. index += 3;
  65192. }
  65193. }
  65194. return byteArray;
  65195. };
  65196. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65197. var byteArray = new Uint8Array(dataLength);
  65198. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65199. var index = 0;
  65200. for (var y = 0; y < height; y++) {
  65201. for (var x = 0; x < width; x++) {
  65202. var srcPos = (x + y * width);
  65203. byteArray[index] = srcData[srcPos];
  65204. index++;
  65205. }
  65206. }
  65207. return byteArray;
  65208. };
  65209. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  65210. if (lodIndex === void 0) { lodIndex = -1; }
  65211. var ext = engine.getCaps().s3tc;
  65212. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  65213. if (header[off_magic] != DDS_MAGIC) {
  65214. BABYLON.Tools.Error("Invalid magic number in DDS header");
  65215. return;
  65216. }
  65217. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  65218. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  65219. return;
  65220. }
  65221. if (info.isCompressed && !ext) {
  65222. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  65223. return;
  65224. }
  65225. var bpp = header[off_RGBbpp];
  65226. dataOffset = header[off_size] + 4;
  65227. var computeFormats = false;
  65228. if (info.isFourCC) {
  65229. fourCC = header[off_pfFourCC];
  65230. switch (fourCC) {
  65231. case FOURCC_DXT1:
  65232. blockBytes = 8;
  65233. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  65234. break;
  65235. case FOURCC_DXT3:
  65236. blockBytes = 16;
  65237. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  65238. break;
  65239. case FOURCC_DXT5:
  65240. blockBytes = 16;
  65241. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  65242. break;
  65243. case FOURCC_D3DFMT_R16G16B16A16F:
  65244. computeFormats = true;
  65245. break;
  65246. case FOURCC_D3DFMT_R32G32B32A32F:
  65247. computeFormats = true;
  65248. break;
  65249. case FOURCC_DX10:
  65250. // There is an additionnal header so dataOffset need to be changed
  65251. dataOffset += 5 * 4; // 5 uints
  65252. var supported = false;
  65253. switch (info.dxgiFormat) {
  65254. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  65255. computeFormats = true;
  65256. supported = true;
  65257. break;
  65258. case DXGI_FORMAT_B8G8R8X8_UNORM:
  65259. info.isRGB = true;
  65260. info.isFourCC = false;
  65261. bpp = 32;
  65262. supported = true;
  65263. break;
  65264. }
  65265. if (supported) {
  65266. break;
  65267. }
  65268. default:
  65269. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  65270. return;
  65271. }
  65272. }
  65273. if (computeFormats) {
  65274. format = engine._getWebGLTextureType(info.textureType);
  65275. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65276. }
  65277. mipmapCount = 1;
  65278. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  65279. mipmapCount = Math.max(1, header[off_mipmapCount]);
  65280. }
  65281. for (var face = 0; face < faces; face++) {
  65282. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65283. width = header[off_width];
  65284. height = header[off_height];
  65285. for (mip = 0; mip < mipmapCount; ++mip) {
  65286. if (lodIndex === -1 || lodIndex === mip) {
  65287. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  65288. var i = (lodIndex === -1) ? mip : 0;
  65289. if (!info.isCompressed && info.isFourCC) {
  65290. dataLength = width * height * 4;
  65291. var floatArray;
  65292. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  65293. if (bpp === 128) {
  65294. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65295. }
  65296. else if (bpp === 64) {
  65297. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65298. }
  65299. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65300. format = engine._getWebGLTextureType(info.textureType);
  65301. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65302. }
  65303. else {
  65304. if (bpp === 128) {
  65305. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65306. }
  65307. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  65308. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65309. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65310. format = engine._getWebGLTextureType(info.textureType);
  65311. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65312. }
  65313. else {
  65314. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65315. }
  65316. }
  65317. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  65318. }
  65319. else if (info.isRGB) {
  65320. if (bpp === 24) {
  65321. dataLength = width * height * 3;
  65322. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65323. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  65324. }
  65325. else {
  65326. dataLength = width * height * 4;
  65327. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65328. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  65329. }
  65330. }
  65331. else if (info.isLuminance) {
  65332. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  65333. var unpaddedRowSize = width;
  65334. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  65335. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  65336. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65337. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  65338. }
  65339. else {
  65340. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  65341. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  65342. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  65343. }
  65344. }
  65345. dataOffset += width * height * (bpp / 8);
  65346. width *= 0.5;
  65347. height *= 0.5;
  65348. width = Math.max(1.0, width);
  65349. height = Math.max(1.0, height);
  65350. }
  65351. }
  65352. };
  65353. DDSTools.StoreLODInAlphaChannel = false;
  65354. return DDSTools;
  65355. }());
  65356. Internals.DDSTools = DDSTools;
  65357. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65358. })(BABYLON || (BABYLON = {}));
  65359. //# sourceMappingURL=babylon.dds.js.map
  65360. var BABYLON;
  65361. (function (BABYLON) {
  65362. var Internals;
  65363. (function (Internals) {
  65364. /**
  65365. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  65366. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  65367. */
  65368. var KhronosTextureContainer = (function () {
  65369. /**
  65370. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  65371. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  65372. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  65373. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  65374. */
  65375. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  65376. this.arrayBuffer = arrayBuffer;
  65377. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  65378. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  65379. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  65380. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  65381. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  65382. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  65383. BABYLON.Tools.Error("texture missing KTX identifier");
  65384. return;
  65385. }
  65386. // load the reset of the header in native 32 bit int
  65387. var header = new Int32Array(this.arrayBuffer, 12, 13);
  65388. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  65389. var oppositeEndianess = header[0] === 0x01020304;
  65390. // read all the header elements in order they exist in the file, without modification (sans endainness)
  65391. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  65392. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  65393. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  65394. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  65395. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  65396. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  65397. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  65398. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  65399. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  65400. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  65401. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  65402. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  65403. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  65404. if (this.glType !== 0) {
  65405. BABYLON.Tools.Error("only compressed formats currently supported");
  65406. return;
  65407. }
  65408. else {
  65409. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  65410. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  65411. }
  65412. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  65413. BABYLON.Tools.Error("only 2D textures currently supported");
  65414. return;
  65415. }
  65416. if (this.numberOfArrayElements !== 0) {
  65417. BABYLON.Tools.Error("texture arrays not currently supported");
  65418. return;
  65419. }
  65420. if (this.numberOfFaces !== facesExpected) {
  65421. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  65422. return;
  65423. }
  65424. // we now have a completely validated file, so could use existence of loadType as success
  65425. // would need to make this more elaborate & adjust checks above to support more than one load type
  65426. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  65427. }
  65428. // not as fast hardware based, but will probably never need to use
  65429. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  65430. return ((val & 0xFF) << 24)
  65431. | ((val & 0xFF00) << 8)
  65432. | ((val >> 8) & 0xFF00)
  65433. | ((val >> 24) & 0xFF);
  65434. };
  65435. /**
  65436. * It is assumed that the texture has already been created & is currently bound
  65437. */
  65438. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  65439. switch (this.loadType) {
  65440. case KhronosTextureContainer.COMPRESSED_2D:
  65441. this._upload2DCompressedLevels(gl, loadMipmaps);
  65442. break;
  65443. case KhronosTextureContainer.TEX_2D:
  65444. case KhronosTextureContainer.COMPRESSED_3D:
  65445. case KhronosTextureContainer.TEX_3D:
  65446. }
  65447. };
  65448. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  65449. // initialize width & height for level 1
  65450. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  65451. var width = this.pixelWidth;
  65452. var height = this.pixelHeight;
  65453. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  65454. for (var level = 0; level < mipmapCount; level++) {
  65455. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  65456. for (var face = 0; face < this.numberOfFaces; face++) {
  65457. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65458. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  65459. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  65460. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  65461. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  65462. }
  65463. width = Math.max(1.0, width * 0.5);
  65464. height = Math.max(1.0, height * 0.5);
  65465. }
  65466. };
  65467. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  65468. // load types
  65469. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  65470. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  65471. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  65472. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  65473. return KhronosTextureContainer;
  65474. }());
  65475. Internals.KhronosTextureContainer = KhronosTextureContainer;
  65476. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65477. })(BABYLON || (BABYLON = {}));
  65478. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  65479. var BABYLON;
  65480. (function (BABYLON) {
  65481. var DynamicFloatArrayElementInfo = (function () {
  65482. function DynamicFloatArrayElementInfo() {
  65483. }
  65484. return DynamicFloatArrayElementInfo;
  65485. }());
  65486. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  65487. /**
  65488. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  65489. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  65490. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  65491. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  65492. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  65493. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  65494. */
  65495. var DynamicFloatArray = (function () {
  65496. /**
  65497. * Construct an instance of the dynamic float array
  65498. * @param stride size of one element in float (i.e. not bytes!)
  65499. * @param initialElementCount the number of available entries at construction
  65500. */
  65501. function DynamicFloatArray(stride, initialElementCount) {
  65502. this.compareValueOffset = null;
  65503. this.sortingAscending = true;
  65504. this._stride = stride;
  65505. this.buffer = new Float32Array(stride * initialElementCount);
  65506. this._lastUsed = 0;
  65507. this._firstFree = 0;
  65508. this._allEntries = new Array(initialElementCount);
  65509. this._freeEntries = new Array(initialElementCount);
  65510. for (var i = 0; i < initialElementCount; i++) {
  65511. var element = new DynamicFloatArrayElementInfo();
  65512. element.offset = i * stride;
  65513. this._allEntries[i] = element;
  65514. this._freeEntries[initialElementCount - i - 1] = element;
  65515. }
  65516. }
  65517. /**
  65518. * Allocate an element in the array.
  65519. * @return the element info instance that contains the offset into the main buffer of the element's location.
  65520. * Beware, this offset may change when you call pack()
  65521. */
  65522. DynamicFloatArray.prototype.allocElement = function () {
  65523. if (this._freeEntries.length === 0) {
  65524. this._growBuffer();
  65525. }
  65526. var el = this._freeEntries.pop();
  65527. this._lastUsed = Math.max(el.offset, this._lastUsed);
  65528. if (el.offset === this._firstFree) {
  65529. if (this._freeEntries.length > 0) {
  65530. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  65531. }
  65532. else {
  65533. this._firstFree += this._stride;
  65534. }
  65535. }
  65536. return el;
  65537. };
  65538. /**
  65539. * Free the element corresponding to the given element info
  65540. * @param elInfo the element that describe the allocated element
  65541. */
  65542. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  65543. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  65544. this._freeEntries.push(elInfo);
  65545. };
  65546. /**
  65547. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  65548. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  65549. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  65550. */
  65551. DynamicFloatArray.prototype.pack = function () {
  65552. // no free slot? no need to pack
  65553. if (this._freeEntries.length === 0) {
  65554. return this.buffer;
  65555. }
  65556. // If the buffer is already packed the last used will always be lower than the first free
  65557. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  65558. if (this._lastUsed < this._firstFree) {
  65559. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  65560. return elementsBuffer_1;
  65561. }
  65562. var s = this._stride;
  65563. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  65564. var lastFree = new DynamicFloatArrayElementInfo();
  65565. lastFree.offset = this.totalElementCount * s;
  65566. this._freeEntries.push(lastFree);
  65567. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  65568. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  65569. var firstFreeSlotOffset = sortedFree[0].offset;
  65570. var freeZoneSize = 1;
  65571. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  65572. var prevOffset = sortedFree[0].offset;
  65573. for (var i = 1; i < sortedFree.length; i++) {
  65574. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  65575. if (firstFreeSlotOffset >= occupiedZoneSize) {
  65576. break;
  65577. }
  65578. var curFree = sortedFree[i];
  65579. var curOffset = curFree.offset;
  65580. // Compute the distance between this offset and the previous
  65581. var distance = curOffset - prevOffset;
  65582. // If the distance is the stride size, they are adjacent, it good, move to the next
  65583. if (distance === s) {
  65584. // Free zone is one element bigger
  65585. ++freeZoneSize;
  65586. // as we're about to iterate to the next, the cur becomes the previous...
  65587. prevOffset = curOffset;
  65588. continue;
  65589. }
  65590. // Distance is bigger, which means there's x element between the previous free and this one
  65591. var usedRange = (distance / s) - 1;
  65592. // Two cases the free zone is smaller than the data to move or bigger
  65593. // Copy what can fit in the free zone
  65594. var curMoveOffset = curOffset - s;
  65595. var copyCount = Math.min(freeZoneSize, usedRange);
  65596. for (var j = 0; j < copyCount; j++) {
  65597. var freeI = firstFreeSlotOffset / s;
  65598. var curI = curMoveOffset / s;
  65599. var moveEl = sortedAll[curI];
  65600. this._moveElement(moveEl, firstFreeSlotOffset);
  65601. var replacedEl = sortedAll[freeI];
  65602. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  65603. replacedEl.offset = curMoveOffset;
  65604. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  65605. sortedAll[freeI] = moveEl;
  65606. sortedAll[curI] = replacedEl;
  65607. curMoveOffset -= s;
  65608. firstFreeSlotOffset += s;
  65609. }
  65610. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  65611. if (freeZoneSize <= usedRange) {
  65612. firstFreeSlotOffset = curMoveOffset + s;
  65613. freeZoneSize = 1 + copyCount;
  65614. }
  65615. else {
  65616. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  65617. }
  65618. // as we're about to iterate to the next, the cur becomes the previous...
  65619. prevOffset = curOffset;
  65620. }
  65621. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  65622. this._lastUsed = firstFreeSlotOffset - s;
  65623. this._firstFree = firstFreeSlotOffset;
  65624. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  65625. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  65626. this._allEntries = sortedAll;
  65627. return elementsBuffer;
  65628. };
  65629. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  65630. for (var i = 0; i < this._stride; i++) {
  65631. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  65632. }
  65633. element.offset = destOffset;
  65634. };
  65635. DynamicFloatArray.prototype._growBuffer = function () {
  65636. // Allocate the new buffer with 50% more entries, copy the content of the current one
  65637. var newElCount = Math.floor(this.totalElementCount * 1.5);
  65638. var newBuffer = new Float32Array(newElCount * this._stride);
  65639. newBuffer.set(this.buffer);
  65640. var curCount = this.totalElementCount;
  65641. var addedCount = newElCount - this.totalElementCount;
  65642. for (var i = 0; i < addedCount; i++) {
  65643. var element = new DynamicFloatArrayElementInfo();
  65644. element.offset = (curCount + i) * this.stride;
  65645. this._allEntries.push(element);
  65646. this._freeEntries[addedCount - i - 1] = element;
  65647. }
  65648. this._firstFree = curCount * this.stride;
  65649. this.buffer = newBuffer;
  65650. };
  65651. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  65652. /**
  65653. * Get the total count of entries that can fit in the current buffer
  65654. * @returns the elements count
  65655. */
  65656. get: function () {
  65657. return this._allEntries.length;
  65658. },
  65659. enumerable: true,
  65660. configurable: true
  65661. });
  65662. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  65663. /**
  65664. * Get the count of free entries that can still be allocated without resizing the buffer
  65665. * @returns the free elements count
  65666. */
  65667. get: function () {
  65668. return this._freeEntries.length;
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  65674. /**
  65675. * Get the count of allocated elements
  65676. * @returns the allocated elements count
  65677. */
  65678. get: function () {
  65679. return this._allEntries.length - this._freeEntries.length;
  65680. },
  65681. enumerable: true,
  65682. configurable: true
  65683. });
  65684. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  65685. /**
  65686. * Return the size of one element in float
  65687. * @returns the size in float
  65688. */
  65689. get: function () {
  65690. return this._stride;
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. DynamicFloatArray.prototype.sort = function () {
  65696. var _this = this;
  65697. if (!this.compareValueOffset) {
  65698. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  65699. }
  65700. var count = this.usedElementCount;
  65701. // Do we have to (re)create the sort table?
  65702. if (!this._sortTable || this._sortTable.length < count) {
  65703. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  65704. var newCount = Math.min(this.totalElementCount, count * 2);
  65705. this._sortTable = new Array(newCount);
  65706. }
  65707. if (!this._sortedTable || this._sortedTable.length !== count) {
  65708. this._sortedTable = new Array(count);
  65709. }
  65710. // Because, you know...
  65711. this.pack();
  65712. //let stride = this.stride;
  65713. //for (let i = 0; i < count; i++) {
  65714. // let si = this._sortTable[i];
  65715. // if (!si) {
  65716. // si = new SortInfo();
  65717. // this._sortTable[i] = si;
  65718. // }
  65719. // si.entry = this._allEntries[i];
  65720. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  65721. // si.swapedOffset = null;
  65722. // this._sortedTable[i] = si;
  65723. //}
  65724. var curOffset = 0;
  65725. var stride = this.stride;
  65726. for (var i = 0; i < count; i++, curOffset += stride) {
  65727. var si = this._sortTable[i];
  65728. if (!si) {
  65729. si = new SortInfo();
  65730. this._sortTable[i] = si;
  65731. }
  65732. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  65733. si.offset = curOffset;
  65734. si.swapedOffset = null;
  65735. this._sortedTable[i] = si;
  65736. }
  65737. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  65738. if (this.sortingAscending) {
  65739. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  65740. }
  65741. else {
  65742. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  65743. }
  65744. var swapElements = function (src, dst) {
  65745. for (var i = 0; i < stride; i++) {
  65746. var tps = _this.buffer[dst + i];
  65747. _this.buffer[dst + i] = _this.buffer[src + i];
  65748. _this.buffer[src + i] = tps;
  65749. }
  65750. };
  65751. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  65752. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  65753. // and I still want something with a good algorithm complexity.
  65754. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  65755. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  65756. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  65757. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  65758. // until we find a SortInfo object without a swapedOffset which means we got the right location
  65759. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  65760. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  65761. for (var i = 0; i < count; i++) {
  65762. // Get the element to move
  65763. var sourceSI = this._sortedTable[i];
  65764. var destSI = this._sortTable[i];
  65765. var sourceOff = sourceSI.offset;
  65766. // If the source changed location, find the new one
  65767. if (sourceSI.swapedOffset) {
  65768. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  65769. var curSI = sourceSI;
  65770. while (curSI.swapedOffset) {
  65771. curSI = this._sortTable[curSI.swapedOffset / stride];
  65772. }
  65773. // Finally get the right location
  65774. sourceOff = curSI.offset;
  65775. }
  65776. // Tag the element being replaced with its new location
  65777. destSI.swapedOffset = sourceOff;
  65778. // Swap elements (only if needed)
  65779. if (sourceOff !== destSI.offset) {
  65780. swapElements(sourceOff, destSI.offset);
  65781. }
  65782. // Update the offset in the corresponding DFAE
  65783. //sourceSI.entry.offset = destSI.entry.offset;
  65784. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  65785. }
  65786. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  65787. return true;
  65788. };
  65789. return DynamicFloatArray;
  65790. }());
  65791. BABYLON.DynamicFloatArray = DynamicFloatArray;
  65792. var SortInfo = (function () {
  65793. function SortInfo() {
  65794. this.compareData = this.offset = this.swapedOffset = null;
  65795. }
  65796. return SortInfo;
  65797. }());
  65798. })(BABYLON || (BABYLON = {}));
  65799. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  65800. var BABYLON;
  65801. (function (BABYLON) {
  65802. var Debug;
  65803. (function (Debug) {
  65804. /**
  65805. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  65806. */
  65807. var SkeletonViewer = (function () {
  65808. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  65809. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65810. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65811. this.skeleton = skeleton;
  65812. this.mesh = mesh;
  65813. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65814. this.renderingGroupId = renderingGroupId;
  65815. this.color = BABYLON.Color3.White();
  65816. this._debugLines = new Array();
  65817. this._isEnabled = false;
  65818. this._scene = scene;
  65819. this.update();
  65820. this._renderFunction = this.update.bind(this);
  65821. }
  65822. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65823. get: function () {
  65824. return this._isEnabled;
  65825. },
  65826. set: function (value) {
  65827. if (this._isEnabled === value) {
  65828. return;
  65829. }
  65830. this._isEnabled = value;
  65831. if (value) {
  65832. this._scene.registerBeforeRender(this._renderFunction);
  65833. }
  65834. else {
  65835. this._scene.unregisterBeforeRender(this._renderFunction);
  65836. }
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65842. if (x === void 0) { x = 0; }
  65843. if (y === void 0) { y = 0; }
  65844. if (z === void 0) { z = 0; }
  65845. var tmat = BABYLON.Tmp.Matrix[0];
  65846. var parentBone = bone.getParent();
  65847. tmat.copyFrom(bone.getLocalMatrix());
  65848. if (x !== 0 || y !== 0 || z !== 0) {
  65849. var tmat2 = BABYLON.Tmp.Matrix[1];
  65850. BABYLON.Matrix.IdentityToRef(tmat2);
  65851. tmat2.m[12] = x;
  65852. tmat2.m[13] = y;
  65853. tmat2.m[14] = z;
  65854. tmat2.multiplyToRef(tmat, tmat);
  65855. }
  65856. if (parentBone) {
  65857. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65858. }
  65859. tmat.multiplyToRef(meshMat, tmat);
  65860. position.x = tmat.m[12];
  65861. position.y = tmat.m[13];
  65862. position.z = tmat.m[14];
  65863. };
  65864. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65865. var len = bones.length;
  65866. var meshPos = this.mesh.position;
  65867. for (var i = 0; i < len; i++) {
  65868. var bone = bones[i];
  65869. var points = this._debugLines[i];
  65870. if (!points) {
  65871. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65872. this._debugLines[i] = points;
  65873. }
  65874. this._getBonePosition(points[0], bone, meshMat);
  65875. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65876. points[0].subtractInPlace(meshPos);
  65877. points[1].subtractInPlace(meshPos);
  65878. }
  65879. };
  65880. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65881. var len = bones.length;
  65882. var boneNum = 0;
  65883. var meshPos = this.mesh.position;
  65884. for (var i = len - 1; i >= 0; i--) {
  65885. var childBone = bones[i];
  65886. var parentBone = childBone.getParent();
  65887. if (!parentBone) {
  65888. continue;
  65889. }
  65890. var points = this._debugLines[boneNum];
  65891. if (!points) {
  65892. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65893. this._debugLines[boneNum] = points;
  65894. }
  65895. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65896. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65897. points[0].subtractInPlace(meshPos);
  65898. points[1].subtractInPlace(meshPos);
  65899. boneNum++;
  65900. }
  65901. };
  65902. SkeletonViewer.prototype.update = function () {
  65903. if (this.autoUpdateBonesMatrices) {
  65904. this.skeleton.computeAbsoluteTransforms();
  65905. }
  65906. if (this.skeleton.bones[0].length === undefined) {
  65907. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65908. }
  65909. else {
  65910. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65911. }
  65912. if (!this._debugMesh) {
  65913. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  65914. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65915. }
  65916. else {
  65917. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65918. }
  65919. this._debugMesh.position.copyFrom(this.mesh.position);
  65920. this._debugMesh.color = this.color;
  65921. };
  65922. SkeletonViewer.prototype.dispose = function () {
  65923. if (this._debugMesh) {
  65924. this.isEnabled = false;
  65925. this._debugMesh.dispose();
  65926. this._debugMesh = null;
  65927. }
  65928. };
  65929. return SkeletonViewer;
  65930. }());
  65931. Debug.SkeletonViewer = SkeletonViewer;
  65932. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65933. })(BABYLON || (BABYLON = {}));
  65934. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65935. var BABYLON;
  65936. (function (BABYLON) {
  65937. var Debug;
  65938. (function (Debug) {
  65939. var AxesViewer = (function () {
  65940. function AxesViewer(scene, scaleLines) {
  65941. if (scaleLines === void 0) { scaleLines = 1; }
  65942. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65943. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65944. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65945. this.scaleLines = 1;
  65946. this.scaleLines = scaleLines;
  65947. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65948. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65949. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65950. this._xmesh.renderingGroupId = 2;
  65951. this._ymesh.renderingGroupId = 2;
  65952. this._zmesh.renderingGroupId = 2;
  65953. this._xmesh.material.checkReadyOnlyOnce = true;
  65954. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65955. this._ymesh.material.checkReadyOnlyOnce = true;
  65956. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65957. this._zmesh.material.checkReadyOnlyOnce = true;
  65958. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65959. this.scene = scene;
  65960. }
  65961. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65962. var scaleLines = this.scaleLines;
  65963. this._xmesh.position.copyFrom(position);
  65964. this._ymesh.position.copyFrom(position);
  65965. this._zmesh.position.copyFrom(position);
  65966. var point2 = this._xline[1];
  65967. point2.x = xaxis.x * scaleLines;
  65968. point2.y = xaxis.y * scaleLines;
  65969. point2.z = xaxis.z * scaleLines;
  65970. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  65971. point2 = this._yline[1];
  65972. point2.x = yaxis.x * scaleLines;
  65973. point2.y = yaxis.y * scaleLines;
  65974. point2.z = yaxis.z * scaleLines;
  65975. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  65976. point2 = this._zline[1];
  65977. point2.x = zaxis.x * scaleLines;
  65978. point2.y = zaxis.y * scaleLines;
  65979. point2.z = zaxis.z * scaleLines;
  65980. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  65981. };
  65982. AxesViewer.prototype.dispose = function () {
  65983. if (this._xmesh) {
  65984. this._xmesh.dispose();
  65985. this._ymesh.dispose();
  65986. this._zmesh.dispose();
  65987. this._xmesh = null;
  65988. this._ymesh = null;
  65989. this._zmesh = null;
  65990. this._xline = null;
  65991. this._yline = null;
  65992. this._zline = null;
  65993. this.scene = null;
  65994. }
  65995. };
  65996. return AxesViewer;
  65997. }());
  65998. Debug.AxesViewer = AxesViewer;
  65999. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66000. })(BABYLON || (BABYLON = {}));
  66001. //# sourceMappingURL=babylon.axesViewer.js.map
  66002. var BABYLON;
  66003. (function (BABYLON) {
  66004. var Debug;
  66005. (function (Debug) {
  66006. var BoneAxesViewer = (function (_super) {
  66007. __extends(BoneAxesViewer, _super);
  66008. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  66009. if (scaleLines === void 0) { scaleLines = 1; }
  66010. var _this = _super.call(this, scene, scaleLines) || this;
  66011. _this.pos = BABYLON.Vector3.Zero();
  66012. _this.xaxis = BABYLON.Vector3.Zero();
  66013. _this.yaxis = BABYLON.Vector3.Zero();
  66014. _this.zaxis = BABYLON.Vector3.Zero();
  66015. _this.mesh = mesh;
  66016. _this.bone = bone;
  66017. return _this;
  66018. }
  66019. BoneAxesViewer.prototype.update = function () {
  66020. var bone = this.bone;
  66021. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  66022. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  66023. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  66024. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  66025. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  66026. };
  66027. BoneAxesViewer.prototype.dispose = function () {
  66028. if (this.pos) {
  66029. this.pos = null;
  66030. this.xaxis = null;
  66031. this.yaxis = null;
  66032. this.zaxis = null;
  66033. this.mesh = null;
  66034. this.bone = null;
  66035. _super.prototype.dispose.call(this);
  66036. }
  66037. };
  66038. return BoneAxesViewer;
  66039. }(Debug.AxesViewer));
  66040. Debug.BoneAxesViewer = BoneAxesViewer;
  66041. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66042. })(BABYLON || (BABYLON = {}));
  66043. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66044. var BABYLON;
  66045. (function (BABYLON) {
  66046. var RayHelper = (function () {
  66047. function RayHelper(ray) {
  66048. this.ray = ray;
  66049. }
  66050. RayHelper.CreateAndShow = function (ray, scene, color) {
  66051. var helper = new RayHelper(ray);
  66052. helper.show(scene, color);
  66053. return helper;
  66054. };
  66055. RayHelper.prototype.show = function (scene, color) {
  66056. if (!this._renderFunction) {
  66057. var ray = this.ray;
  66058. this._renderFunction = this._render.bind(this);
  66059. this._scene = scene;
  66060. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66061. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66062. this._scene.registerBeforeRender(this._renderFunction);
  66063. }
  66064. if (color) {
  66065. this._renderLine.color.copyFrom(color);
  66066. }
  66067. };
  66068. RayHelper.prototype.hide = function () {
  66069. if (this._renderFunction) {
  66070. this._scene.unregisterBeforeRender(this._renderFunction);
  66071. this._scene = null;
  66072. this._renderFunction = null;
  66073. this._renderLine.dispose();
  66074. this._renderLine = null;
  66075. this._renderPoints = null;
  66076. }
  66077. };
  66078. RayHelper.prototype._render = function () {
  66079. var ray = this.ray;
  66080. var point = this._renderPoints[1];
  66081. var len = Math.min(ray.length, 1000000);
  66082. point.copyFrom(ray.direction);
  66083. point.scaleInPlace(len);
  66084. point.addInPlace(ray.origin);
  66085. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66086. };
  66087. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66088. this._attachedToMesh = mesh;
  66089. var ray = this.ray;
  66090. if (!ray.direction) {
  66091. ray.direction = BABYLON.Vector3.Zero();
  66092. }
  66093. if (!ray.origin) {
  66094. ray.origin = BABYLON.Vector3.Zero();
  66095. }
  66096. if (length) {
  66097. ray.length = length;
  66098. }
  66099. if (!meshSpaceOrigin) {
  66100. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66101. }
  66102. if (!meshSpaceDirection) {
  66103. // -1 so that this will work with Mesh.lookAt
  66104. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66105. }
  66106. if (!this._meshSpaceDirection) {
  66107. this._meshSpaceDirection = meshSpaceDirection.clone();
  66108. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66109. }
  66110. else {
  66111. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66112. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66113. }
  66114. if (!this._updateToMeshFunction) {
  66115. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66116. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66117. }
  66118. this._updateToMesh();
  66119. };
  66120. RayHelper.prototype.detachFromMesh = function () {
  66121. if (this._attachedToMesh) {
  66122. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66123. this._attachedToMesh = null;
  66124. this._updateToMeshFunction = null;
  66125. }
  66126. };
  66127. RayHelper.prototype._updateToMesh = function () {
  66128. var ray = this.ray;
  66129. if (this._attachedToMesh._isDisposed) {
  66130. this.detachFromMesh();
  66131. return;
  66132. }
  66133. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66134. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66135. };
  66136. RayHelper.prototype.dispose = function () {
  66137. this.hide();
  66138. this.detachFromMesh();
  66139. this.ray = null;
  66140. };
  66141. return RayHelper;
  66142. }());
  66143. BABYLON.RayHelper = RayHelper;
  66144. })(BABYLON || (BABYLON = {}));
  66145. //# sourceMappingURL=babylon.rayHelper.js.map
  66146. var BABYLON;
  66147. (function (BABYLON) {
  66148. var DebugLayer = (function () {
  66149. function DebugLayer(scene) {
  66150. this._scene = scene;
  66151. }
  66152. /** Creates the inspector window. */
  66153. DebugLayer.prototype._createInspector = function (config) {
  66154. if (config === void 0) { config = {}; }
  66155. var popup = config.popup || false;
  66156. var initialTab = config.initialTab || 0;
  66157. var parentElement = config.parentElement || null;
  66158. if (!this._inspector) {
  66159. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66160. } // else nothing to do,; instance is already existing
  66161. };
  66162. DebugLayer.prototype.isVisible = function () {
  66163. if (!this._inspector) {
  66164. return false;
  66165. }
  66166. return true;
  66167. };
  66168. DebugLayer.prototype.hide = function () {
  66169. if (this._inspector) {
  66170. try {
  66171. this._inspector.dispose();
  66172. }
  66173. catch (e) {
  66174. // If the inspector has been removed directly from the inspector tool
  66175. }
  66176. this._inspector = null;
  66177. }
  66178. };
  66179. DebugLayer.prototype.show = function (config) {
  66180. if (config === void 0) { config = {}; }
  66181. if (typeof INSPECTOR == 'undefined') {
  66182. // Load inspector and add it to the DOM
  66183. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66184. }
  66185. else {
  66186. // Otherwise creates the inspector
  66187. this._createInspector(config);
  66188. }
  66189. };
  66190. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66191. return DebugLayer;
  66192. }());
  66193. BABYLON.DebugLayer = DebugLayer;
  66194. })(BABYLON || (BABYLON = {}));
  66195. //# sourceMappingURL=babylon.debugLayer.js.map
  66196. var BABYLON;
  66197. (function (BABYLON) {
  66198. var Debug;
  66199. (function (Debug) {
  66200. var PhysicsViewer = (function () {
  66201. function PhysicsViewer(scene) {
  66202. this._impostors = [];
  66203. this._meshes = [];
  66204. this._numMeshes = 0;
  66205. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66206. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  66207. }
  66208. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66209. var plugin = this._physicsEnginePlugin;
  66210. for (var i = 0; i < this._numMeshes; i++) {
  66211. if (this._impostors[i].isDisposed) {
  66212. this.hideImpostor(this._impostors[i--]);
  66213. }
  66214. else {
  66215. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  66216. }
  66217. }
  66218. };
  66219. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66220. for (var i = 0; i < this._numMeshes; i++) {
  66221. if (this._impostors[i] == impostor) {
  66222. return;
  66223. }
  66224. }
  66225. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66226. if (debugMesh) {
  66227. this._impostors[this._numMeshes] = impostor;
  66228. this._meshes[this._numMeshes] = debugMesh;
  66229. if (this._numMeshes === 0) {
  66230. this._renderFunction = this._updateDebugMeshes.bind(this);
  66231. this._scene.registerBeforeRender(this._renderFunction);
  66232. }
  66233. this._numMeshes++;
  66234. }
  66235. };
  66236. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66237. var removed = false;
  66238. for (var i = 0; i < this._numMeshes; i++) {
  66239. if (this._impostors[i] == impostor) {
  66240. this._scene.removeMesh(this._meshes[i]);
  66241. this._meshes[i].dispose();
  66242. this._numMeshes--;
  66243. if (this._numMeshes > 0) {
  66244. this._meshes[i] = this._meshes[this._numMeshes];
  66245. this._impostors[i] = this._impostors[this._numMeshes];
  66246. this._meshes[this._numMeshes] = null;
  66247. this._impostors[this._numMeshes] = null;
  66248. }
  66249. else {
  66250. this._meshes[0] = null;
  66251. this._impostors[0] = null;
  66252. }
  66253. removed = true;
  66254. break;
  66255. }
  66256. }
  66257. if (removed && this._numMeshes === 0) {
  66258. this._scene.unregisterBeforeRender(this._renderFunction);
  66259. }
  66260. };
  66261. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66262. if (!this._debugMaterial) {
  66263. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66264. this._debugMaterial.wireframe = true;
  66265. }
  66266. return this._debugMaterial;
  66267. };
  66268. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66269. if (!this._debugBoxMesh) {
  66270. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66271. this._debugBoxMesh.renderingGroupId = 1;
  66272. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66273. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66274. scene.removeMesh(this._debugBoxMesh);
  66275. }
  66276. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66277. };
  66278. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66279. if (!this._debugSphereMesh) {
  66280. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66281. this._debugSphereMesh.renderingGroupId = 1;
  66282. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66283. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66284. scene.removeMesh(this._debugSphereMesh);
  66285. }
  66286. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66287. };
  66288. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66289. var body = impostor.physicsBody;
  66290. var shape = body.shapes[0];
  66291. var mesh;
  66292. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66293. mesh = this._getDebugBoxMesh(scene);
  66294. impostor.getBoxSizeToRef(mesh.scaling);
  66295. }
  66296. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66297. mesh = this._getDebugSphereMesh(scene);
  66298. var radius = impostor.getRadius();
  66299. mesh.scaling.x = radius * 2;
  66300. mesh.scaling.y = radius * 2;
  66301. mesh.scaling.z = radius * 2;
  66302. }
  66303. return mesh;
  66304. };
  66305. PhysicsViewer.prototype.dispose = function () {
  66306. for (var i = 0; i < this._numMeshes; i++) {
  66307. this.hideImpostor(this._impostors[i]);
  66308. }
  66309. if (this._debugBoxMesh) {
  66310. this._debugBoxMesh.dispose();
  66311. }
  66312. if (this._debugSphereMesh) {
  66313. this._debugSphereMesh.dispose();
  66314. }
  66315. if (this._debugMaterial) {
  66316. this._debugMaterial.dispose();
  66317. }
  66318. this._impostors.length = 0;
  66319. this._scene = null;
  66320. this._physicsEnginePlugin = null;
  66321. };
  66322. return PhysicsViewer;
  66323. }());
  66324. Debug.PhysicsViewer = PhysicsViewer;
  66325. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66326. })(BABYLON || (BABYLON = {}));
  66327. //# sourceMappingURL=babylon.physicsViewer.js.map
  66328. var BABYLON;
  66329. (function (BABYLON) {
  66330. var BoundingBoxRenderer = (function () {
  66331. function BoundingBoxRenderer(scene) {
  66332. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66333. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66334. this.showBackLines = true;
  66335. this.renderList = new BABYLON.SmartArray(32);
  66336. this._vertexBuffers = {};
  66337. this._scene = scene;
  66338. }
  66339. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66340. if (this._colorShader) {
  66341. return;
  66342. }
  66343. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  66344. attributes: [BABYLON.VertexBuffer.PositionKind],
  66345. uniforms: ["world", "viewProjection", "color"]
  66346. });
  66347. var engine = this._scene.getEngine();
  66348. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66349. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66350. this._createIndexBuffer();
  66351. };
  66352. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66353. var engine = this._scene.getEngine();
  66354. 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]);
  66355. };
  66356. BoundingBoxRenderer.prototype._rebuild = function () {
  66357. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  66358. this._createIndexBuffer();
  66359. };
  66360. BoundingBoxRenderer.prototype.reset = function () {
  66361. this.renderList.reset();
  66362. };
  66363. BoundingBoxRenderer.prototype.render = function () {
  66364. if (this.renderList.length === 0) {
  66365. return;
  66366. }
  66367. this._prepareRessources();
  66368. if (!this._colorShader.isReady()) {
  66369. return;
  66370. }
  66371. var engine = this._scene.getEngine();
  66372. engine.setDepthWrite(false);
  66373. this._colorShader._preBind();
  66374. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66375. var boundingBox = this.renderList.data[boundingBoxIndex];
  66376. var min = boundingBox.minimum;
  66377. var max = boundingBox.maximum;
  66378. var diff = max.subtract(min);
  66379. var median = min.add(diff.scale(0.5));
  66380. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66381. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66382. .multiply(boundingBox.getWorldMatrix());
  66383. // VBOs
  66384. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66385. if (this.showBackLines) {
  66386. // Back
  66387. engine.setDepthFunctionToGreaterOrEqual();
  66388. this._scene.resetCachedMaterial();
  66389. this._colorShader.setColor4("color", this.backColor.toColor4());
  66390. this._colorShader.bind(worldMatrix);
  66391. // Draw order
  66392. engine.draw(false, 0, 24);
  66393. }
  66394. // Front
  66395. engine.setDepthFunctionToLess();
  66396. this._scene.resetCachedMaterial();
  66397. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66398. this._colorShader.bind(worldMatrix);
  66399. // Draw order
  66400. engine.draw(false, 0, 24);
  66401. }
  66402. this._colorShader.unbind();
  66403. engine.setDepthFunctionToLessOrEqual();
  66404. engine.setDepthWrite(true);
  66405. };
  66406. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66407. this._prepareRessources();
  66408. if (!this._colorShader.isReady()) {
  66409. return;
  66410. }
  66411. var engine = this._scene.getEngine();
  66412. engine.setDepthWrite(false);
  66413. engine.setColorWrite(false);
  66414. this._colorShader._preBind();
  66415. var boundingBox = mesh._boundingInfo.boundingBox;
  66416. var min = boundingBox.minimum;
  66417. var max = boundingBox.maximum;
  66418. var diff = max.subtract(min);
  66419. var median = min.add(diff.scale(0.5));
  66420. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66421. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66422. .multiply(boundingBox.getWorldMatrix());
  66423. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66424. engine.setDepthFunctionToLess();
  66425. this._scene.resetCachedMaterial();
  66426. this._colorShader.bind(worldMatrix);
  66427. engine.draw(false, 0, 24);
  66428. this._colorShader.unbind();
  66429. engine.setDepthFunctionToLessOrEqual();
  66430. engine.setDepthWrite(true);
  66431. engine.setColorWrite(true);
  66432. };
  66433. BoundingBoxRenderer.prototype.dispose = function () {
  66434. if (!this._colorShader) {
  66435. return;
  66436. }
  66437. this.renderList.dispose();
  66438. this._colorShader.dispose();
  66439. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66440. if (buffer) {
  66441. buffer.dispose();
  66442. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66443. }
  66444. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66445. };
  66446. return BoundingBoxRenderer;
  66447. }());
  66448. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66449. })(BABYLON || (BABYLON = {}));
  66450. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66451. var BABYLON;
  66452. (function (BABYLON) {
  66453. var MorphTarget = (function () {
  66454. function MorphTarget(name, influence) {
  66455. if (influence === void 0) { influence = 0; }
  66456. this.name = name;
  66457. this.animations = new Array();
  66458. this.onInfluenceChanged = new BABYLON.Observable();
  66459. this.influence = influence;
  66460. }
  66461. Object.defineProperty(MorphTarget.prototype, "influence", {
  66462. get: function () {
  66463. return this._influence;
  66464. },
  66465. set: function (influence) {
  66466. if (this._influence === influence) {
  66467. return;
  66468. }
  66469. var previous = this._influence;
  66470. this._influence = influence;
  66471. if (this.onInfluenceChanged.hasObservers) {
  66472. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  66473. }
  66474. },
  66475. enumerable: true,
  66476. configurable: true
  66477. });
  66478. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  66479. get: function () {
  66480. return this._normals !== undefined;
  66481. },
  66482. enumerable: true,
  66483. configurable: true
  66484. });
  66485. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  66486. get: function () {
  66487. return this._tangents !== undefined;
  66488. },
  66489. enumerable: true,
  66490. configurable: true
  66491. });
  66492. MorphTarget.prototype.setPositions = function (data) {
  66493. this._positions = new Float32Array(data);
  66494. };
  66495. MorphTarget.prototype.getPositions = function () {
  66496. return this._positions;
  66497. };
  66498. MorphTarget.prototype.setNormals = function (data) {
  66499. this._normals = new Float32Array(data);
  66500. };
  66501. MorphTarget.prototype.getNormals = function () {
  66502. return this._normals;
  66503. };
  66504. MorphTarget.prototype.setTangents = function (data) {
  66505. this._tangents = new Float32Array(data);
  66506. };
  66507. MorphTarget.prototype.getTangents = function () {
  66508. return this._tangents;
  66509. };
  66510. /**
  66511. * Serializes the current target into a Serialization object.
  66512. * Returns the serialized object.
  66513. */
  66514. MorphTarget.prototype.serialize = function () {
  66515. var serializationObject = {};
  66516. serializationObject.name = this.name;
  66517. serializationObject.influence = this.influence;
  66518. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  66519. if (this.hasNormals) {
  66520. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  66521. }
  66522. if (this.hasTangents) {
  66523. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  66524. }
  66525. // Animations
  66526. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  66527. return serializationObject;
  66528. };
  66529. // Statics
  66530. MorphTarget.Parse = function (serializationObject) {
  66531. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  66532. result.setPositions(serializationObject.positions);
  66533. if (serializationObject.normals) {
  66534. result.setNormals(serializationObject.normals);
  66535. }
  66536. if (serializationObject.tangents) {
  66537. result.setTangents(serializationObject.tangents);
  66538. }
  66539. // Animations
  66540. if (serializationObject.animations) {
  66541. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  66542. var parsedAnimation = serializationObject.animations[animationIndex];
  66543. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66544. }
  66545. }
  66546. return result;
  66547. };
  66548. MorphTarget.FromMesh = function (mesh, name, influence) {
  66549. if (!name) {
  66550. name = mesh.name;
  66551. }
  66552. var result = new MorphTarget(name, influence);
  66553. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66555. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  66556. }
  66557. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  66558. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  66559. }
  66560. return result;
  66561. };
  66562. return MorphTarget;
  66563. }());
  66564. BABYLON.MorphTarget = MorphTarget;
  66565. })(BABYLON || (BABYLON = {}));
  66566. //# sourceMappingURL=babylon.morphTarget.js.map
  66567. var BABYLON;
  66568. (function (BABYLON) {
  66569. var MorphTargetManager = (function () {
  66570. function MorphTargetManager(scene) {
  66571. this._targets = new Array();
  66572. this._targetObservable = new Array();
  66573. this._activeTargets = new BABYLON.SmartArray(16);
  66574. this._supportsNormals = false;
  66575. this._supportsTangents = false;
  66576. this._vertexCount = 0;
  66577. this._uniqueId = 0;
  66578. this._tempInfluences = new Array();
  66579. if (!scene) {
  66580. scene = BABYLON.Engine.LastCreatedScene;
  66581. }
  66582. this._scene = scene;
  66583. this._scene.morphTargetManagers.push(this);
  66584. this._uniqueId = scene.getUniqueId();
  66585. }
  66586. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  66587. get: function () {
  66588. return this._uniqueId;
  66589. },
  66590. enumerable: true,
  66591. configurable: true
  66592. });
  66593. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  66594. get: function () {
  66595. return this._vertexCount;
  66596. },
  66597. enumerable: true,
  66598. configurable: true
  66599. });
  66600. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  66601. get: function () {
  66602. return this._supportsNormals;
  66603. },
  66604. enumerable: true,
  66605. configurable: true
  66606. });
  66607. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  66608. get: function () {
  66609. return this._supportsTangents;
  66610. },
  66611. enumerable: true,
  66612. configurable: true
  66613. });
  66614. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  66615. get: function () {
  66616. return this._targets.length;
  66617. },
  66618. enumerable: true,
  66619. configurable: true
  66620. });
  66621. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  66622. get: function () {
  66623. return this._activeTargets.length;
  66624. },
  66625. enumerable: true,
  66626. configurable: true
  66627. });
  66628. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  66629. get: function () {
  66630. return this._influences;
  66631. },
  66632. enumerable: true,
  66633. configurable: true
  66634. });
  66635. MorphTargetManager.prototype.getActiveTarget = function (index) {
  66636. return this._activeTargets.data[index];
  66637. };
  66638. MorphTargetManager.prototype.getTarget = function (index) {
  66639. return this._targets[index];
  66640. };
  66641. MorphTargetManager.prototype.addTarget = function (target) {
  66642. var _this = this;
  66643. if (this._vertexCount) {
  66644. if (this._vertexCount !== target.getPositions().length / 3) {
  66645. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  66646. return;
  66647. }
  66648. }
  66649. this._targets.push(target);
  66650. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  66651. _this._syncActiveTargets(needUpdate);
  66652. }));
  66653. this._syncActiveTargets(true);
  66654. };
  66655. MorphTargetManager.prototype.removeTarget = function (target) {
  66656. var index = this._targets.indexOf(target);
  66657. if (index >= 0) {
  66658. this._targets.splice(index, 1);
  66659. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  66660. this._vertexCount = 0;
  66661. this._syncActiveTargets(true);
  66662. }
  66663. };
  66664. /**
  66665. * Serializes the current manager into a Serialization object.
  66666. * Returns the serialized object.
  66667. */
  66668. MorphTargetManager.prototype.serialize = function () {
  66669. var serializationObject = {};
  66670. serializationObject.id = this.uniqueId;
  66671. serializationObject.targets = [];
  66672. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66673. var target = _a[_i];
  66674. serializationObject.targets.push(target.serialize());
  66675. }
  66676. return serializationObject;
  66677. };
  66678. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  66679. this._syncActiveTargets(needUpdate);
  66680. };
  66681. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  66682. var influenceCount = 0;
  66683. this._activeTargets.reset();
  66684. this._supportsNormals = true;
  66685. this._supportsTangents = true;
  66686. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66687. var target = _a[_i];
  66688. if (target.influence > 0) {
  66689. this._activeTargets.push(target);
  66690. this._tempInfluences[influenceCount++] = target.influence;
  66691. this._supportsNormals = this._supportsNormals && target.hasNormals;
  66692. this._supportsTangents = this._supportsTangents && target.hasTangents;
  66693. if (this._vertexCount === 0) {
  66694. this._vertexCount = target.getPositions().length / 3;
  66695. }
  66696. }
  66697. }
  66698. if (!this._influences || this._influences.length !== influenceCount) {
  66699. this._influences = new Float32Array(influenceCount);
  66700. }
  66701. for (var index = 0; index < influenceCount; index++) {
  66702. this._influences[index] = this._tempInfluences[index];
  66703. }
  66704. if (needUpdate) {
  66705. // Flag meshes as dirty to resync with the active targets
  66706. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  66707. var mesh = _c[_b];
  66708. if (mesh.morphTargetManager === this) {
  66709. mesh._syncGeometryWithMorphTargetManager();
  66710. }
  66711. }
  66712. }
  66713. };
  66714. // Statics
  66715. MorphTargetManager.Parse = function (serializationObject, scene) {
  66716. var result = new MorphTargetManager(scene);
  66717. result._uniqueId = serializationObject.id;
  66718. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  66719. var targetData = _a[_i];
  66720. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  66721. }
  66722. return result;
  66723. };
  66724. return MorphTargetManager;
  66725. }());
  66726. BABYLON.MorphTargetManager = MorphTargetManager;
  66727. })(BABYLON || (BABYLON = {}));
  66728. //# sourceMappingURL=babylon.morphTargetManager.js.map
  66729. var BABYLON;
  66730. (function (BABYLON) {
  66731. var Octree = (function () {
  66732. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  66733. if (maxDepth === void 0) { maxDepth = 2; }
  66734. this.maxDepth = maxDepth;
  66735. this.dynamicContent = new Array();
  66736. this._maxBlockCapacity = maxBlockCapacity || 64;
  66737. this._selectionContent = new BABYLON.SmartArray(1024);
  66738. this._creationFunc = creationFunc;
  66739. }
  66740. // Methods
  66741. Octree.prototype.update = function (worldMin, worldMax, entries) {
  66742. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  66743. };
  66744. Octree.prototype.addMesh = function (entry) {
  66745. for (var index = 0; index < this.blocks.length; index++) {
  66746. var block = this.blocks[index];
  66747. block.addEntry(entry);
  66748. }
  66749. };
  66750. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  66751. this._selectionContent.reset();
  66752. for (var index = 0; index < this.blocks.length; index++) {
  66753. var block = this.blocks[index];
  66754. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  66755. }
  66756. if (allowDuplicate) {
  66757. this._selectionContent.concat(this.dynamicContent);
  66758. }
  66759. else {
  66760. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66761. }
  66762. return this._selectionContent;
  66763. };
  66764. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  66765. this._selectionContent.reset();
  66766. for (var index = 0; index < this.blocks.length; index++) {
  66767. var block = this.blocks[index];
  66768. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  66769. }
  66770. if (allowDuplicate) {
  66771. this._selectionContent.concat(this.dynamicContent);
  66772. }
  66773. else {
  66774. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66775. }
  66776. return this._selectionContent;
  66777. };
  66778. Octree.prototype.intersectsRay = function (ray) {
  66779. this._selectionContent.reset();
  66780. for (var index = 0; index < this.blocks.length; index++) {
  66781. var block = this.blocks[index];
  66782. block.intersectsRay(ray, this._selectionContent);
  66783. }
  66784. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66785. return this._selectionContent;
  66786. };
  66787. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  66788. target.blocks = new Array();
  66789. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  66790. // Segmenting space
  66791. for (var x = 0; x < 2; x++) {
  66792. for (var y = 0; y < 2; y++) {
  66793. for (var z = 0; z < 2; z++) {
  66794. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  66795. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  66796. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  66797. block.addEntries(entries);
  66798. target.blocks.push(block);
  66799. }
  66800. }
  66801. }
  66802. };
  66803. Octree.CreationFuncForMeshes = function (entry, block) {
  66804. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66805. block.entries.push(entry);
  66806. }
  66807. };
  66808. Octree.CreationFuncForSubMeshes = function (entry, block) {
  66809. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66810. block.entries.push(entry);
  66811. }
  66812. };
  66813. return Octree;
  66814. }());
  66815. BABYLON.Octree = Octree;
  66816. })(BABYLON || (BABYLON = {}));
  66817. //# sourceMappingURL=babylon.octree.js.map
  66818. var BABYLON;
  66819. (function (BABYLON) {
  66820. var OctreeBlock = (function () {
  66821. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  66822. this.entries = new Array();
  66823. this._boundingVectors = new Array();
  66824. this._capacity = capacity;
  66825. this._depth = depth;
  66826. this._maxDepth = maxDepth;
  66827. this._creationFunc = creationFunc;
  66828. this._minPoint = minPoint;
  66829. this._maxPoint = maxPoint;
  66830. this._boundingVectors.push(minPoint.clone());
  66831. this._boundingVectors.push(maxPoint.clone());
  66832. this._boundingVectors.push(minPoint.clone());
  66833. this._boundingVectors[2].x = maxPoint.x;
  66834. this._boundingVectors.push(minPoint.clone());
  66835. this._boundingVectors[3].y = maxPoint.y;
  66836. this._boundingVectors.push(minPoint.clone());
  66837. this._boundingVectors[4].z = maxPoint.z;
  66838. this._boundingVectors.push(maxPoint.clone());
  66839. this._boundingVectors[5].z = minPoint.z;
  66840. this._boundingVectors.push(maxPoint.clone());
  66841. this._boundingVectors[6].x = minPoint.x;
  66842. this._boundingVectors.push(maxPoint.clone());
  66843. this._boundingVectors[7].y = minPoint.y;
  66844. }
  66845. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  66846. // Property
  66847. get: function () {
  66848. return this._capacity;
  66849. },
  66850. enumerable: true,
  66851. configurable: true
  66852. });
  66853. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  66854. get: function () {
  66855. return this._minPoint;
  66856. },
  66857. enumerable: true,
  66858. configurable: true
  66859. });
  66860. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  66861. get: function () {
  66862. return this._maxPoint;
  66863. },
  66864. enumerable: true,
  66865. configurable: true
  66866. });
  66867. // Methods
  66868. OctreeBlock.prototype.addEntry = function (entry) {
  66869. if (this.blocks) {
  66870. for (var index = 0; index < this.blocks.length; index++) {
  66871. var block = this.blocks[index];
  66872. block.addEntry(entry);
  66873. }
  66874. return;
  66875. }
  66876. this._creationFunc(entry, this);
  66877. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  66878. this.createInnerBlocks();
  66879. }
  66880. };
  66881. OctreeBlock.prototype.addEntries = function (entries) {
  66882. for (var index = 0; index < entries.length; index++) {
  66883. var mesh = entries[index];
  66884. this.addEntry(mesh);
  66885. }
  66886. };
  66887. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  66888. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  66889. if (this.blocks) {
  66890. for (var index = 0; index < this.blocks.length; index++) {
  66891. var block = this.blocks[index];
  66892. block.select(frustumPlanes, selection, allowDuplicate);
  66893. }
  66894. return;
  66895. }
  66896. if (allowDuplicate) {
  66897. selection.concat(this.entries);
  66898. }
  66899. else {
  66900. selection.concatWithNoDuplicate(this.entries);
  66901. }
  66902. }
  66903. };
  66904. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  66905. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  66906. if (this.blocks) {
  66907. for (var index = 0; index < this.blocks.length; index++) {
  66908. var block = this.blocks[index];
  66909. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  66910. }
  66911. return;
  66912. }
  66913. if (allowDuplicate) {
  66914. selection.concat(this.entries);
  66915. }
  66916. else {
  66917. selection.concatWithNoDuplicate(this.entries);
  66918. }
  66919. }
  66920. };
  66921. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  66922. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  66923. if (this.blocks) {
  66924. for (var index = 0; index < this.blocks.length; index++) {
  66925. var block = this.blocks[index];
  66926. block.intersectsRay(ray, selection);
  66927. }
  66928. return;
  66929. }
  66930. selection.concatWithNoDuplicate(this.entries);
  66931. }
  66932. };
  66933. OctreeBlock.prototype.createInnerBlocks = function () {
  66934. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  66935. };
  66936. return OctreeBlock;
  66937. }());
  66938. BABYLON.OctreeBlock = OctreeBlock;
  66939. })(BABYLON || (BABYLON = {}));
  66940. //# sourceMappingURL=babylon.octreeBlock.js.map
  66941. var BABYLON;
  66942. (function (BABYLON) {
  66943. var SIMDVector3 = (function () {
  66944. function SIMDVector3() {
  66945. }
  66946. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  66947. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  66948. };
  66949. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  66950. var m = transformation.m;
  66951. var m0 = SIMD.Float32x4.load(m, 0);
  66952. var m1 = SIMD.Float32x4.load(m, 4);
  66953. var m2 = SIMD.Float32x4.load(m, 8);
  66954. var m3 = SIMD.Float32x4.load(m, 12);
  66955. 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));
  66956. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  66957. result.x = SIMD.Float32x4.extractLane(r, 0);
  66958. result.y = SIMD.Float32x4.extractLane(r, 1);
  66959. result.z = SIMD.Float32x4.extractLane(r, 2);
  66960. };
  66961. return SIMDVector3;
  66962. }());
  66963. var SIMDMatrix = (function () {
  66964. function SIMDMatrix() {
  66965. }
  66966. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  66967. var tm = this.m;
  66968. var om = other.m;
  66969. var m0 = SIMD.Float32x4.load(om, 0);
  66970. var m1 = SIMD.Float32x4.load(om, 4);
  66971. var m2 = SIMD.Float32x4.load(om, 8);
  66972. var m3 = SIMD.Float32x4.load(om, 12);
  66973. for (var i = 0; i < 16; i += 4) {
  66974. 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)))));
  66975. }
  66976. return this;
  66977. };
  66978. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  66979. var src = this.m;
  66980. var dest = other.m;
  66981. // Load the 4 rows
  66982. var src0 = SIMD.Float32x4.load(src, 0);
  66983. var src1 = SIMD.Float32x4.load(src, 4);
  66984. var src2 = SIMD.Float32x4.load(src, 8);
  66985. var src3 = SIMD.Float32x4.load(src, 12);
  66986. // Transpose the source matrix. Sort of. Not a true transpose operation
  66987. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  66988. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  66989. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  66990. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  66991. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  66992. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  66993. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  66994. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  66995. // This is a true transposition, but it will lead to an incorrect result
  66996. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  66997. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  66998. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66999. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67000. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  67001. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  67002. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  67003. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  67004. // ----
  67005. tmp1 = SIMD.Float32x4.mul(row2, row3);
  67006. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67007. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  67008. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  67009. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67010. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  67011. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  67012. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  67013. // ----
  67014. tmp1 = SIMD.Float32x4.mul(row1, row2);
  67015. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67016. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  67017. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  67018. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67019. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  67020. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  67021. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  67022. // ----
  67023. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  67024. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67025. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  67026. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  67027. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  67028. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67029. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  67030. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  67031. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  67032. // ----
  67033. tmp1 = SIMD.Float32x4.mul(row0, row1);
  67034. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67035. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67036. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  67037. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67038. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67039. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  67040. // ----
  67041. tmp1 = SIMD.Float32x4.mul(row0, row3);
  67042. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67043. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  67044. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  67045. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67046. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  67047. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  67048. // ----
  67049. tmp1 = SIMD.Float32x4.mul(row0, row2);
  67050. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67051. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  67052. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  67053. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67054. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  67055. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  67056. // Compute determinant
  67057. var det = SIMD.Float32x4.mul(row0, minor0);
  67058. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  67059. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  67060. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  67061. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  67062. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  67063. // These shuffles aren't necessary if the faulty transposition is done
  67064. // up at the top of this function.
  67065. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  67066. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  67067. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  67068. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  67069. // Compute final values by multiplying with 1/det
  67070. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  67071. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  67072. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  67073. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  67074. return this;
  67075. };
  67076. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  67077. var out = result.m;
  67078. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  67079. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  67080. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  67081. // cc.kmVec3Subtract(f, pCenter, pEye);
  67082. var f = SIMD.Float32x4.sub(center, eye);
  67083. // cc.kmVec3Normalize(f, f);
  67084. var tmp = SIMD.Float32x4.mul(f, f);
  67085. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67086. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67087. // cc.kmVec3Assign(up, pUp);
  67088. // cc.kmVec3Normalize(up, up);
  67089. tmp = SIMD.Float32x4.mul(up, up);
  67090. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67091. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67092. // cc.kmVec3Cross(s, f, up);
  67093. 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)));
  67094. // cc.kmVec3Normalize(s, s);
  67095. tmp = SIMD.Float32x4.mul(s, s);
  67096. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67097. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67098. // cc.kmVec3Cross(u, s, f);
  67099. 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)));
  67100. // cc.kmVec3Normalize(s, s);
  67101. tmp = SIMD.Float32x4.mul(s, s);
  67102. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67103. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67104. var zero = SIMD.Float32x4.splat(0.0);
  67105. s = SIMD.Float32x4.neg(s);
  67106. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  67107. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  67108. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  67109. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  67110. 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);
  67111. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  67112. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  67113. 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)))));
  67114. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  67115. 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)))));
  67116. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  67117. 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)))));
  67118. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  67119. 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)))));
  67120. };
  67121. return SIMDMatrix;
  67122. }());
  67123. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  67124. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  67125. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  67126. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  67127. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  67128. var SIMDHelper = (function () {
  67129. function SIMDHelper() {
  67130. }
  67131. Object.defineProperty(SIMDHelper, "IsEnabled", {
  67132. get: function () {
  67133. return SIMDHelper._isEnabled;
  67134. },
  67135. enumerable: true,
  67136. configurable: true
  67137. });
  67138. SIMDHelper.DisableSIMD = function () {
  67139. // Replace functions
  67140. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  67141. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  67142. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  67143. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  67144. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  67145. SIMDHelper._isEnabled = false;
  67146. };
  67147. SIMDHelper.EnableSIMD = function () {
  67148. if (self.SIMD === undefined) {
  67149. return;
  67150. }
  67151. // check if polyfills needed
  67152. if (!self.Math.fround) {
  67153. self.Math.fround = (function (array) { return function (x) {
  67154. return array[0] = x, array[0];
  67155. }; })(new Float32Array(1));
  67156. }
  67157. if (!self.Math.imul) {
  67158. self.Math.imul = function (a, b) {
  67159. var ah = (a >>> 16) & 0xffff;
  67160. var al = a & 0xffff;
  67161. var bh = (b >>> 16) & 0xffff;
  67162. var bl = b & 0xffff;
  67163. // the shift by 0 fixes the sign on the high part
  67164. // the final |0 converts the unsigned value into a signed value
  67165. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  67166. };
  67167. }
  67168. // Replace functions
  67169. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  67170. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  67171. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  67172. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  67173. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  67174. SIMDHelper._isEnabled = true;
  67175. };
  67176. SIMDHelper._isEnabled = false;
  67177. return SIMDHelper;
  67178. }());
  67179. BABYLON.SIMDHelper = SIMDHelper;
  67180. })(BABYLON || (BABYLON = {}));
  67181. //# sourceMappingURL=babylon.math.SIMD.js.map
  67182. var BABYLON;
  67183. (function (BABYLON) {
  67184. var VRDistortionCorrectionPostProcess = (function (_super) {
  67185. __extends(VRDistortionCorrectionPostProcess, _super);
  67186. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  67187. var _this = _super.call(this, name, "vrDistortionCorrection", [
  67188. 'LensCenter',
  67189. 'Scale',
  67190. 'ScaleIn',
  67191. 'HmdWarpParam'
  67192. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  67193. _this._isRightEye = isRightEye;
  67194. _this._distortionFactors = vrMetrics.distortionK;
  67195. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  67196. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  67197. _this.adaptScaleToCurrentViewport = true;
  67198. _this.onSizeChangedObservable.add(function () {
  67199. _this.aspectRatio = _this.width * .5 / _this.height;
  67200. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  67201. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  67202. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  67203. });
  67204. _this.onApplyObservable.add(function (effect) {
  67205. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  67206. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  67207. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  67208. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  67209. });
  67210. return _this;
  67211. }
  67212. return VRDistortionCorrectionPostProcess;
  67213. }(BABYLON.PostProcess));
  67214. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  67215. })(BABYLON || (BABYLON = {}));
  67216. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  67217. var BABYLON;
  67218. (function (BABYLON) {
  67219. var AnaglyphPostProcess = (function (_super) {
  67220. __extends(AnaglyphPostProcess, _super);
  67221. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  67222. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  67223. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67224. _this.onApplyObservable.add(function (effect) {
  67225. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  67226. });
  67227. return _this;
  67228. }
  67229. return AnaglyphPostProcess;
  67230. }(BABYLON.PostProcess));
  67231. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  67232. })(BABYLON || (BABYLON = {}));
  67233. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  67234. var BABYLON;
  67235. (function (BABYLON) {
  67236. var StereoscopicInterlacePostProcess = (function (_super) {
  67237. __extends(StereoscopicInterlacePostProcess, _super);
  67238. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  67239. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  67240. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67241. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67242. _this.onSizeChangedObservable.add(function () {
  67243. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67244. });
  67245. _this.onApplyObservable.add(function (effect) {
  67246. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  67247. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  67248. });
  67249. return _this;
  67250. }
  67251. return StereoscopicInterlacePostProcess;
  67252. }(BABYLON.PostProcess));
  67253. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  67254. })(BABYLON || (BABYLON = {}));
  67255. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  67256. var BABYLON;
  67257. (function (BABYLON) {
  67258. var FreeCameraDeviceOrientationInput = (function () {
  67259. function FreeCameraDeviceOrientationInput() {
  67260. var _this = this;
  67261. this._screenOrientationAngle = 0;
  67262. this._screenQuaternion = new BABYLON.Quaternion();
  67263. this._alpha = 0;
  67264. this._beta = 0;
  67265. this._gamma = 0;
  67266. this._orientationChanged = function () {
  67267. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  67268. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  67269. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  67270. };
  67271. this._deviceOrientation = function (evt) {
  67272. _this._alpha = evt.alpha;
  67273. _this._beta = evt.beta;
  67274. _this._gamma = evt.gamma;
  67275. };
  67276. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  67277. this._orientationChanged();
  67278. }
  67279. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  67280. get: function () {
  67281. return this._camera;
  67282. },
  67283. set: function (camera) {
  67284. this._camera = camera;
  67285. if (this._camera != null && !this._camera.rotationQuaternion) {
  67286. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  67287. }
  67288. },
  67289. enumerable: true,
  67290. configurable: true
  67291. });
  67292. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67293. window.addEventListener("orientationchange", this._orientationChanged);
  67294. window.addEventListener("deviceorientation", this._deviceOrientation);
  67295. //In certain cases, the attach control is called AFTER orientation was changed,
  67296. //So this is needed.
  67297. this._orientationChanged();
  67298. };
  67299. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  67300. window.removeEventListener("orientationchange", this._orientationChanged);
  67301. window.removeEventListener("deviceorientation", this._deviceOrientation);
  67302. };
  67303. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  67304. //if no device orientation provided, don't update the rotation.
  67305. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  67306. if (!this._alpha)
  67307. return;
  67308. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  67309. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  67310. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  67311. //Mirror on XY Plane
  67312. this._camera.rotationQuaternion.z *= -1;
  67313. this._camera.rotationQuaternion.w *= -1;
  67314. };
  67315. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  67316. return "FreeCameraDeviceOrientationInput";
  67317. };
  67318. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  67319. return "deviceOrientation";
  67320. };
  67321. return FreeCameraDeviceOrientationInput;
  67322. }());
  67323. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  67324. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  67325. })(BABYLON || (BABYLON = {}));
  67326. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  67327. var BABYLON;
  67328. (function (BABYLON) {
  67329. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  67330. function ArcRotateCameraVRDeviceOrientationInput() {
  67331. this.alphaCorrection = 1;
  67332. this.betaCorrection = 1;
  67333. this.gammaCorrection = 1;
  67334. this._alpha = 0;
  67335. this._beta = 0;
  67336. this._gamma = 0;
  67337. this._dirty = false;
  67338. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  67339. }
  67340. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67341. this.camera.attachControl(element, noPreventDefault);
  67342. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  67343. };
  67344. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  67345. var camera = this.camera;
  67346. this._alpha = +evt.alpha | 0;
  67347. this._beta = +evt.beta | 0;
  67348. this._gamma = +evt.gamma | 0;
  67349. this._dirty = true;
  67350. };
  67351. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  67352. if (this._dirty) {
  67353. this._dirty = false;
  67354. if (this._gamma < 0) {
  67355. this._gamma = 180 + this._gamma;
  67356. }
  67357. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  67358. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  67359. }
  67360. };
  67361. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  67362. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  67363. };
  67364. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  67365. return "ArcRotateCameraVRDeviceOrientationInput";
  67366. };
  67367. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  67368. return "VRDeviceOrientation";
  67369. };
  67370. return ArcRotateCameraVRDeviceOrientationInput;
  67371. }());
  67372. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  67373. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  67374. })(BABYLON || (BABYLON = {}));
  67375. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  67376. var BABYLON;
  67377. (function (BABYLON) {
  67378. var VRCameraMetrics = (function () {
  67379. function VRCameraMetrics() {
  67380. this.compensateDistortion = true;
  67381. }
  67382. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  67383. get: function () {
  67384. return this.hResolution / (2 * this.vResolution);
  67385. },
  67386. enumerable: true,
  67387. configurable: true
  67388. });
  67389. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  67390. get: function () {
  67391. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  67392. },
  67393. enumerable: true,
  67394. configurable: true
  67395. });
  67396. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  67397. get: function () {
  67398. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67399. var h = (4 * meters) / this.hScreenSize;
  67400. return BABYLON.Matrix.Translation(h, 0, 0);
  67401. },
  67402. enumerable: true,
  67403. configurable: true
  67404. });
  67405. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  67406. get: function () {
  67407. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67408. var h = (4 * meters) / this.hScreenSize;
  67409. return BABYLON.Matrix.Translation(-h, 0, 0);
  67410. },
  67411. enumerable: true,
  67412. configurable: true
  67413. });
  67414. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  67415. get: function () {
  67416. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  67417. },
  67418. enumerable: true,
  67419. configurable: true
  67420. });
  67421. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  67422. get: function () {
  67423. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  67424. },
  67425. enumerable: true,
  67426. configurable: true
  67427. });
  67428. VRCameraMetrics.GetDefault = function () {
  67429. var result = new VRCameraMetrics();
  67430. result.hResolution = 1280;
  67431. result.vResolution = 800;
  67432. result.hScreenSize = 0.149759993;
  67433. result.vScreenSize = 0.0935999975;
  67434. result.vScreenCenter = 0.0467999987;
  67435. result.eyeToScreenDistance = 0.0410000011;
  67436. result.lensSeparationDistance = 0.0635000020;
  67437. result.interpupillaryDistance = 0.0640000030;
  67438. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  67439. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  67440. result.postProcessScaleFactor = 1.714605507808412;
  67441. result.lensCenterOffset = 0.151976421;
  67442. return result;
  67443. };
  67444. return VRCameraMetrics;
  67445. }());
  67446. BABYLON.VRCameraMetrics = VRCameraMetrics;
  67447. })(BABYLON || (BABYLON = {}));
  67448. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  67449. var BABYLON;
  67450. (function (BABYLON) {
  67451. var WebVRFreeCamera = (function (_super) {
  67452. __extends(WebVRFreeCamera, _super);
  67453. function WebVRFreeCamera(name, position, scene, webVROptions) {
  67454. if (webVROptions === void 0) { webVROptions = {}; }
  67455. var _this = _super.call(this, name, position, scene) || this;
  67456. _this.webVROptions = webVROptions;
  67457. _this._vrDevice = null;
  67458. _this.rawPose = null;
  67459. _this._specsVersion = "1.1";
  67460. _this._attached = false;
  67461. _this._positionOffset = BABYLON.Vector3.Zero();
  67462. _this._descendants = [];
  67463. _this.devicePosition = BABYLON.Vector3.Zero();
  67464. _this.deviceScaleFactor = 1;
  67465. _this.controllers = [];
  67466. _this.onControllersAttachedObservable = new BABYLON.Observable();
  67467. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  67468. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  67469. _this.minZ = 0.1;
  67470. //legacy support - the compensation boolean was removed.
  67471. if (arguments.length === 5) {
  67472. _this.webVROptions = arguments[4];
  67473. }
  67474. // default webVR options
  67475. if (_this.webVROptions.trackPosition == undefined) {
  67476. _this.webVROptions.trackPosition = true;
  67477. }
  67478. if (_this.webVROptions.controllerMeshes == undefined) {
  67479. _this.webVROptions.controllerMeshes = true;
  67480. }
  67481. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  67482. _this.webVROptions.defaultLightingOnControllers = true;
  67483. }
  67484. _this.rotationQuaternion = new BABYLON.Quaternion();
  67485. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  67486. if (_this.webVROptions && _this.webVROptions.positionScale) {
  67487. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  67488. }
  67489. //enable VR
  67490. var engine = _this.getEngine();
  67491. _this._onVREnabled = function (success) { if (success) {
  67492. _this.initControllers();
  67493. } };
  67494. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  67495. engine.initWebVR().add(function (event) {
  67496. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  67497. return;
  67498. }
  67499. _this._vrDevice = event.vrDisplay;
  67500. //reset the rig parameters.
  67501. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  67502. if (_this._attached) {
  67503. _this.getEngine().enableVR();
  67504. }
  67505. });
  67506. if (typeof (VRFrameData) !== "undefined")
  67507. _this._frameData = new VRFrameData();
  67508. /**
  67509. * The idea behind the following lines:
  67510. * objects that have the camera as parent should actually have the rig cameras as a parent.
  67511. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  67512. * the second will not show it correctly.
  67513. *
  67514. * To solve this - each object that has the camera as parent will be added to a protected array.
  67515. * When the rig camera renders, it will take this array and set all of those to be its children.
  67516. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  67517. * Amazing!
  67518. */
  67519. scene.onBeforeCameraRenderObservable.add(function (camera) {
  67520. if (camera.parent === _this && _this.rigParenting) {
  67521. _this._descendants = _this.getDescendants(true, function (n) {
  67522. // don't take the cameras or the controllers!
  67523. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  67524. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  67525. return !isController && !isRigCamera;
  67526. });
  67527. _this._descendants.forEach(function (node) {
  67528. node.parent = camera;
  67529. });
  67530. }
  67531. });
  67532. scene.onAfterCameraRenderObservable.add(function (camera) {
  67533. if (camera.parent === _this && _this.rigParenting) {
  67534. _this._descendants.forEach(function (node) {
  67535. node.parent = _this;
  67536. });
  67537. }
  67538. });
  67539. return _this;
  67540. }
  67541. WebVRFreeCamera.prototype.dispose = function () {
  67542. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  67543. _super.prototype.dispose.call(this);
  67544. };
  67545. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  67546. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  67547. var gp = _a[_i];
  67548. if (gp.hand === name) {
  67549. return gp;
  67550. }
  67551. }
  67552. return undefined;
  67553. };
  67554. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  67555. get: function () {
  67556. if (!this._leftController) {
  67557. this._leftController = this.getControllerByName("left");
  67558. }
  67559. return this._leftController;
  67560. },
  67561. enumerable: true,
  67562. configurable: true
  67563. });
  67564. ;
  67565. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  67566. get: function () {
  67567. if (!this._rightController) {
  67568. this._rightController = this.getControllerByName("right");
  67569. }
  67570. return this._rightController;
  67571. },
  67572. enumerable: true,
  67573. configurable: true
  67574. });
  67575. ;
  67576. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  67577. if (length === void 0) { length = 100; }
  67578. if (this.leftCamera) {
  67579. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  67580. }
  67581. else {
  67582. return _super.prototype.getForwardRay.call(this, length);
  67583. }
  67584. };
  67585. WebVRFreeCamera.prototype._checkInputs = function () {
  67586. if (this._vrDevice && this._vrDevice.isPresenting) {
  67587. this._vrDevice.getFrameData(this._frameData);
  67588. this.updateFromDevice(this._frameData.pose);
  67589. }
  67590. _super.prototype._checkInputs.call(this);
  67591. };
  67592. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  67593. if (poseData && poseData.orientation) {
  67594. this.rawPose = poseData;
  67595. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  67596. if (this.getScene().useRightHandedSystem) {
  67597. this.deviceRotationQuaternion.z *= -1;
  67598. this.deviceRotationQuaternion.w *= -1;
  67599. }
  67600. if (this.webVROptions.trackPosition && this.rawPose.position) {
  67601. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  67602. if (this.getScene().useRightHandedSystem) {
  67603. this.devicePosition.z *= -1;
  67604. }
  67605. }
  67606. }
  67607. };
  67608. /**
  67609. * WebVR's attach control will start broadcasting frames to the device.
  67610. * Note that in certain browsers (chrome for example) this function must be called
  67611. * within a user-interaction callback. Example:
  67612. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  67613. *
  67614. * @param {HTMLElement} element
  67615. * @param {boolean} [noPreventDefault]
  67616. *
  67617. * @memberOf WebVRFreeCamera
  67618. */
  67619. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  67620. _super.prototype.attachControl.call(this, element, noPreventDefault);
  67621. this._attached = true;
  67622. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  67623. if (this._vrDevice) {
  67624. this.getEngine().enableVR();
  67625. }
  67626. };
  67627. WebVRFreeCamera.prototype.detachControl = function (element) {
  67628. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67629. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67630. _super.prototype.detachControl.call(this, element);
  67631. this._attached = false;
  67632. this.getEngine().disableVR();
  67633. };
  67634. WebVRFreeCamera.prototype.getClassName = function () {
  67635. return "WebVRFreeCamera";
  67636. };
  67637. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  67638. //uses the vrDisplay's "resetPose()".
  67639. //pitch and roll won't be affected.
  67640. this._vrDevice.resetPose();
  67641. };
  67642. WebVRFreeCamera.prototype._updateRigCameras = function () {
  67643. var camLeft = this._rigCameras[0];
  67644. var camRight = this._rigCameras[1];
  67645. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67646. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67647. camLeft.position.copyFrom(this.devicePosition);
  67648. camRight.position.copyFrom(this.devicePosition);
  67649. };
  67650. /**
  67651. * This function is called by the two RIG cameras.
  67652. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  67653. */
  67654. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  67655. var _this = this;
  67656. //WebVR 1.1
  67657. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  67658. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  67659. if (!this.getScene().useRightHandedSystem) {
  67660. [2, 6, 8, 9, 14].forEach(function (num) {
  67661. _this._webvrViewMatrix.m[num] *= -1;
  67662. });
  67663. }
  67664. // update the camera rotation matrix
  67665. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  67666. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  67667. // Computing target and final matrix
  67668. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  67669. var parentCamera = this._cameraRigParams["parentCamera"];
  67670. // should the view matrix be updated with scale and position offset?
  67671. if (parentCamera.deviceScaleFactor !== 1) {
  67672. this._webvrViewMatrix.invert();
  67673. // scale the position, if set
  67674. if (parentCamera.deviceScaleFactor) {
  67675. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  67676. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  67677. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  67678. }
  67679. this._webvrViewMatrix.invert();
  67680. }
  67681. return this._webvrViewMatrix;
  67682. };
  67683. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  67684. var _this = this;
  67685. var parentCamera = this.parent;
  67686. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  67687. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  67688. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  67689. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  67690. //babylon compatible matrix
  67691. if (!this.getScene().useRightHandedSystem) {
  67692. [8, 9, 10, 11].forEach(function (num) {
  67693. _this._projectionMatrix.m[num] *= -1;
  67694. });
  67695. }
  67696. return this._projectionMatrix;
  67697. };
  67698. WebVRFreeCamera.prototype.initControllers = function () {
  67699. var _this = this;
  67700. this.controllers = [];
  67701. var manager = this.getScene().gamepadManager;
  67702. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67703. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67704. var webVrController = gamepad;
  67705. if (webVrController.defaultModel) {
  67706. webVrController.defaultModel.setEnabled(false);
  67707. }
  67708. }
  67709. });
  67710. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67711. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67712. var webVrController_1 = gamepad;
  67713. if (_this.webVROptions.controllerMeshes) {
  67714. if (webVrController_1.defaultModel) {
  67715. webVrController_1.defaultModel.setEnabled(true);
  67716. }
  67717. else {
  67718. // Load the meshes
  67719. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  67720. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  67721. if (_this.webVROptions.defaultLightingOnControllers) {
  67722. if (!_this._lightOnControllers) {
  67723. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  67724. }
  67725. var activateLightOnSubMeshes_1 = function (mesh, light) {
  67726. var children = mesh.getChildren();
  67727. if (children.length !== 0) {
  67728. children.forEach(function (mesh) {
  67729. light.includedOnlyMeshes.push(mesh);
  67730. activateLightOnSubMeshes_1(mesh, light);
  67731. });
  67732. }
  67733. };
  67734. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  67735. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  67736. }
  67737. });
  67738. }
  67739. }
  67740. webVrController_1.attachToPoseControlledCamera(_this);
  67741. // since this is async - sanity check. Is the controller already stored?
  67742. if (_this.controllers.indexOf(webVrController_1) === -1) {
  67743. //add to the controllers array
  67744. _this.controllers.push(webVrController_1);
  67745. //did we find enough controllers? Great! let the developer know.
  67746. if (_this.controllers.length >= 2) {
  67747. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  67748. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  67749. // So we're overriding setting left & right manually to be sure
  67750. var firstViveWandDetected = false;
  67751. for (var i = 0; i < _this.controllers.length; i++) {
  67752. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  67753. if (!firstViveWandDetected) {
  67754. firstViveWandDetected = true;
  67755. _this.controllers[i].hand = "left";
  67756. }
  67757. else {
  67758. _this.controllers[i].hand = "right";
  67759. }
  67760. }
  67761. }
  67762. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  67763. }
  67764. }
  67765. }
  67766. });
  67767. };
  67768. return WebVRFreeCamera;
  67769. }(BABYLON.FreeCamera));
  67770. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  67771. })(BABYLON || (BABYLON = {}));
  67772. //# sourceMappingURL=babylon.webVRCamera.js.map
  67773. /// <reference path="babylon.freeCamera.ts" />
  67774. var BABYLON;
  67775. (function (BABYLON) {
  67776. // We're mainly based on the logic defined into the FreeCamera code
  67777. var DeviceOrientationCamera = (function (_super) {
  67778. __extends(DeviceOrientationCamera, _super);
  67779. function DeviceOrientationCamera(name, position, scene) {
  67780. var _this = _super.call(this, name, position, scene) || this;
  67781. _this._quaternionCache = new BABYLON.Quaternion();
  67782. _this.inputs.addDeviceOrientation();
  67783. return _this;
  67784. }
  67785. DeviceOrientationCamera.prototype.getClassName = function () {
  67786. return "DeviceOrientationCamera";
  67787. };
  67788. DeviceOrientationCamera.prototype._checkInputs = function () {
  67789. _super.prototype._checkInputs.call(this);
  67790. this._quaternionCache.copyFrom(this.rotationQuaternion);
  67791. if (this._initialQuaternion) {
  67792. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67793. }
  67794. };
  67795. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  67796. var _this = this;
  67797. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  67798. //can only work if this camera has a rotation quaternion already.
  67799. if (!this.rotationQuaternion)
  67800. return;
  67801. if (!this._initialQuaternion) {
  67802. this._initialQuaternion = new BABYLON.Quaternion();
  67803. }
  67804. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  67805. ['x', 'y', 'z'].forEach(function (axisName) {
  67806. if (!axis[axisName]) {
  67807. _this._initialQuaternion[axisName] = 0;
  67808. }
  67809. else {
  67810. _this._initialQuaternion[axisName] *= -1;
  67811. }
  67812. });
  67813. this._initialQuaternion.normalize();
  67814. //force rotation update
  67815. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67816. };
  67817. return DeviceOrientationCamera;
  67818. }(BABYLON.FreeCamera));
  67819. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  67820. })(BABYLON || (BABYLON = {}));
  67821. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  67822. var BABYLON;
  67823. (function (BABYLON) {
  67824. var VRDeviceOrientationFreeCamera = (function (_super) {
  67825. __extends(VRDeviceOrientationFreeCamera, _super);
  67826. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67827. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67828. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67829. var _this = _super.call(this, name, position, scene) || this;
  67830. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67831. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67832. return _this;
  67833. }
  67834. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  67835. return "VRDeviceOrientationFreeCamera";
  67836. };
  67837. return VRDeviceOrientationFreeCamera;
  67838. }(BABYLON.DeviceOrientationCamera));
  67839. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  67840. var VRDeviceOrientationGamepadCamera = (function (_super) {
  67841. __extends(VRDeviceOrientationGamepadCamera, _super);
  67842. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67843. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67844. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67845. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  67846. _this.inputs.addGamepad();
  67847. return _this;
  67848. }
  67849. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  67850. return "VRDeviceOrientationGamepadCamera";
  67851. };
  67852. return VRDeviceOrientationGamepadCamera;
  67853. }(VRDeviceOrientationFreeCamera));
  67854. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  67855. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  67856. __extends(VRDeviceOrientationArcRotateCamera, _super);
  67857. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  67858. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67859. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67860. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67861. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67862. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67863. _this.inputs.addVRDeviceOrientation();
  67864. return _this;
  67865. }
  67866. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  67867. return "VRDeviceOrientationArcRotateCamera";
  67868. };
  67869. return VRDeviceOrientationArcRotateCamera;
  67870. }(BABYLON.ArcRotateCamera));
  67871. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  67872. })(BABYLON || (BABYLON = {}));
  67873. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  67874. /// <reference path="babylon.freeCamera.ts" />
  67875. /// <reference path="babylon.arcRotateCamera.ts" />
  67876. /// <reference path="babylon.gamepadCamera.ts" />
  67877. /// <reference path="babylon.universalCamera.ts" />
  67878. var BABYLON;
  67879. (function (BABYLON) {
  67880. var AnaglyphFreeCamera = (function (_super) {
  67881. __extends(AnaglyphFreeCamera, _super);
  67882. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  67883. var _this = _super.call(this, name, position, scene) || this;
  67884. _this.interaxialDistance = interaxialDistance;
  67885. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67886. return _this;
  67887. }
  67888. AnaglyphFreeCamera.prototype.getClassName = function () {
  67889. return "AnaglyphFreeCamera";
  67890. };
  67891. return AnaglyphFreeCamera;
  67892. }(BABYLON.FreeCamera));
  67893. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  67894. var AnaglyphArcRotateCamera = (function (_super) {
  67895. __extends(AnaglyphArcRotateCamera, _super);
  67896. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  67897. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67898. _this.interaxialDistance = interaxialDistance;
  67899. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67900. return _this;
  67901. }
  67902. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  67903. return "AnaglyphArcRotateCamera";
  67904. };
  67905. return AnaglyphArcRotateCamera;
  67906. }(BABYLON.ArcRotateCamera));
  67907. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  67908. var AnaglyphGamepadCamera = (function (_super) {
  67909. __extends(AnaglyphGamepadCamera, _super);
  67910. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  67911. var _this = _super.call(this, name, position, scene) || this;
  67912. _this.interaxialDistance = interaxialDistance;
  67913. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67914. return _this;
  67915. }
  67916. AnaglyphGamepadCamera.prototype.getClassName = function () {
  67917. return "AnaglyphGamepadCamera";
  67918. };
  67919. return AnaglyphGamepadCamera;
  67920. }(BABYLON.GamepadCamera));
  67921. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  67922. var AnaglyphUniversalCamera = (function (_super) {
  67923. __extends(AnaglyphUniversalCamera, _super);
  67924. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  67925. var _this = _super.call(this, name, position, scene) || this;
  67926. _this.interaxialDistance = interaxialDistance;
  67927. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67928. return _this;
  67929. }
  67930. AnaglyphUniversalCamera.prototype.getClassName = function () {
  67931. return "AnaglyphUniversalCamera";
  67932. };
  67933. return AnaglyphUniversalCamera;
  67934. }(BABYLON.UniversalCamera));
  67935. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  67936. var StereoscopicFreeCamera = (function (_super) {
  67937. __extends(StereoscopicFreeCamera, _super);
  67938. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67939. var _this = _super.call(this, name, position, scene) || this;
  67940. _this.interaxialDistance = interaxialDistance;
  67941. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67942. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67943. return _this;
  67944. }
  67945. StereoscopicFreeCamera.prototype.getClassName = function () {
  67946. return "StereoscopicFreeCamera";
  67947. };
  67948. return StereoscopicFreeCamera;
  67949. }(BABYLON.FreeCamera));
  67950. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  67951. var StereoscopicArcRotateCamera = (function (_super) {
  67952. __extends(StereoscopicArcRotateCamera, _super);
  67953. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  67954. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67955. _this.interaxialDistance = interaxialDistance;
  67956. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67957. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67958. return _this;
  67959. }
  67960. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  67961. return "StereoscopicArcRotateCamera";
  67962. };
  67963. return StereoscopicArcRotateCamera;
  67964. }(BABYLON.ArcRotateCamera));
  67965. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  67966. var StereoscopicGamepadCamera = (function (_super) {
  67967. __extends(StereoscopicGamepadCamera, _super);
  67968. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67969. var _this = _super.call(this, name, position, scene) || this;
  67970. _this.interaxialDistance = interaxialDistance;
  67971. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67972. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67973. return _this;
  67974. }
  67975. StereoscopicGamepadCamera.prototype.getClassName = function () {
  67976. return "StereoscopicGamepadCamera";
  67977. };
  67978. return StereoscopicGamepadCamera;
  67979. }(BABYLON.GamepadCamera));
  67980. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  67981. var StereoscopicUniversalCamera = (function (_super) {
  67982. __extends(StereoscopicUniversalCamera, _super);
  67983. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67984. var _this = _super.call(this, name, position, scene) || this;
  67985. _this.interaxialDistance = interaxialDistance;
  67986. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67987. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67988. return _this;
  67989. }
  67990. StereoscopicUniversalCamera.prototype.getClassName = function () {
  67991. return "StereoscopicUniversalCamera";
  67992. };
  67993. return StereoscopicUniversalCamera;
  67994. }(BABYLON.UniversalCamera));
  67995. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  67996. })(BABYLON || (BABYLON = {}));
  67997. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  67998. var BABYLON;
  67999. (function (BABYLON) {
  68000. var VRExperienceHelper = (function () {
  68001. function VRExperienceHelper(scene, webVROptions) {
  68002. if (webVROptions === void 0) { webVROptions = {}; }
  68003. var _this = this;
  68004. this.webVROptions = webVROptions;
  68005. // Can the system support WebVR, even if a headset isn't plugged in?
  68006. this._webVRsupported = false;
  68007. // If WebVR is supported, is a headset plugged in and are we ready to present?
  68008. this._webVRready = false;
  68009. // Are we waiting for the requestPresent callback to complete?
  68010. this._webVRrequesting = false;
  68011. // Are we presenting to the headset right now?
  68012. this._webVRpresenting = false;
  68013. // Are we presenting in the fullscreen fallback?
  68014. this._fullscreenVRpresenting = false;
  68015. this._scene = scene;
  68016. if (!this._scene.activeCamera) {
  68017. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  68018. }
  68019. else {
  68020. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  68021. if (scene.activeCamera.rotation) {
  68022. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  68023. }
  68024. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  68025. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  68026. }
  68027. this._scene.activeCamera = this._deviceOrientationCamera;
  68028. this._position = this._scene.activeCamera.position;
  68029. this._canvas = scene.getEngine().getRenderingCanvas();
  68030. this._scene.activeCamera.attachControl(this._canvas);
  68031. this._btnVR = document.createElement("BUTTON");
  68032. this._btnVR.className = "babylonVRicon";
  68033. this._btnVR.id = "babylonVRiconbtn";
  68034. this._btnVR.title = "Click to switch to VR";
  68035. 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) }";
  68036. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  68037. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  68038. // css += ".babylonVRicon.vrdisplaysupported { }";
  68039. // css += ".babylonVRicon.vrdisplayready { }";
  68040. // css += ".babylonVRicon.vrdisplayrequesting { }";
  68041. var style = document.createElement('style');
  68042. style.appendChild(document.createTextNode(css));
  68043. document.getElementsByTagName('head')[0].appendChild(style);
  68044. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68045. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68046. this._btnVR.addEventListener("click", function () {
  68047. _this.enterVR();
  68048. });
  68049. window.addEventListener("resize", function () {
  68050. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  68051. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  68052. if (_this._fullscreenVRpresenting && _this._webVRready) {
  68053. _this.exitVR();
  68054. }
  68055. });
  68056. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68057. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68058. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68059. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68060. document.body.appendChild(this._btnVR);
  68061. // Exiting VR mode using 'ESC' key on desktop
  68062. this._onKeyDown = function (event) {
  68063. if (event.keyCode === 27 && _this.isInVRMode()) {
  68064. _this.exitVR();
  68065. }
  68066. };
  68067. document.addEventListener("keydown", this._onKeyDown);
  68068. // Exiting VR mode double tapping the touch screen
  68069. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  68070. if (_this.isInVRMode()) {
  68071. _this.exitVR();
  68072. if (_this._fullscreenVRpresenting) {
  68073. _this._scene.getEngine().switchFullscreen(true);
  68074. }
  68075. }
  68076. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  68077. // Listen for WebVR display changes
  68078. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  68079. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  68080. this._onVRRequestPresentStart = function () {
  68081. _this._webVRrequesting = true;
  68082. _this.updateButtonVisibility();
  68083. };
  68084. this._onVRRequestPresentComplete = function (success) {
  68085. _this._webVRrequesting = false;
  68086. _this.updateButtonVisibility();
  68087. };
  68088. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  68089. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  68090. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  68091. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68092. // Create the cameras
  68093. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  68094. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  68095. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  68096. this.updateButtonVisibility();
  68097. }
  68098. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  68099. if (this.onControllerMeshLoaded) {
  68100. this.onControllerMeshLoaded(webVRController);
  68101. }
  68102. };
  68103. VRExperienceHelper.prototype._onFullscreenChange = function () {
  68104. if (document.fullscreen !== undefined) {
  68105. this._fullscreenVRpresenting = document.fullscreen;
  68106. }
  68107. else if (document.mozFullScreen !== undefined) {
  68108. this._fullscreenVRpresenting = document.mozFullScreen;
  68109. }
  68110. else if (document.webkitIsFullScreen !== undefined) {
  68111. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  68112. }
  68113. else if (document.msIsFullScreen !== undefined) {
  68114. this._fullscreenVRpresenting = document.msIsFullScreen;
  68115. }
  68116. if (!this._fullscreenVRpresenting) {
  68117. this.exitVR();
  68118. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68119. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68120. }
  68121. };
  68122. VRExperienceHelper.prototype.isInVRMode = function () {
  68123. return this._webVRpresenting || this._fullscreenVRpresenting;
  68124. };
  68125. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  68126. var vrDisplay = this._scene.getEngine().getVRDevice();
  68127. if (vrDisplay) {
  68128. var wasPresenting = this._webVRpresenting;
  68129. // A VR display is connected
  68130. this._webVRpresenting = vrDisplay.isPresenting;
  68131. if (wasPresenting && !this._webVRpresenting)
  68132. this.exitVR();
  68133. }
  68134. else {
  68135. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  68136. }
  68137. this.updateButtonVisibility();
  68138. };
  68139. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  68140. this._webVRsupported = eventArgs.vrSupported;
  68141. this._webVRready = !!eventArgs.vrDisplay;
  68142. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  68143. this.updateButtonVisibility();
  68144. };
  68145. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  68146. if (!this._btnVR) {
  68147. return;
  68148. }
  68149. this._btnVR.className = "babylonVRicon";
  68150. if (this.isInVRMode()) {
  68151. this._btnVR.className += " vrdisplaypresenting";
  68152. }
  68153. else {
  68154. if (this._webVRready)
  68155. this._btnVR.className += " vrdisplayready";
  68156. if (this._webVRsupported)
  68157. this._btnVR.className += " vrdisplaysupported";
  68158. if (this._webVRrequesting)
  68159. this._btnVR.className += " vrdisplayrequesting";
  68160. }
  68161. };
  68162. /**
  68163. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  68164. * Otherwise, will use the fullscreen API.
  68165. */
  68166. VRExperienceHelper.prototype.enterVR = function () {
  68167. if (this.onEnteringVR) {
  68168. this.onEnteringVR();
  68169. }
  68170. if (this._webVRrequesting)
  68171. return;
  68172. // If WebVR is supported and a headset is connected
  68173. if (this._webVRready) {
  68174. if (!this._webVRpresenting) {
  68175. this._webVRCamera.position = this._position;
  68176. this._scene.activeCamera = this._webVRCamera;
  68177. }
  68178. }
  68179. else {
  68180. this._vrDeviceOrientationCamera.position = this._position;
  68181. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  68182. this._scene.getEngine().switchFullscreen(true);
  68183. this.updateButtonVisibility();
  68184. }
  68185. this._scene.activeCamera.attachControl(this._canvas);
  68186. };
  68187. /**
  68188. * Attempt to exit VR, or fullscreen.
  68189. */
  68190. VRExperienceHelper.prototype.exitVR = function () {
  68191. if (this.onExitingVR) {
  68192. this.onExitingVR();
  68193. }
  68194. if (this._webVRpresenting) {
  68195. this._scene.getEngine().disableVR();
  68196. }
  68197. if (this._scene.activeCamera) {
  68198. this._position = this._scene.activeCamera.position;
  68199. }
  68200. this._deviceOrientationCamera.position = this._position;
  68201. this._scene.activeCamera = this._deviceOrientationCamera;
  68202. this._scene.activeCamera.attachControl(this._canvas);
  68203. this.updateButtonVisibility();
  68204. };
  68205. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  68206. get: function () {
  68207. return this._position;
  68208. },
  68209. set: function (value) {
  68210. this._position = value;
  68211. this._scene.activeCamera.position = value;
  68212. },
  68213. enumerable: true,
  68214. configurable: true
  68215. });
  68216. VRExperienceHelper.prototype.dispose = function () {
  68217. if (this.isInVRMode()) {
  68218. this.exitVR();
  68219. }
  68220. this._deviceOrientationCamera.dispose();
  68221. if (this._webVRCamera) {
  68222. this._webVRCamera.dispose();
  68223. }
  68224. if (this._vrDeviceOrientationCamera) {
  68225. this._vrDeviceOrientationCamera.dispose();
  68226. }
  68227. document.body.removeChild(this._btnVR);
  68228. document.removeEventListener("keydown", this._onKeyDown);
  68229. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68230. };
  68231. VRExperienceHelper.prototype.getClassName = function () {
  68232. return "VRExperienceHelper";
  68233. };
  68234. return VRExperienceHelper;
  68235. }());
  68236. BABYLON.VRExperienceHelper = VRExperienceHelper;
  68237. })(BABYLON || (BABYLON = {}));
  68238. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  68239. // Mainly based on these 2 articles :
  68240. // 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
  68241. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  68242. var BABYLON;
  68243. (function (BABYLON) {
  68244. var JoystickAxis;
  68245. (function (JoystickAxis) {
  68246. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  68247. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  68248. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  68249. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  68250. var VirtualJoystick = (function () {
  68251. function VirtualJoystick(leftJoystick) {
  68252. var _this = this;
  68253. if (leftJoystick) {
  68254. this._leftJoystick = true;
  68255. }
  68256. else {
  68257. this._leftJoystick = false;
  68258. }
  68259. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  68260. VirtualJoystick._globalJoystickIndex++;
  68261. // By default left & right arrow keys are moving the X
  68262. // and up & down keys are moving the Y
  68263. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68264. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68265. this.reverseLeftRight = false;
  68266. this.reverseUpDown = false;
  68267. // collections of pointers
  68268. this._touches = new BABYLON.StringDictionary();
  68269. this.deltaPosition = BABYLON.Vector3.Zero();
  68270. this._joystickSensibility = 25;
  68271. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68272. this._rotationSpeed = 25;
  68273. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  68274. this._rotateOnAxisRelativeToMesh = false;
  68275. this._onResize = function (evt) {
  68276. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68277. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68278. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  68279. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  68280. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  68281. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  68282. };
  68283. // injecting a canvas element on top of the canvas 3D game
  68284. if (!VirtualJoystick.vjCanvas) {
  68285. window.addEventListener("resize", this._onResize, false);
  68286. VirtualJoystick.vjCanvas = document.createElement("canvas");
  68287. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68288. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68289. VirtualJoystick.vjCanvas.width = window.innerWidth;
  68290. VirtualJoystick.vjCanvas.height = window.innerHeight;
  68291. VirtualJoystick.vjCanvas.style.width = "100%";
  68292. VirtualJoystick.vjCanvas.style.height = "100%";
  68293. VirtualJoystick.vjCanvas.style.position = "absolute";
  68294. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  68295. VirtualJoystick.vjCanvas.style.top = "0px";
  68296. VirtualJoystick.vjCanvas.style.left = "0px";
  68297. VirtualJoystick.vjCanvas.style.zIndex = "5";
  68298. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  68299. // Support for jQuery PEP polyfill
  68300. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  68301. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  68302. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  68303. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68304. document.body.appendChild(VirtualJoystick.vjCanvas);
  68305. }
  68306. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  68307. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  68308. this.pressed = false;
  68309. // default joystick color
  68310. this._joystickColor = "cyan";
  68311. this._joystickPointerID = -1;
  68312. // current joystick position
  68313. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  68314. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  68315. // origin joystick position
  68316. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  68317. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  68318. this._onPointerDownHandlerRef = function (evt) {
  68319. _this._onPointerDown(evt);
  68320. };
  68321. this._onPointerMoveHandlerRef = function (evt) {
  68322. _this._onPointerMove(evt);
  68323. };
  68324. this._onPointerOutHandlerRef = function (evt) {
  68325. _this._onPointerUp(evt);
  68326. };
  68327. this._onPointerUpHandlerRef = function (evt) {
  68328. _this._onPointerUp(evt);
  68329. };
  68330. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  68331. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  68332. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  68333. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  68334. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  68335. evt.preventDefault(); // Disables system menu
  68336. }, false);
  68337. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68338. }
  68339. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  68340. this._joystickSensibility = newJoystickSensibility;
  68341. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68342. };
  68343. VirtualJoystick.prototype._onPointerDown = function (e) {
  68344. var positionOnScreenCondition;
  68345. e.preventDefault();
  68346. if (this._leftJoystick === true) {
  68347. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  68348. }
  68349. else {
  68350. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  68351. }
  68352. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  68353. // First contact will be dedicated to the virtual joystick
  68354. this._joystickPointerID = e.pointerId;
  68355. this._joystickPointerStartPos.x = e.clientX;
  68356. this._joystickPointerStartPos.y = e.clientY;
  68357. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  68358. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  68359. this._deltaJoystickVector.x = 0;
  68360. this._deltaJoystickVector.y = 0;
  68361. this.pressed = true;
  68362. this._touches.add(e.pointerId.toString(), e);
  68363. }
  68364. else {
  68365. // You can only trigger the action buttons with a joystick declared
  68366. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  68367. this._action();
  68368. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  68369. }
  68370. }
  68371. };
  68372. VirtualJoystick.prototype._onPointerMove = function (e) {
  68373. // If the current pointer is the one associated to the joystick (first touch contact)
  68374. if (this._joystickPointerID == e.pointerId) {
  68375. this._joystickPointerPos.x = e.clientX;
  68376. this._joystickPointerPos.y = e.clientY;
  68377. this._deltaJoystickVector = this._joystickPointerPos.clone();
  68378. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  68379. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  68380. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  68381. switch (this._axisTargetedByLeftAndRight) {
  68382. case JoystickAxis.X:
  68383. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  68384. break;
  68385. case JoystickAxis.Y:
  68386. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  68387. break;
  68388. case JoystickAxis.Z:
  68389. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  68390. break;
  68391. }
  68392. var directionUpDown = this.reverseUpDown ? 1 : -1;
  68393. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  68394. switch (this._axisTargetedByUpAndDown) {
  68395. case JoystickAxis.X:
  68396. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  68397. break;
  68398. case JoystickAxis.Y:
  68399. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  68400. break;
  68401. case JoystickAxis.Z:
  68402. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  68403. break;
  68404. }
  68405. }
  68406. else {
  68407. var data = this._touches.get(e.pointerId.toString());
  68408. if (data) {
  68409. data.x = e.clientX;
  68410. data.y = e.clientY;
  68411. }
  68412. }
  68413. };
  68414. VirtualJoystick.prototype._onPointerUp = function (e) {
  68415. if (this._joystickPointerID == e.pointerId) {
  68416. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  68417. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  68418. this._joystickPointerID = -1;
  68419. this.pressed = false;
  68420. }
  68421. else {
  68422. var touch = this._touches.get(e.pointerId.toString());
  68423. if (touch) {
  68424. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68425. }
  68426. }
  68427. this._deltaJoystickVector.x = 0;
  68428. this._deltaJoystickVector.y = 0;
  68429. this._touches.remove(e.pointerId.toString());
  68430. };
  68431. /**
  68432. * Change the color of the virtual joystick
  68433. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  68434. */
  68435. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  68436. this._joystickColor = newColor;
  68437. };
  68438. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  68439. this._action = action;
  68440. };
  68441. // Define which axis you'd like to control for left & right
  68442. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  68443. switch (axis) {
  68444. case JoystickAxis.X:
  68445. case JoystickAxis.Y:
  68446. case JoystickAxis.Z:
  68447. this._axisTargetedByLeftAndRight = axis;
  68448. break;
  68449. default:
  68450. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68451. break;
  68452. }
  68453. };
  68454. // Define which axis you'd like to control for up & down
  68455. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  68456. switch (axis) {
  68457. case JoystickAxis.X:
  68458. case JoystickAxis.Y:
  68459. case JoystickAxis.Z:
  68460. this._axisTargetedByUpAndDown = axis;
  68461. break;
  68462. default:
  68463. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68464. break;
  68465. }
  68466. };
  68467. VirtualJoystick.prototype._clearCanvas = function () {
  68468. if (this._leftJoystick) {
  68469. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  68470. }
  68471. else {
  68472. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  68473. }
  68474. };
  68475. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  68476. var _this = this;
  68477. if (this.pressed) {
  68478. this._touches.forEach(function (key, touch) {
  68479. if (touch.pointerId === _this._joystickPointerID) {
  68480. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  68481. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  68482. VirtualJoystick.vjCanvasContext.beginPath();
  68483. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68484. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68485. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  68486. VirtualJoystick.vjCanvasContext.stroke();
  68487. VirtualJoystick.vjCanvasContext.closePath();
  68488. VirtualJoystick.vjCanvasContext.beginPath();
  68489. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68490. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68491. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  68492. VirtualJoystick.vjCanvasContext.stroke();
  68493. VirtualJoystick.vjCanvasContext.closePath();
  68494. VirtualJoystick.vjCanvasContext.beginPath();
  68495. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68496. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  68497. VirtualJoystick.vjCanvasContext.stroke();
  68498. VirtualJoystick.vjCanvasContext.closePath();
  68499. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  68500. }
  68501. else {
  68502. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68503. VirtualJoystick.vjCanvasContext.beginPath();
  68504. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  68505. VirtualJoystick.vjCanvasContext.beginPath();
  68506. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  68507. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68508. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  68509. VirtualJoystick.vjCanvasContext.stroke();
  68510. VirtualJoystick.vjCanvasContext.closePath();
  68511. touch.prevX = touch.x;
  68512. touch.prevY = touch.y;
  68513. }
  68514. ;
  68515. });
  68516. }
  68517. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68518. };
  68519. VirtualJoystick.prototype.releaseCanvas = function () {
  68520. if (VirtualJoystick.vjCanvas) {
  68521. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  68522. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  68523. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  68524. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  68525. window.removeEventListener("resize", this._onResize);
  68526. document.body.removeChild(VirtualJoystick.vjCanvas);
  68527. VirtualJoystick.vjCanvas = null;
  68528. }
  68529. };
  68530. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  68531. VirtualJoystick._globalJoystickIndex = 0;
  68532. return VirtualJoystick;
  68533. }());
  68534. BABYLON.VirtualJoystick = VirtualJoystick;
  68535. })(BABYLON || (BABYLON = {}));
  68536. //# sourceMappingURL=babylon.virtualJoystick.js.map
  68537. var BABYLON;
  68538. (function (BABYLON) {
  68539. // We're mainly based on the logic defined into the FreeCamera code
  68540. var VirtualJoysticksCamera = (function (_super) {
  68541. __extends(VirtualJoysticksCamera, _super);
  68542. function VirtualJoysticksCamera(name, position, scene) {
  68543. var _this = _super.call(this, name, position, scene) || this;
  68544. _this.inputs.addVirtualJoystick();
  68545. return _this;
  68546. }
  68547. VirtualJoysticksCamera.prototype.getClassName = function () {
  68548. return "VirtualJoysticksCamera";
  68549. };
  68550. return VirtualJoysticksCamera;
  68551. }(BABYLON.FreeCamera));
  68552. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  68553. })(BABYLON || (BABYLON = {}));
  68554. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  68555. var BABYLON;
  68556. (function (BABYLON) {
  68557. var FreeCameraVirtualJoystickInput = (function () {
  68558. function FreeCameraVirtualJoystickInput() {
  68559. }
  68560. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  68561. return this._leftjoystick;
  68562. };
  68563. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  68564. return this._rightjoystick;
  68565. };
  68566. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  68567. if (this._leftjoystick) {
  68568. var camera = this.camera;
  68569. var speed = camera._computeLocalCameraSpeed() * 50;
  68570. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  68571. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  68572. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  68573. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  68574. if (!this._leftjoystick.pressed) {
  68575. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  68576. }
  68577. if (!this._rightjoystick.pressed) {
  68578. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  68579. }
  68580. }
  68581. };
  68582. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  68583. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  68584. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  68585. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  68586. this._leftjoystick.setJoystickSensibility(0.15);
  68587. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  68588. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  68589. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  68590. this._rightjoystick.reverseUpDown = true;
  68591. this._rightjoystick.setJoystickSensibility(0.05);
  68592. this._rightjoystick.setJoystickColor("yellow");
  68593. };
  68594. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  68595. this._leftjoystick.releaseCanvas();
  68596. this._rightjoystick.releaseCanvas();
  68597. };
  68598. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  68599. return "FreeCameraVirtualJoystickInput";
  68600. };
  68601. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  68602. return "virtualJoystick";
  68603. };
  68604. return FreeCameraVirtualJoystickInput;
  68605. }());
  68606. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  68607. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  68608. })(BABYLON || (BABYLON = {}));
  68609. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  68610. var BABYLON;
  68611. (function (BABYLON) {
  68612. var SimplificationSettings = (function () {
  68613. function SimplificationSettings(quality, distance, optimizeMesh) {
  68614. this.quality = quality;
  68615. this.distance = distance;
  68616. this.optimizeMesh = optimizeMesh;
  68617. }
  68618. return SimplificationSettings;
  68619. }());
  68620. BABYLON.SimplificationSettings = SimplificationSettings;
  68621. var SimplificationQueue = (function () {
  68622. function SimplificationQueue() {
  68623. this.running = false;
  68624. this._simplificationArray = [];
  68625. }
  68626. SimplificationQueue.prototype.addTask = function (task) {
  68627. this._simplificationArray.push(task);
  68628. };
  68629. SimplificationQueue.prototype.executeNext = function () {
  68630. var task = this._simplificationArray.pop();
  68631. if (task) {
  68632. this.running = true;
  68633. this.runSimplification(task);
  68634. }
  68635. else {
  68636. this.running = false;
  68637. }
  68638. };
  68639. SimplificationQueue.prototype.runSimplification = function (task) {
  68640. var _this = this;
  68641. if (task.parallelProcessing) {
  68642. //parallel simplifier
  68643. task.settings.forEach(function (setting) {
  68644. var simplifier = _this.getSimplifier(task);
  68645. simplifier.simplify(setting, function (newMesh) {
  68646. task.mesh.addLODLevel(setting.distance, newMesh);
  68647. newMesh.isVisible = true;
  68648. //check if it is the last
  68649. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  68650. //all done, run the success callback.
  68651. task.successCallback();
  68652. }
  68653. _this.executeNext();
  68654. });
  68655. });
  68656. }
  68657. else {
  68658. //single simplifier.
  68659. var simplifier = this.getSimplifier(task);
  68660. var runDecimation = function (setting, callback) {
  68661. simplifier.simplify(setting, function (newMesh) {
  68662. task.mesh.addLODLevel(setting.distance, newMesh);
  68663. newMesh.isVisible = true;
  68664. //run the next quality level
  68665. callback();
  68666. });
  68667. };
  68668. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  68669. runDecimation(task.settings[loop.index], function () {
  68670. loop.executeNext();
  68671. });
  68672. }, function () {
  68673. //execution ended, run the success callback.
  68674. if (task.successCallback) {
  68675. task.successCallback();
  68676. }
  68677. _this.executeNext();
  68678. });
  68679. }
  68680. };
  68681. SimplificationQueue.prototype.getSimplifier = function (task) {
  68682. switch (task.simplificationType) {
  68683. case SimplificationType.QUADRATIC:
  68684. default:
  68685. return new QuadraticErrorSimplification(task.mesh);
  68686. }
  68687. };
  68688. return SimplificationQueue;
  68689. }());
  68690. BABYLON.SimplificationQueue = SimplificationQueue;
  68691. /**
  68692. * The implemented types of simplification.
  68693. * At the moment only Quadratic Error Decimation is implemented.
  68694. */
  68695. var SimplificationType;
  68696. (function (SimplificationType) {
  68697. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  68698. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  68699. var DecimationTriangle = (function () {
  68700. function DecimationTriangle(vertices) {
  68701. this.vertices = vertices;
  68702. this.error = new Array(4);
  68703. this.deleted = false;
  68704. this.isDirty = false;
  68705. this.deletePending = false;
  68706. this.borderFactor = 0;
  68707. }
  68708. return DecimationTriangle;
  68709. }());
  68710. BABYLON.DecimationTriangle = DecimationTriangle;
  68711. var DecimationVertex = (function () {
  68712. function DecimationVertex(position, id) {
  68713. this.position = position;
  68714. this.id = id;
  68715. this.isBorder = true;
  68716. this.q = new QuadraticMatrix();
  68717. this.triangleCount = 0;
  68718. this.triangleStart = 0;
  68719. this.originalOffsets = [];
  68720. }
  68721. DecimationVertex.prototype.updatePosition = function (newPosition) {
  68722. this.position.copyFrom(newPosition);
  68723. };
  68724. return DecimationVertex;
  68725. }());
  68726. BABYLON.DecimationVertex = DecimationVertex;
  68727. var QuadraticMatrix = (function () {
  68728. function QuadraticMatrix(data) {
  68729. this.data = new Array(10);
  68730. for (var i = 0; i < 10; ++i) {
  68731. if (data && data[i]) {
  68732. this.data[i] = data[i];
  68733. }
  68734. else {
  68735. this.data[i] = 0;
  68736. }
  68737. }
  68738. }
  68739. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  68740. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  68741. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  68742. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  68743. return det;
  68744. };
  68745. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  68746. for (var i = 0; i < 10; ++i) {
  68747. this.data[i] += matrix.data[i];
  68748. }
  68749. };
  68750. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  68751. for (var i = 0; i < 10; ++i) {
  68752. this.data[i] += data[i];
  68753. }
  68754. };
  68755. QuadraticMatrix.prototype.add = function (matrix) {
  68756. var m = new QuadraticMatrix();
  68757. for (var i = 0; i < 10; ++i) {
  68758. m.data[i] = this.data[i] + matrix.data[i];
  68759. }
  68760. return m;
  68761. };
  68762. QuadraticMatrix.FromData = function (a, b, c, d) {
  68763. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  68764. };
  68765. //returning an array to avoid garbage collection
  68766. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  68767. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  68768. };
  68769. return QuadraticMatrix;
  68770. }());
  68771. BABYLON.QuadraticMatrix = QuadraticMatrix;
  68772. var Reference = (function () {
  68773. function Reference(vertexId, triangleId) {
  68774. this.vertexId = vertexId;
  68775. this.triangleId = triangleId;
  68776. }
  68777. return Reference;
  68778. }());
  68779. BABYLON.Reference = Reference;
  68780. /**
  68781. * An implementation of the Quadratic Error simplification algorithm.
  68782. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  68783. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  68784. * @author RaananW
  68785. */
  68786. var QuadraticErrorSimplification = (function () {
  68787. function QuadraticErrorSimplification(_mesh) {
  68788. this._mesh = _mesh;
  68789. this.initialized = false;
  68790. this.syncIterations = 5000;
  68791. this.aggressiveness = 7;
  68792. this.decimationIterations = 100;
  68793. this.boundingBoxEpsilon = BABYLON.Epsilon;
  68794. }
  68795. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  68796. var _this = this;
  68797. this.initDecimatedMesh();
  68798. //iterating through the submeshes array, one after the other.
  68799. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  68800. _this.initWithMesh(loop.index, function () {
  68801. _this.runDecimation(settings, loop.index, function () {
  68802. loop.executeNext();
  68803. });
  68804. }, settings.optimizeMesh);
  68805. }, function () {
  68806. setTimeout(function () {
  68807. successCallback(_this._reconstructedMesh);
  68808. }, 0);
  68809. });
  68810. };
  68811. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  68812. var _this = this;
  68813. var gCount = 0;
  68814. triangle.vertices.forEach(function (vertex) {
  68815. var count = 0;
  68816. var vPos = vertex.position;
  68817. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  68818. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  68819. ++count;
  68820. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  68821. ++count;
  68822. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  68823. ++count;
  68824. if (count > 1) {
  68825. ++gCount;
  68826. }
  68827. ;
  68828. });
  68829. if (gCount > 1) {
  68830. console.log(triangle, gCount);
  68831. }
  68832. return gCount > 1;
  68833. };
  68834. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  68835. var _this = this;
  68836. var targetCount = ~~(this.triangles.length * settings.quality);
  68837. var deletedTriangles = 0;
  68838. var triangleCount = this.triangles.length;
  68839. var iterationFunction = function (iteration, callback) {
  68840. setTimeout(function () {
  68841. if (iteration % 5 === 0) {
  68842. _this.updateMesh(iteration === 0);
  68843. }
  68844. for (var i = 0; i < _this.triangles.length; ++i) {
  68845. _this.triangles[i].isDirty = false;
  68846. }
  68847. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  68848. var trianglesIterator = function (i) {
  68849. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  68850. var t = _this.triangles[tIdx];
  68851. if (!t)
  68852. return;
  68853. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  68854. return;
  68855. }
  68856. for (var j = 0; j < 3; ++j) {
  68857. if (t.error[j] < threshold) {
  68858. var deleted0 = [];
  68859. var deleted1 = [];
  68860. var v0 = t.vertices[j];
  68861. var v1 = t.vertices[(j + 1) % 3];
  68862. if (v0.isBorder || v1.isBorder)
  68863. continue;
  68864. var p = BABYLON.Vector3.Zero();
  68865. var n = BABYLON.Vector3.Zero();
  68866. var uv = BABYLON.Vector2.Zero();
  68867. var color = new BABYLON.Color4(0, 0, 0, 1);
  68868. _this.calculateError(v0, v1, p, n, uv, color);
  68869. var delTr = new Array();
  68870. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  68871. continue;
  68872. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  68873. continue;
  68874. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  68875. continue;
  68876. var uniqueArray = new Array();
  68877. delTr.forEach(function (deletedT) {
  68878. if (uniqueArray.indexOf(deletedT) === -1) {
  68879. deletedT.deletePending = true;
  68880. uniqueArray.push(deletedT);
  68881. }
  68882. });
  68883. if (uniqueArray.length % 2 !== 0) {
  68884. continue;
  68885. }
  68886. v0.q = v1.q.add(v0.q);
  68887. v0.updatePosition(p);
  68888. var tStart = _this.references.length;
  68889. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  68890. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  68891. var tCount = _this.references.length - tStart;
  68892. if (tCount <= v0.triangleCount) {
  68893. if (tCount) {
  68894. for (var c = 0; c < tCount; c++) {
  68895. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  68896. }
  68897. }
  68898. }
  68899. else {
  68900. v0.triangleStart = tStart;
  68901. }
  68902. v0.triangleCount = tCount;
  68903. break;
  68904. }
  68905. }
  68906. };
  68907. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  68908. }, 0);
  68909. };
  68910. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  68911. if (triangleCount - deletedTriangles <= targetCount)
  68912. loop.breakLoop();
  68913. else {
  68914. iterationFunction(loop.index, function () {
  68915. loop.executeNext();
  68916. });
  68917. }
  68918. }, function () {
  68919. setTimeout(function () {
  68920. //reconstruct this part of the mesh
  68921. _this.reconstructMesh(submeshIndex);
  68922. successCallback();
  68923. }, 0);
  68924. });
  68925. };
  68926. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  68927. var _this = this;
  68928. this.vertices = [];
  68929. this.triangles = [];
  68930. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68931. var indices = this._mesh.getIndices();
  68932. var submesh = this._mesh.subMeshes[submeshIndex];
  68933. var findInVertices = function (positionToSearch) {
  68934. if (optimizeMesh) {
  68935. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  68936. if (_this.vertices[ii].position.equals(positionToSearch)) {
  68937. return _this.vertices[ii];
  68938. }
  68939. }
  68940. }
  68941. return null;
  68942. };
  68943. var vertexReferences = [];
  68944. var vertexInit = function (i) {
  68945. var offset = i + submesh.verticesStart;
  68946. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  68947. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  68948. vertex.originalOffsets.push(offset);
  68949. if (vertex.id === _this.vertices.length) {
  68950. _this.vertices.push(vertex);
  68951. }
  68952. vertexReferences.push(vertex.id);
  68953. };
  68954. //var totalVertices = mesh.getTotalVertices();
  68955. var totalVertices = submesh.verticesCount;
  68956. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  68957. var indicesInit = function (i) {
  68958. var offset = (submesh.indexStart / 3) + i;
  68959. var pos = (offset * 3);
  68960. var i0 = indices[pos + 0];
  68961. var i1 = indices[pos + 1];
  68962. var i2 = indices[pos + 2];
  68963. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  68964. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  68965. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  68966. var triangle = new DecimationTriangle([v0, v1, v2]);
  68967. triangle.originalOffset = pos;
  68968. _this.triangles.push(triangle);
  68969. };
  68970. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  68971. _this.init(callback);
  68972. });
  68973. });
  68974. };
  68975. QuadraticErrorSimplification.prototype.init = function (callback) {
  68976. var _this = this;
  68977. var triangleInit1 = function (i) {
  68978. var t = _this.triangles[i];
  68979. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  68980. for (var j = 0; j < 3; j++) {
  68981. 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))));
  68982. }
  68983. };
  68984. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  68985. var triangleInit2 = function (i) {
  68986. var t = _this.triangles[i];
  68987. for (var j = 0; j < 3; ++j) {
  68988. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  68989. }
  68990. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68991. };
  68992. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  68993. _this.initialized = true;
  68994. callback();
  68995. });
  68996. });
  68997. };
  68998. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  68999. var newTriangles = [];
  69000. var i;
  69001. for (i = 0; i < this.vertices.length; ++i) {
  69002. this.vertices[i].triangleCount = 0;
  69003. }
  69004. var t;
  69005. var j;
  69006. for (i = 0; i < this.triangles.length; ++i) {
  69007. if (!this.triangles[i].deleted) {
  69008. t = this.triangles[i];
  69009. for (j = 0; j < 3; ++j) {
  69010. t.vertices[j].triangleCount = 1;
  69011. }
  69012. newTriangles.push(t);
  69013. }
  69014. }
  69015. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  69016. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  69017. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  69018. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  69019. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69020. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69021. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69022. var vertexCount = 0;
  69023. for (i = 0; i < this.vertices.length; ++i) {
  69024. var vertex = this.vertices[i];
  69025. vertex.id = vertexCount;
  69026. if (vertex.triangleCount) {
  69027. vertex.originalOffsets.forEach(function (originalOffset) {
  69028. newPositionData.push(vertex.position.x);
  69029. newPositionData.push(vertex.position.y);
  69030. newPositionData.push(vertex.position.z);
  69031. newNormalData.push(normalData[originalOffset * 3]);
  69032. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  69033. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  69034. if (uvs && uvs.length) {
  69035. newUVsData.push(uvs[(originalOffset * 2)]);
  69036. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  69037. }
  69038. else if (colorsData && colorsData.length) {
  69039. newColorsData.push(colorsData[(originalOffset * 4)]);
  69040. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  69041. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  69042. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  69043. }
  69044. ++vertexCount;
  69045. });
  69046. }
  69047. }
  69048. var startingIndex = this._reconstructedMesh.getTotalIndices();
  69049. var startingVertex = this._reconstructedMesh.getTotalVertices();
  69050. var submeshesArray = this._reconstructedMesh.subMeshes;
  69051. this._reconstructedMesh.subMeshes = [];
  69052. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  69053. var originalIndices = this._mesh.getIndices();
  69054. for (i = 0; i < newTriangles.length; ++i) {
  69055. t = newTriangles[i]; //now get the new referencing point for each vertex
  69056. [0, 1, 2].forEach(function (idx) {
  69057. var id = originalIndices[t.originalOffset + idx];
  69058. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  69059. if (offset < 0)
  69060. offset = 0;
  69061. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  69062. });
  69063. }
  69064. //overwriting the old vertex buffers and indices.
  69065. this._reconstructedMesh.setIndices(newIndicesArray);
  69066. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  69067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  69068. if (newUVsData.length > 0)
  69069. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  69070. if (newColorsData.length > 0)
  69071. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  69072. //create submesh
  69073. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  69074. if (submeshIndex > 0) {
  69075. this._reconstructedMesh.subMeshes = [];
  69076. submeshesArray.forEach(function (submesh) {
  69077. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  69078. });
  69079. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  69080. }
  69081. };
  69082. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  69083. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  69084. this._reconstructedMesh.material = this._mesh.material;
  69085. this._reconstructedMesh.parent = this._mesh.parent;
  69086. this._reconstructedMesh.isVisible = false;
  69087. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  69088. };
  69089. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  69090. for (var i = 0; i < vertex1.triangleCount; ++i) {
  69091. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  69092. if (t.deleted)
  69093. continue;
  69094. var s = this.references[vertex1.triangleStart + i].vertexId;
  69095. var v1 = t.vertices[(s + 1) % 3];
  69096. var v2 = t.vertices[(s + 2) % 3];
  69097. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  69098. deletedArray[i] = true;
  69099. delTr.push(t);
  69100. continue;
  69101. }
  69102. var d1 = v1.position.subtract(point);
  69103. d1 = d1.normalize();
  69104. var d2 = v2.position.subtract(point);
  69105. d2 = d2.normalize();
  69106. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  69107. return true;
  69108. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  69109. deletedArray[i] = false;
  69110. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  69111. return true;
  69112. }
  69113. return false;
  69114. };
  69115. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  69116. var newDeleted = deletedTriangles;
  69117. for (var i = 0; i < vertex.triangleCount; ++i) {
  69118. var ref = this.references[vertex.triangleStart + i];
  69119. var t = this.triangles[ref.triangleId];
  69120. if (t.deleted)
  69121. continue;
  69122. if (deletedArray[i] && t.deletePending) {
  69123. t.deleted = true;
  69124. newDeleted++;
  69125. continue;
  69126. }
  69127. t.vertices[ref.vertexId] = origVertex;
  69128. t.isDirty = true;
  69129. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  69130. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  69131. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  69132. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69133. this.references.push(ref);
  69134. }
  69135. return newDeleted;
  69136. };
  69137. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  69138. for (var i = 0; i < this.vertices.length; ++i) {
  69139. var vCount = [];
  69140. var vId = [];
  69141. var v = this.vertices[i];
  69142. var j;
  69143. for (j = 0; j < v.triangleCount; ++j) {
  69144. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  69145. for (var ii = 0; ii < 3; ii++) {
  69146. var ofs = 0;
  69147. var vv = triangle.vertices[ii];
  69148. while (ofs < vCount.length) {
  69149. if (vId[ofs] === vv.id)
  69150. break;
  69151. ++ofs;
  69152. }
  69153. if (ofs === vCount.length) {
  69154. vCount.push(1);
  69155. vId.push(vv.id);
  69156. }
  69157. else {
  69158. vCount[ofs]++;
  69159. }
  69160. }
  69161. }
  69162. for (j = 0; j < vCount.length; ++j) {
  69163. if (vCount[j] === 1) {
  69164. this.vertices[vId[j]].isBorder = true;
  69165. }
  69166. else {
  69167. this.vertices[vId[j]].isBorder = false;
  69168. }
  69169. }
  69170. }
  69171. };
  69172. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  69173. if (identifyBorders === void 0) { identifyBorders = false; }
  69174. var i;
  69175. if (!identifyBorders) {
  69176. var newTrianglesVector = [];
  69177. for (i = 0; i < this.triangles.length; ++i) {
  69178. if (!this.triangles[i].deleted) {
  69179. newTrianglesVector.push(this.triangles[i]);
  69180. }
  69181. }
  69182. this.triangles = newTrianglesVector;
  69183. }
  69184. for (i = 0; i < this.vertices.length; ++i) {
  69185. this.vertices[i].triangleCount = 0;
  69186. this.vertices[i].triangleStart = 0;
  69187. }
  69188. var t;
  69189. var j;
  69190. var v;
  69191. for (i = 0; i < this.triangles.length; ++i) {
  69192. t = this.triangles[i];
  69193. for (j = 0; j < 3; ++j) {
  69194. v = t.vertices[j];
  69195. v.triangleCount++;
  69196. }
  69197. }
  69198. var tStart = 0;
  69199. for (i = 0; i < this.vertices.length; ++i) {
  69200. this.vertices[i].triangleStart = tStart;
  69201. tStart += this.vertices[i].triangleCount;
  69202. this.vertices[i].triangleCount = 0;
  69203. }
  69204. var newReferences = new Array(this.triangles.length * 3);
  69205. for (i = 0; i < this.triangles.length; ++i) {
  69206. t = this.triangles[i];
  69207. for (j = 0; j < 3; ++j) {
  69208. v = t.vertices[j];
  69209. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  69210. v.triangleCount++;
  69211. }
  69212. }
  69213. this.references = newReferences;
  69214. if (identifyBorders) {
  69215. this.identifyBorder();
  69216. }
  69217. };
  69218. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  69219. var x = point.x;
  69220. var y = point.y;
  69221. var z = point.z;
  69222. 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
  69223. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  69224. };
  69225. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  69226. var q = vertex1.q.add(vertex2.q);
  69227. var border = vertex1.isBorder && vertex2.isBorder;
  69228. var error = 0;
  69229. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  69230. if (qDet !== 0 && !border) {
  69231. if (!pointResult) {
  69232. pointResult = BABYLON.Vector3.Zero();
  69233. }
  69234. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  69235. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  69236. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  69237. error = this.vertexError(q, pointResult);
  69238. }
  69239. else {
  69240. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  69241. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  69242. var error1 = this.vertexError(q, vertex1.position);
  69243. var error2 = this.vertexError(q, vertex2.position);
  69244. var error3 = this.vertexError(q, p3);
  69245. error = Math.min(error1, error2, error3);
  69246. if (error === error1) {
  69247. if (pointResult) {
  69248. pointResult.copyFrom(vertex1.position);
  69249. }
  69250. }
  69251. else if (error === error2) {
  69252. if (pointResult) {
  69253. pointResult.copyFrom(vertex2.position);
  69254. }
  69255. }
  69256. else {
  69257. if (pointResult) {
  69258. pointResult.copyFrom(p3);
  69259. }
  69260. }
  69261. }
  69262. return error;
  69263. };
  69264. return QuadraticErrorSimplification;
  69265. }());
  69266. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  69267. })(BABYLON || (BABYLON = {}));
  69268. //# sourceMappingURL=babylon.meshSimplification.js.map
  69269. var BABYLON;
  69270. (function (BABYLON) {
  69271. var Internals;
  69272. (function (Internals) {
  69273. var MeshLODLevel = (function () {
  69274. function MeshLODLevel(distance, mesh) {
  69275. this.distance = distance;
  69276. this.mesh = mesh;
  69277. }
  69278. return MeshLODLevel;
  69279. }());
  69280. Internals.MeshLODLevel = MeshLODLevel;
  69281. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69282. })(BABYLON || (BABYLON = {}));
  69283. //# sourceMappingURL=babylon.meshLODLevel.js.map
  69284. var BABYLON;
  69285. (function (BABYLON) {
  69286. // Standard optimizations
  69287. var SceneOptimization = (function () {
  69288. function SceneOptimization(priority) {
  69289. if (priority === void 0) { priority = 0; }
  69290. this.priority = priority;
  69291. this.apply = function (scene) {
  69292. return true; // Return true if everything that can be done was applied
  69293. };
  69294. }
  69295. return SceneOptimization;
  69296. }());
  69297. BABYLON.SceneOptimization = SceneOptimization;
  69298. var TextureOptimization = (function (_super) {
  69299. __extends(TextureOptimization, _super);
  69300. function TextureOptimization(priority, maximumSize) {
  69301. if (priority === void 0) { priority = 0; }
  69302. if (maximumSize === void 0) { maximumSize = 1024; }
  69303. var _this = _super.call(this, priority) || this;
  69304. _this.priority = priority;
  69305. _this.maximumSize = maximumSize;
  69306. _this.apply = function (scene) {
  69307. var allDone = true;
  69308. for (var index = 0; index < scene.textures.length; index++) {
  69309. var texture = scene.textures[index];
  69310. if (!texture.canRescale || texture.getContext) {
  69311. continue;
  69312. }
  69313. var currentSize = texture.getSize();
  69314. var maxDimension = Math.max(currentSize.width, currentSize.height);
  69315. if (maxDimension > _this.maximumSize) {
  69316. texture.scale(0.5);
  69317. allDone = false;
  69318. }
  69319. }
  69320. return allDone;
  69321. };
  69322. return _this;
  69323. }
  69324. return TextureOptimization;
  69325. }(SceneOptimization));
  69326. BABYLON.TextureOptimization = TextureOptimization;
  69327. var HardwareScalingOptimization = (function (_super) {
  69328. __extends(HardwareScalingOptimization, _super);
  69329. function HardwareScalingOptimization(priority, maximumScale) {
  69330. if (priority === void 0) { priority = 0; }
  69331. if (maximumScale === void 0) { maximumScale = 2; }
  69332. var _this = _super.call(this, priority) || this;
  69333. _this.priority = priority;
  69334. _this.maximumScale = maximumScale;
  69335. _this._currentScale = 1;
  69336. _this.apply = function (scene) {
  69337. _this._currentScale++;
  69338. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  69339. return _this._currentScale >= _this.maximumScale;
  69340. };
  69341. return _this;
  69342. }
  69343. return HardwareScalingOptimization;
  69344. }(SceneOptimization));
  69345. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  69346. var ShadowsOptimization = (function (_super) {
  69347. __extends(ShadowsOptimization, _super);
  69348. function ShadowsOptimization() {
  69349. var _this = _super !== null && _super.apply(this, arguments) || this;
  69350. _this.apply = function (scene) {
  69351. scene.shadowsEnabled = false;
  69352. return true;
  69353. };
  69354. return _this;
  69355. }
  69356. return ShadowsOptimization;
  69357. }(SceneOptimization));
  69358. BABYLON.ShadowsOptimization = ShadowsOptimization;
  69359. var PostProcessesOptimization = (function (_super) {
  69360. __extends(PostProcessesOptimization, _super);
  69361. function PostProcessesOptimization() {
  69362. var _this = _super !== null && _super.apply(this, arguments) || this;
  69363. _this.apply = function (scene) {
  69364. scene.postProcessesEnabled = false;
  69365. return true;
  69366. };
  69367. return _this;
  69368. }
  69369. return PostProcessesOptimization;
  69370. }(SceneOptimization));
  69371. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  69372. var LensFlaresOptimization = (function (_super) {
  69373. __extends(LensFlaresOptimization, _super);
  69374. function LensFlaresOptimization() {
  69375. var _this = _super !== null && _super.apply(this, arguments) || this;
  69376. _this.apply = function (scene) {
  69377. scene.lensFlaresEnabled = false;
  69378. return true;
  69379. };
  69380. return _this;
  69381. }
  69382. return LensFlaresOptimization;
  69383. }(SceneOptimization));
  69384. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  69385. var ParticlesOptimization = (function (_super) {
  69386. __extends(ParticlesOptimization, _super);
  69387. function ParticlesOptimization() {
  69388. var _this = _super !== null && _super.apply(this, arguments) || this;
  69389. _this.apply = function (scene) {
  69390. scene.particlesEnabled = false;
  69391. return true;
  69392. };
  69393. return _this;
  69394. }
  69395. return ParticlesOptimization;
  69396. }(SceneOptimization));
  69397. BABYLON.ParticlesOptimization = ParticlesOptimization;
  69398. var RenderTargetsOptimization = (function (_super) {
  69399. __extends(RenderTargetsOptimization, _super);
  69400. function RenderTargetsOptimization() {
  69401. var _this = _super !== null && _super.apply(this, arguments) || this;
  69402. _this.apply = function (scene) {
  69403. scene.renderTargetsEnabled = false;
  69404. return true;
  69405. };
  69406. return _this;
  69407. }
  69408. return RenderTargetsOptimization;
  69409. }(SceneOptimization));
  69410. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  69411. var MergeMeshesOptimization = (function (_super) {
  69412. __extends(MergeMeshesOptimization, _super);
  69413. function MergeMeshesOptimization() {
  69414. var _this = _super !== null && _super.apply(this, arguments) || this;
  69415. _this._canBeMerged = function (abstractMesh) {
  69416. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  69417. return false;
  69418. }
  69419. var mesh = abstractMesh;
  69420. if (!mesh.isVisible || !mesh.isEnabled()) {
  69421. return false;
  69422. }
  69423. if (mesh.instances.length > 0) {
  69424. return false;
  69425. }
  69426. if (mesh.skeleton || mesh.hasLODLevels) {
  69427. return false;
  69428. }
  69429. if (mesh.parent) {
  69430. return false;
  69431. }
  69432. return true;
  69433. };
  69434. _this.apply = function (scene, updateSelectionTree) {
  69435. var globalPool = scene.meshes.slice(0);
  69436. var globalLength = globalPool.length;
  69437. for (var index = 0; index < globalLength; index++) {
  69438. var currentPool = new Array();
  69439. var current = globalPool[index];
  69440. // Checks
  69441. if (!_this._canBeMerged(current)) {
  69442. continue;
  69443. }
  69444. currentPool.push(current);
  69445. // Find compatible meshes
  69446. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  69447. var otherMesh = globalPool[subIndex];
  69448. if (!_this._canBeMerged(otherMesh)) {
  69449. continue;
  69450. }
  69451. if (otherMesh.material !== current.material) {
  69452. continue;
  69453. }
  69454. if (otherMesh.checkCollisions !== current.checkCollisions) {
  69455. continue;
  69456. }
  69457. currentPool.push(otherMesh);
  69458. globalLength--;
  69459. globalPool.splice(subIndex, 1);
  69460. subIndex--;
  69461. }
  69462. if (currentPool.length < 2) {
  69463. continue;
  69464. }
  69465. // Merge meshes
  69466. BABYLON.Mesh.MergeMeshes(currentPool);
  69467. }
  69468. if (updateSelectionTree != undefined) {
  69469. if (updateSelectionTree) {
  69470. scene.createOrUpdateSelectionOctree();
  69471. }
  69472. }
  69473. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  69474. scene.createOrUpdateSelectionOctree();
  69475. }
  69476. return true;
  69477. };
  69478. return _this;
  69479. }
  69480. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  69481. get: function () {
  69482. return MergeMeshesOptimization._UpdateSelectionTree;
  69483. },
  69484. set: function (value) {
  69485. MergeMeshesOptimization._UpdateSelectionTree = value;
  69486. },
  69487. enumerable: true,
  69488. configurable: true
  69489. });
  69490. MergeMeshesOptimization._UpdateSelectionTree = false;
  69491. return MergeMeshesOptimization;
  69492. }(SceneOptimization));
  69493. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  69494. // Options
  69495. var SceneOptimizerOptions = (function () {
  69496. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  69497. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  69498. if (trackerDuration === void 0) { trackerDuration = 2000; }
  69499. this.targetFrameRate = targetFrameRate;
  69500. this.trackerDuration = trackerDuration;
  69501. this.optimizations = new Array();
  69502. }
  69503. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  69504. var result = new SceneOptimizerOptions(targetFrameRate);
  69505. var priority = 0;
  69506. result.optimizations.push(new MergeMeshesOptimization(priority));
  69507. result.optimizations.push(new ShadowsOptimization(priority));
  69508. result.optimizations.push(new LensFlaresOptimization(priority));
  69509. // Next priority
  69510. priority++;
  69511. result.optimizations.push(new PostProcessesOptimization(priority));
  69512. result.optimizations.push(new ParticlesOptimization(priority));
  69513. // Next priority
  69514. priority++;
  69515. result.optimizations.push(new TextureOptimization(priority, 1024));
  69516. return result;
  69517. };
  69518. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  69519. var result = new SceneOptimizerOptions(targetFrameRate);
  69520. var priority = 0;
  69521. result.optimizations.push(new MergeMeshesOptimization(priority));
  69522. result.optimizations.push(new ShadowsOptimization(priority));
  69523. result.optimizations.push(new LensFlaresOptimization(priority));
  69524. // Next priority
  69525. priority++;
  69526. result.optimizations.push(new PostProcessesOptimization(priority));
  69527. result.optimizations.push(new ParticlesOptimization(priority));
  69528. // Next priority
  69529. priority++;
  69530. result.optimizations.push(new TextureOptimization(priority, 512));
  69531. // Next priority
  69532. priority++;
  69533. result.optimizations.push(new RenderTargetsOptimization(priority));
  69534. // Next priority
  69535. priority++;
  69536. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  69537. return result;
  69538. };
  69539. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  69540. var result = new SceneOptimizerOptions(targetFrameRate);
  69541. var priority = 0;
  69542. result.optimizations.push(new MergeMeshesOptimization(priority));
  69543. result.optimizations.push(new ShadowsOptimization(priority));
  69544. result.optimizations.push(new LensFlaresOptimization(priority));
  69545. // Next priority
  69546. priority++;
  69547. result.optimizations.push(new PostProcessesOptimization(priority));
  69548. result.optimizations.push(new ParticlesOptimization(priority));
  69549. // Next priority
  69550. priority++;
  69551. result.optimizations.push(new TextureOptimization(priority, 256));
  69552. // Next priority
  69553. priority++;
  69554. result.optimizations.push(new RenderTargetsOptimization(priority));
  69555. // Next priority
  69556. priority++;
  69557. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  69558. return result;
  69559. };
  69560. return SceneOptimizerOptions;
  69561. }());
  69562. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  69563. // Scene optimizer tool
  69564. var SceneOptimizer = (function () {
  69565. function SceneOptimizer() {
  69566. }
  69567. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  69568. // TODO: add an epsilon
  69569. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  69570. if (onSuccess) {
  69571. onSuccess();
  69572. }
  69573. return;
  69574. }
  69575. // Apply current level of optimizations
  69576. var allDone = true;
  69577. var noOptimizationApplied = true;
  69578. for (var index = 0; index < options.optimizations.length; index++) {
  69579. var optimization = options.optimizations[index];
  69580. if (optimization.priority === currentPriorityLevel) {
  69581. noOptimizationApplied = false;
  69582. allDone = allDone && optimization.apply(scene);
  69583. }
  69584. }
  69585. // If no optimization was applied, this is a failure :(
  69586. if (noOptimizationApplied) {
  69587. if (onFailure) {
  69588. onFailure();
  69589. }
  69590. return;
  69591. }
  69592. // If all optimizations were done, move to next level
  69593. if (allDone) {
  69594. currentPriorityLevel++;
  69595. }
  69596. // Let's the system running for a specific amount of time before checking FPS
  69597. scene.executeWhenReady(function () {
  69598. setTimeout(function () {
  69599. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  69600. }, options.trackerDuration);
  69601. });
  69602. };
  69603. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  69604. if (!options) {
  69605. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  69606. }
  69607. // Let's the system running for a specific amount of time before checking FPS
  69608. scene.executeWhenReady(function () {
  69609. setTimeout(function () {
  69610. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  69611. }, options.trackerDuration);
  69612. });
  69613. };
  69614. return SceneOptimizer;
  69615. }());
  69616. BABYLON.SceneOptimizer = SceneOptimizer;
  69617. })(BABYLON || (BABYLON = {}));
  69618. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  69619. var BABYLON;
  69620. (function (BABYLON) {
  69621. var OutlineRenderer = (function () {
  69622. function OutlineRenderer(scene) {
  69623. this.zOffset = 1;
  69624. this._scene = scene;
  69625. }
  69626. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  69627. var _this = this;
  69628. if (useOverlay === void 0) { useOverlay = false; }
  69629. var scene = this._scene;
  69630. var engine = this._scene.getEngine();
  69631. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69632. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  69633. return;
  69634. }
  69635. var mesh = subMesh.getRenderingMesh();
  69636. var material = subMesh.getMaterial();
  69637. engine.enableEffect(this._effect);
  69638. // Logarithmic depth
  69639. if (material.useLogarithmicDepth) {
  69640. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  69641. }
  69642. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  69643. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  69644. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69645. // Bones
  69646. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69647. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69648. }
  69649. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69650. // Alpha test
  69651. if (material && material.needAlphaTesting()) {
  69652. var alphaTexture = material.getAlphaTestTexture();
  69653. if (alphaTexture) {
  69654. this._effect.setTexture("diffuseSampler", alphaTexture);
  69655. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69656. }
  69657. }
  69658. engine.setZOffset(-this.zOffset);
  69659. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  69660. engine.setZOffset(0);
  69661. };
  69662. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  69663. var defines = [];
  69664. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69665. var mesh = subMesh.getMesh();
  69666. var material = subMesh.getMaterial();
  69667. if (material) {
  69668. // Alpha test
  69669. if (material.needAlphaTesting()) {
  69670. defines.push("#define ALPHATEST");
  69671. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69672. attribs.push(BABYLON.VertexBuffer.UVKind);
  69673. defines.push("#define UV1");
  69674. }
  69675. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69676. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69677. defines.push("#define UV2");
  69678. }
  69679. }
  69680. //Logarithmic depth
  69681. if (material.useLogarithmicDepth) {
  69682. defines.push("#define LOGARITHMICDEPTH");
  69683. }
  69684. }
  69685. // Bones
  69686. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69687. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69688. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69689. if (mesh.numBoneInfluencers > 4) {
  69690. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69691. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69692. }
  69693. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69694. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69695. }
  69696. else {
  69697. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69698. }
  69699. // Instances
  69700. if (useInstances) {
  69701. defines.push("#define INSTANCES");
  69702. attribs.push("world0");
  69703. attribs.push("world1");
  69704. attribs.push("world2");
  69705. attribs.push("world3");
  69706. }
  69707. // Get correct effect
  69708. var join = defines.join("\n");
  69709. if (this._cachedDefines !== join) {
  69710. this._cachedDefines = join;
  69711. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  69712. }
  69713. return this._effect.isReady();
  69714. };
  69715. return OutlineRenderer;
  69716. }());
  69717. BABYLON.OutlineRenderer = OutlineRenderer;
  69718. })(BABYLON || (BABYLON = {}));
  69719. //# sourceMappingURL=babylon.outlineRenderer.js.map
  69720. var BABYLON;
  69721. (function (BABYLON) {
  69722. var FaceAdjacencies = (function () {
  69723. function FaceAdjacencies() {
  69724. this.edges = new Array();
  69725. this.edgesConnectedCount = 0;
  69726. }
  69727. return FaceAdjacencies;
  69728. }());
  69729. var EdgesRenderer = (function () {
  69730. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  69731. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  69732. if (epsilon === void 0) { epsilon = 0.95; }
  69733. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  69734. this.edgesWidthScalerForOrthographic = 1000.0;
  69735. this.edgesWidthScalerForPerspective = 50.0;
  69736. this._linesPositions = new Array();
  69737. this._linesNormals = new Array();
  69738. this._linesIndices = new Array();
  69739. this._buffers = {};
  69740. this._checkVerticesInsteadOfIndices = false;
  69741. this._source = source;
  69742. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  69743. this._epsilon = epsilon;
  69744. this._prepareRessources();
  69745. this._generateEdgesLines();
  69746. }
  69747. EdgesRenderer.prototype._prepareRessources = function () {
  69748. if (this._lineShader) {
  69749. return;
  69750. }
  69751. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  69752. attributes: ["position", "normal"],
  69753. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  69754. });
  69755. this._lineShader.disableDepthWrite = true;
  69756. this._lineShader.backFaceCulling = false;
  69757. };
  69758. EdgesRenderer.prototype._rebuild = function () {
  69759. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69760. if (buffer) {
  69761. buffer._rebuild();
  69762. }
  69763. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69764. if (buffer) {
  69765. buffer._rebuild();
  69766. }
  69767. var scene = this._source.getScene();
  69768. var engine = scene.getEngine();
  69769. this._ib = engine.createIndexBuffer(this._linesIndices);
  69770. };
  69771. EdgesRenderer.prototype.dispose = function () {
  69772. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69773. if (buffer) {
  69774. buffer.dispose();
  69775. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  69776. }
  69777. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69778. if (buffer) {
  69779. buffer.dispose();
  69780. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  69781. }
  69782. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  69783. this._lineShader.dispose();
  69784. };
  69785. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  69786. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  69787. return 0;
  69788. }
  69789. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  69790. return 1;
  69791. }
  69792. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  69793. return 2;
  69794. }
  69795. return -1;
  69796. };
  69797. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  69798. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  69799. return 0;
  69800. }
  69801. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  69802. return 1;
  69803. }
  69804. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  69805. return 2;
  69806. }
  69807. return -1;
  69808. };
  69809. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  69810. var needToCreateLine;
  69811. if (edge === undefined) {
  69812. needToCreateLine = true;
  69813. }
  69814. else {
  69815. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  69816. needToCreateLine = dotProduct < this._epsilon;
  69817. }
  69818. if (needToCreateLine) {
  69819. var offset = this._linesPositions.length / 3;
  69820. var normal = p0.subtract(p1);
  69821. normal.normalize();
  69822. // Positions
  69823. this._linesPositions.push(p0.x);
  69824. this._linesPositions.push(p0.y);
  69825. this._linesPositions.push(p0.z);
  69826. this._linesPositions.push(p0.x);
  69827. this._linesPositions.push(p0.y);
  69828. this._linesPositions.push(p0.z);
  69829. this._linesPositions.push(p1.x);
  69830. this._linesPositions.push(p1.y);
  69831. this._linesPositions.push(p1.z);
  69832. this._linesPositions.push(p1.x);
  69833. this._linesPositions.push(p1.y);
  69834. this._linesPositions.push(p1.z);
  69835. // Normals
  69836. this._linesNormals.push(p1.x);
  69837. this._linesNormals.push(p1.y);
  69838. this._linesNormals.push(p1.z);
  69839. this._linesNormals.push(-1);
  69840. this._linesNormals.push(p1.x);
  69841. this._linesNormals.push(p1.y);
  69842. this._linesNormals.push(p1.z);
  69843. this._linesNormals.push(1);
  69844. this._linesNormals.push(p0.x);
  69845. this._linesNormals.push(p0.y);
  69846. this._linesNormals.push(p0.z);
  69847. this._linesNormals.push(-1);
  69848. this._linesNormals.push(p0.x);
  69849. this._linesNormals.push(p0.y);
  69850. this._linesNormals.push(p0.z);
  69851. this._linesNormals.push(1);
  69852. // Indices
  69853. this._linesIndices.push(offset);
  69854. this._linesIndices.push(offset + 1);
  69855. this._linesIndices.push(offset + 2);
  69856. this._linesIndices.push(offset);
  69857. this._linesIndices.push(offset + 2);
  69858. this._linesIndices.push(offset + 3);
  69859. }
  69860. };
  69861. EdgesRenderer.prototype._generateEdgesLines = function () {
  69862. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69863. var indices = this._source.getIndices();
  69864. // First let's find adjacencies
  69865. var adjacencies = new Array();
  69866. var faceNormals = new Array();
  69867. var index;
  69868. var faceAdjacencies;
  69869. // Prepare faces
  69870. for (index = 0; index < indices.length; index += 3) {
  69871. faceAdjacencies = new FaceAdjacencies();
  69872. var p0Index = indices[index];
  69873. var p1Index = indices[index + 1];
  69874. var p2Index = indices[index + 2];
  69875. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  69876. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  69877. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  69878. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  69879. faceNormal.normalize();
  69880. faceNormals.push(faceNormal);
  69881. adjacencies.push(faceAdjacencies);
  69882. }
  69883. // Scan
  69884. for (index = 0; index < adjacencies.length; index++) {
  69885. faceAdjacencies = adjacencies[index];
  69886. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  69887. var otherFaceAdjacencies = adjacencies[otherIndex];
  69888. if (faceAdjacencies.edgesConnectedCount === 3) {
  69889. break;
  69890. }
  69891. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  69892. continue;
  69893. }
  69894. var otherP0 = indices[otherIndex * 3];
  69895. var otherP1 = indices[otherIndex * 3 + 1];
  69896. var otherP2 = indices[otherIndex * 3 + 2];
  69897. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  69898. var otherEdgeIndex;
  69899. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  69900. continue;
  69901. }
  69902. switch (edgeIndex) {
  69903. case 0:
  69904. if (this._checkVerticesInsteadOfIndices) {
  69905. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69906. }
  69907. else {
  69908. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  69909. }
  69910. break;
  69911. case 1:
  69912. if (this._checkVerticesInsteadOfIndices) {
  69913. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69914. }
  69915. else {
  69916. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  69917. }
  69918. break;
  69919. case 2:
  69920. if (this._checkVerticesInsteadOfIndices) {
  69921. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69922. }
  69923. else {
  69924. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  69925. }
  69926. break;
  69927. }
  69928. if (otherEdgeIndex === -1) {
  69929. continue;
  69930. }
  69931. faceAdjacencies.edges[edgeIndex] = otherIndex;
  69932. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  69933. faceAdjacencies.edgesConnectedCount++;
  69934. otherFaceAdjacencies.edgesConnectedCount++;
  69935. if (faceAdjacencies.edgesConnectedCount === 3) {
  69936. break;
  69937. }
  69938. }
  69939. }
  69940. }
  69941. // Create lines
  69942. for (index = 0; index < adjacencies.length; index++) {
  69943. // 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
  69944. var current = adjacencies[index];
  69945. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  69946. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  69947. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  69948. }
  69949. // Merge into a single mesh
  69950. var engine = this._source.getScene().getEngine();
  69951. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  69952. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  69953. this._ib = engine.createIndexBuffer(this._linesIndices);
  69954. this._indicesCount = this._linesIndices.length;
  69955. };
  69956. EdgesRenderer.prototype.render = function () {
  69957. if (!this._lineShader.isReady()) {
  69958. return;
  69959. }
  69960. var scene = this._source.getScene();
  69961. var engine = scene.getEngine();
  69962. this._lineShader._preBind();
  69963. // VBOs
  69964. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  69965. scene.resetCachedMaterial();
  69966. this._lineShader.setColor4("color", this._source.edgesColor);
  69967. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  69968. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  69969. }
  69970. else {
  69971. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  69972. }
  69973. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  69974. this._lineShader.bind(this._source.getWorldMatrix());
  69975. // Draw order
  69976. engine.draw(true, 0, this._indicesCount);
  69977. this._lineShader.unbind();
  69978. engine.setDepthWrite(true);
  69979. };
  69980. return EdgesRenderer;
  69981. }());
  69982. BABYLON.EdgesRenderer = EdgesRenderer;
  69983. })(BABYLON || (BABYLON = {}));
  69984. //# sourceMappingURL=babylon.edgesRenderer.js.map
  69985. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  69986. /// <reference path="..\Math\babylon.math.ts" />
  69987. var BABYLON;
  69988. (function (BABYLON) {
  69989. /**
  69990. * Special Glow Blur post process only blurring the alpha channel
  69991. * It enforces keeping the most luminous color in the color channel.
  69992. */
  69993. var GlowBlurPostProcess = (function (_super) {
  69994. __extends(GlowBlurPostProcess, _super);
  69995. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  69996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69997. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  69998. _this.direction = direction;
  69999. _this.kernel = kernel;
  70000. _this.onApplyObservable.add(function (effect) {
  70001. effect.setFloat2("screenSize", _this.width, _this.height);
  70002. effect.setVector2("direction", _this.direction);
  70003. effect.setFloat("blurWidth", _this.kernel);
  70004. });
  70005. return _this;
  70006. }
  70007. return GlowBlurPostProcess;
  70008. }(BABYLON.PostProcess));
  70009. /**
  70010. * The highlight layer Helps adding a glow effect around a mesh.
  70011. *
  70012. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  70013. * glowy meshes to your scene.
  70014. *
  70015. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  70016. */
  70017. var HighlightLayer = (function () {
  70018. /**
  70019. * Instantiates a new highlight Layer and references it to the scene..
  70020. * @param name The name of the layer
  70021. * @param scene The scene to use the layer in
  70022. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  70023. */
  70024. function HighlightLayer(name, scene, options) {
  70025. this.name = name;
  70026. this._vertexBuffers = {};
  70027. this._mainTextureDesiredSize = { width: 0, height: 0 };
  70028. this._meshes = {};
  70029. this._maxSize = 0;
  70030. this._shouldRender = false;
  70031. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  70032. this._excludedMeshes = {};
  70033. /**
  70034. * Specifies whether or not the inner glow is ACTIVE in the layer.
  70035. */
  70036. this.innerGlow = true;
  70037. /**
  70038. * Specifies whether or not the outer glow is ACTIVE in the layer.
  70039. */
  70040. this.outerGlow = true;
  70041. /**
  70042. * Specifies wether the highlight layer is enabled or not.
  70043. */
  70044. this.isEnabled = true;
  70045. /**
  70046. * An event triggered when the highlight layer has been disposed.
  70047. * @type {BABYLON.Observable}
  70048. */
  70049. this.onDisposeObservable = new BABYLON.Observable();
  70050. /**
  70051. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  70052. * @type {BABYLON.Observable}
  70053. */
  70054. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  70055. /**
  70056. * An event triggered when the highlight layer is being blurred.
  70057. * @type {BABYLON.Observable}
  70058. */
  70059. this.onBeforeBlurObservable = new BABYLON.Observable();
  70060. /**
  70061. * An event triggered when the highlight layer has been blurred.
  70062. * @type {BABYLON.Observable}
  70063. */
  70064. this.onAfterBlurObservable = new BABYLON.Observable();
  70065. /**
  70066. * An event triggered when the glowing blurred texture is being merged in the scene.
  70067. * @type {BABYLON.Observable}
  70068. */
  70069. this.onBeforeComposeObservable = new BABYLON.Observable();
  70070. /**
  70071. * An event triggered when the glowing blurred texture has been merged in the scene.
  70072. * @type {BABYLON.Observable}
  70073. */
  70074. this.onAfterComposeObservable = new BABYLON.Observable();
  70075. /**
  70076. * An event triggered when the highlight layer changes its size.
  70077. * @type {BABYLON.Observable}
  70078. */
  70079. this.onSizeChangedObservable = new BABYLON.Observable();
  70080. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70081. var engine = scene.getEngine();
  70082. this._engine = engine;
  70083. this._maxSize = this._engine.getCaps().maxTextureSize;
  70084. this._scene.highlightLayers.push(this);
  70085. // Warn on stencil.
  70086. if (!this._engine.isStencilEnable) {
  70087. 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 }");
  70088. }
  70089. // Adapt options
  70090. this._options = options || {
  70091. mainTextureRatio: 0.5,
  70092. blurTextureSizeRatio: 0.5,
  70093. blurHorizontalSize: 1.0,
  70094. blurVerticalSize: 1.0,
  70095. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  70096. };
  70097. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  70098. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  70099. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  70100. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  70101. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  70102. // VBO
  70103. var vertices = [];
  70104. vertices.push(1, 1);
  70105. vertices.push(-1, 1);
  70106. vertices.push(-1, -1);
  70107. vertices.push(1, -1);
  70108. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70110. this._createIndexBuffer();
  70111. // Effect
  70112. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  70113. // Render target
  70114. this.setMainTextureSize();
  70115. // Create Textures and post processes
  70116. this.createTextureAndPostProcesses();
  70117. }
  70118. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  70119. /**
  70120. * Gets the horizontal size of the blur.
  70121. */
  70122. get: function () {
  70123. return this._horizontalBlurPostprocess.kernel;
  70124. },
  70125. /**
  70126. * Specifies the horizontal size of the blur.
  70127. */
  70128. set: function (value) {
  70129. this._horizontalBlurPostprocess.kernel = value;
  70130. },
  70131. enumerable: true,
  70132. configurable: true
  70133. });
  70134. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  70135. /**
  70136. * Gets the vertical size of the blur.
  70137. */
  70138. get: function () {
  70139. return this._verticalBlurPostprocess.kernel;
  70140. },
  70141. /**
  70142. * Specifies the vertical size of the blur.
  70143. */
  70144. set: function (value) {
  70145. this._verticalBlurPostprocess.kernel = value;
  70146. },
  70147. enumerable: true,
  70148. configurable: true
  70149. });
  70150. Object.defineProperty(HighlightLayer.prototype, "camera", {
  70151. /**
  70152. * Gets the camera attached to the layer.
  70153. */
  70154. get: function () {
  70155. return this._options.camera;
  70156. },
  70157. enumerable: true,
  70158. configurable: true
  70159. });
  70160. HighlightLayer.prototype._createIndexBuffer = function () {
  70161. var engine = this._scene.getEngine();
  70162. // Indices
  70163. var indices = [];
  70164. indices.push(0);
  70165. indices.push(1);
  70166. indices.push(2);
  70167. indices.push(0);
  70168. indices.push(2);
  70169. indices.push(3);
  70170. this._indexBuffer = engine.createIndexBuffer(indices);
  70171. };
  70172. HighlightLayer.prototype._rebuild = function () {
  70173. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70174. this._createIndexBuffer();
  70175. };
  70176. /**
  70177. * Creates the render target textures and post processes used in the highlight layer.
  70178. */
  70179. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  70180. var _this = this;
  70181. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  70182. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  70183. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  70184. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  70185. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  70186. width: this._mainTextureDesiredSize.width,
  70187. height: this._mainTextureDesiredSize.height
  70188. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70189. this._mainTexture.activeCamera = this._options.camera;
  70190. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70191. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70192. this._mainTexture.anisotropicFilteringLevel = 1;
  70193. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70194. this._mainTexture.renderParticles = false;
  70195. this._mainTexture.renderList = null;
  70196. this._mainTexture.ignoreCameraViewport = true;
  70197. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  70198. width: blurTextureWidth,
  70199. height: blurTextureHeight
  70200. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70201. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70202. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70203. this._blurTexture.anisotropicFilteringLevel = 16;
  70204. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70205. this._blurTexture.renderParticles = false;
  70206. this._blurTexture.ignoreCameraViewport = true;
  70207. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70208. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  70209. effect.setTexture("textureSampler", _this._mainTexture);
  70210. });
  70211. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  70212. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70213. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70214. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70215. });
  70216. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70217. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70218. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70219. });
  70220. }
  70221. else {
  70222. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70223. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70224. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70225. });
  70226. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70227. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70228. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70229. });
  70230. }
  70231. this._mainTexture.onAfterUnbindObservable.add(function () {
  70232. _this.onBeforeBlurObservable.notifyObservers(_this);
  70233. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  70234. _this.onAfterBlurObservable.notifyObservers(_this);
  70235. });
  70236. // Custom render function
  70237. var renderSubMesh = function (subMesh) {
  70238. var mesh = subMesh.getRenderingMesh();
  70239. var scene = _this._scene;
  70240. var engine = scene.getEngine();
  70241. // Culling
  70242. engine.setState(subMesh.getMaterial().backFaceCulling);
  70243. // Managing instances
  70244. var batch = mesh._getInstancesRenderList(subMesh._id);
  70245. if (batch.mustReturn) {
  70246. return;
  70247. }
  70248. // Excluded Mesh
  70249. if (_this._excludedMeshes[mesh.uniqueId]) {
  70250. return;
  70251. }
  70252. ;
  70253. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70254. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  70255. var material = subMesh.getMaterial();
  70256. var emissiveTexture = null;
  70257. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  70258. emissiveTexture = material.emissiveTexture;
  70259. }
  70260. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  70261. engine.enableEffect(_this._glowMapGenerationEffect);
  70262. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  70263. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  70264. if (highlightLayerMesh) {
  70265. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  70266. }
  70267. else {
  70268. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  70269. }
  70270. // Alpha test
  70271. if (material && material.needAlphaTesting()) {
  70272. var alphaTexture = material.getAlphaTestTexture();
  70273. if (alphaTexture) {
  70274. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  70275. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70276. }
  70277. }
  70278. // Glow emissive only
  70279. if (emissiveTexture) {
  70280. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  70281. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  70282. }
  70283. // Bones
  70284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70285. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70286. }
  70287. // Draw
  70288. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  70289. }
  70290. else {
  70291. // Need to reset refresh rate of the shadowMap
  70292. _this._mainTexture.resetRefreshCounter();
  70293. }
  70294. };
  70295. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70296. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  70297. var index;
  70298. var engine = _this._scene.getEngine();
  70299. if (depthOnlySubMeshes.length) {
  70300. engine.setColorWrite(false);
  70301. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70302. renderSubMesh(depthOnlySubMeshes.data[index]);
  70303. }
  70304. engine.setColorWrite(true);
  70305. }
  70306. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70307. renderSubMesh(opaqueSubMeshes.data[index]);
  70308. }
  70309. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70310. renderSubMesh(alphaTestSubMeshes.data[index]);
  70311. }
  70312. for (index = 0; index < transparentSubMeshes.length; index++) {
  70313. renderSubMesh(transparentSubMeshes.data[index]);
  70314. }
  70315. };
  70316. this._mainTexture.onClearObservable.add(function (engine) {
  70317. engine.clear(HighlightLayer.neutralColor, true, true, true);
  70318. });
  70319. };
  70320. /**
  70321. * Checks for the readiness of the element composing the layer.
  70322. * @param subMesh the mesh to check for
  70323. * @param useInstances specify wether or not to use instances to render the mesh
  70324. * @param emissiveTexture the associated emissive texture used to generate the glow
  70325. * @return true if ready otherwise, false
  70326. */
  70327. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  70328. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  70329. return false;
  70330. }
  70331. var defines = [];
  70332. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70333. var mesh = subMesh.getMesh();
  70334. var material = subMesh.getMaterial();
  70335. var uv1 = false;
  70336. var uv2 = false;
  70337. // Alpha test
  70338. if (material && material.needAlphaTesting()) {
  70339. var alphaTexture = material.getAlphaTestTexture();
  70340. if (alphaTexture) {
  70341. defines.push("#define ALPHATEST");
  70342. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70343. alphaTexture.coordinatesIndex === 1) {
  70344. defines.push("#define DIFFUSEUV2");
  70345. uv2 = true;
  70346. }
  70347. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70348. defines.push("#define DIFFUSEUV1");
  70349. uv1 = true;
  70350. }
  70351. }
  70352. }
  70353. // Emissive
  70354. if (emissiveTexture) {
  70355. defines.push("#define EMISSIVE");
  70356. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70357. emissiveTexture.coordinatesIndex === 1) {
  70358. defines.push("#define EMISSIVEUV2");
  70359. uv2 = true;
  70360. }
  70361. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70362. defines.push("#define EMISSIVEUV1");
  70363. uv1 = true;
  70364. }
  70365. }
  70366. if (uv1) {
  70367. attribs.push(BABYLON.VertexBuffer.UVKind);
  70368. defines.push("#define UV1");
  70369. }
  70370. if (uv2) {
  70371. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70372. defines.push("#define UV2");
  70373. }
  70374. // Bones
  70375. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70376. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70377. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70378. if (mesh.numBoneInfluencers > 4) {
  70379. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70380. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70381. }
  70382. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70383. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70384. }
  70385. else {
  70386. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70387. }
  70388. // Instances
  70389. if (useInstances) {
  70390. defines.push("#define INSTANCES");
  70391. attribs.push("world0");
  70392. attribs.push("world1");
  70393. attribs.push("world2");
  70394. attribs.push("world3");
  70395. }
  70396. // Get correct effect
  70397. var join = defines.join("\n");
  70398. if (this._cachedDefines !== join) {
  70399. this._cachedDefines = join;
  70400. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  70401. }
  70402. return this._glowMapGenerationEffect.isReady();
  70403. };
  70404. /**
  70405. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  70406. */
  70407. HighlightLayer.prototype.render = function () {
  70408. var currentEffect = this._glowMapMergeEffect;
  70409. // Check
  70410. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  70411. return;
  70412. var engine = this._scene.getEngine();
  70413. this.onBeforeComposeObservable.notifyObservers(this);
  70414. // Render
  70415. engine.enableEffect(currentEffect);
  70416. engine.setState(false);
  70417. // Cache
  70418. var previousStencilBuffer = engine.getStencilBuffer();
  70419. var previousStencilFunction = engine.getStencilFunction();
  70420. var previousStencilMask = engine.getStencilMask();
  70421. var previousStencilOperationPass = engine.getStencilOperationPass();
  70422. var previousStencilOperationFail = engine.getStencilOperationFail();
  70423. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  70424. var previousAlphaMode = engine.getAlphaMode();
  70425. // Texture
  70426. currentEffect.setTexture("textureSampler", this._blurTexture);
  70427. // VBOs
  70428. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70429. // Stencil operations
  70430. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  70431. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  70432. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  70433. // Draw order
  70434. engine.setAlphaMode(this._options.alphaBlendingMode);
  70435. engine.setStencilMask(0x00);
  70436. engine.setStencilBuffer(true);
  70437. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  70438. if (this.outerGlow) {
  70439. currentEffect.setFloat("offset", 0);
  70440. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  70441. engine.draw(true, 0, 6);
  70442. }
  70443. if (this.innerGlow) {
  70444. currentEffect.setFloat("offset", 1);
  70445. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  70446. engine.draw(true, 0, 6);
  70447. }
  70448. // Restore Cache
  70449. engine.setStencilFunction(previousStencilFunction);
  70450. engine.setStencilMask(previousStencilMask);
  70451. engine.setAlphaMode(previousAlphaMode);
  70452. engine.setStencilBuffer(previousStencilBuffer);
  70453. engine.setStencilOperationPass(previousStencilOperationPass);
  70454. engine.setStencilOperationFail(previousStencilOperationFail);
  70455. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  70456. engine._stencilState.reset();
  70457. this.onAfterComposeObservable.notifyObservers(this);
  70458. // Handle size changes.
  70459. var size = this._mainTexture.getSize();
  70460. this.setMainTextureSize();
  70461. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  70462. // Recreate RTT and post processes on size change.
  70463. this.onSizeChangedObservable.notifyObservers(this);
  70464. this.disposeTextureAndPostProcesses();
  70465. this.createTextureAndPostProcesses();
  70466. }
  70467. };
  70468. /**
  70469. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  70470. * @param mesh The mesh to exclude from the highlight layer
  70471. */
  70472. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  70473. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70474. if (!meshExcluded) {
  70475. this._excludedMeshes[mesh.uniqueId] = {
  70476. mesh: mesh,
  70477. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  70478. mesh.getEngine().setStencilBuffer(false);
  70479. }),
  70480. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  70481. mesh.getEngine().setStencilBuffer(true);
  70482. }),
  70483. };
  70484. }
  70485. };
  70486. /**
  70487. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  70488. * @param mesh The mesh to highlight
  70489. */
  70490. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  70491. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70492. if (meshExcluded) {
  70493. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  70494. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  70495. }
  70496. this._excludedMeshes[mesh.uniqueId] = undefined;
  70497. };
  70498. /**
  70499. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  70500. * @param mesh The mesh to highlight
  70501. * @param color The color of the highlight
  70502. * @param glowEmissiveOnly Extract the glow from the emissive texture
  70503. */
  70504. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  70505. var _this = this;
  70506. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  70507. var meshHighlight = this._meshes[mesh.uniqueId];
  70508. if (meshHighlight) {
  70509. meshHighlight.color = color;
  70510. }
  70511. else {
  70512. this._meshes[mesh.uniqueId] = {
  70513. mesh: mesh,
  70514. color: color,
  70515. // Lambda required for capture due to Observable this context
  70516. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  70517. if (_this._excludedMeshes[mesh.uniqueId]) {
  70518. _this.defaultStencilReference(mesh);
  70519. }
  70520. else {
  70521. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  70522. }
  70523. }),
  70524. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  70525. glowEmissiveOnly: glowEmissiveOnly
  70526. };
  70527. }
  70528. this._shouldRender = true;
  70529. };
  70530. /**
  70531. * Remove a mesh from the highlight layer in order to make it stop glowing.
  70532. * @param mesh The mesh to highlight
  70533. */
  70534. HighlightLayer.prototype.removeMesh = function (mesh) {
  70535. var meshHighlight = this._meshes[mesh.uniqueId];
  70536. if (meshHighlight) {
  70537. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70538. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70539. }
  70540. this._meshes[mesh.uniqueId] = undefined;
  70541. this._shouldRender = false;
  70542. for (var meshHighlightToCheck in this._meshes) {
  70543. if (meshHighlightToCheck) {
  70544. this._shouldRender = true;
  70545. break;
  70546. }
  70547. }
  70548. };
  70549. /**
  70550. * Returns true if the layer contains information to display, otherwise false.
  70551. */
  70552. HighlightLayer.prototype.shouldRender = function () {
  70553. return this.isEnabled && this._shouldRender;
  70554. };
  70555. /**
  70556. * Sets the main texture desired size which is the closest power of two
  70557. * of the engine canvas size.
  70558. */
  70559. HighlightLayer.prototype.setMainTextureSize = function () {
  70560. if (this._options.mainTextureFixedSize) {
  70561. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  70562. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  70563. }
  70564. else {
  70565. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  70566. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  70567. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  70568. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  70569. }
  70570. };
  70571. /**
  70572. * Force the stencil to the normal expected value for none glowing parts
  70573. */
  70574. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  70575. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  70576. };
  70577. /**
  70578. * Dispose only the render target textures and post process.
  70579. */
  70580. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  70581. this._blurTexture.dispose();
  70582. this._mainTexture.dispose();
  70583. this._downSamplePostprocess.dispose();
  70584. this._horizontalBlurPostprocess.dispose();
  70585. this._verticalBlurPostprocess.dispose();
  70586. };
  70587. /**
  70588. * Dispose the highlight layer and free resources.
  70589. */
  70590. HighlightLayer.prototype.dispose = function () {
  70591. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70592. if (vertexBuffer) {
  70593. vertexBuffer.dispose();
  70594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70595. }
  70596. if (this._indexBuffer) {
  70597. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70598. this._indexBuffer = null;
  70599. }
  70600. // Clean textures and post processes
  70601. this.disposeTextureAndPostProcesses();
  70602. // Clean mesh references
  70603. for (var id in this._meshes) {
  70604. var meshHighlight = this._meshes[id];
  70605. if (meshHighlight && meshHighlight.mesh) {
  70606. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70607. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70608. }
  70609. }
  70610. this._meshes = null;
  70611. for (var id in this._excludedMeshes) {
  70612. var meshHighlight = this._excludedMeshes[id];
  70613. if (meshHighlight) {
  70614. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  70615. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  70616. }
  70617. }
  70618. this._excludedMeshes = null;
  70619. // Remove from scene
  70620. var index = this._scene.highlightLayers.indexOf(this, 0);
  70621. if (index > -1) {
  70622. this._scene.highlightLayers.splice(index, 1);
  70623. }
  70624. // Callback
  70625. this.onDisposeObservable.notifyObservers(this);
  70626. this.onDisposeObservable.clear();
  70627. this.onBeforeRenderMainTextureObservable.clear();
  70628. this.onBeforeBlurObservable.clear();
  70629. this.onBeforeComposeObservable.clear();
  70630. this.onAfterComposeObservable.clear();
  70631. this.onSizeChangedObservable.clear();
  70632. };
  70633. /**
  70634. * The neutral color used during the preparation of the glow effect.
  70635. * This is black by default as the blend operation is a blend operation.
  70636. */
  70637. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  70638. /**
  70639. * Stencil value used for glowing meshes.
  70640. */
  70641. HighlightLayer.glowingMeshStencilReference = 0x02;
  70642. /**
  70643. * Stencil value used for the other meshes in the scene.
  70644. */
  70645. HighlightLayer.normalMeshStencilReference = 0x01;
  70646. return HighlightLayer;
  70647. }());
  70648. BABYLON.HighlightLayer = HighlightLayer;
  70649. })(BABYLON || (BABYLON = {}));
  70650. //# sourceMappingURL=babylon.highlightlayer.js.map
  70651. var BABYLON;
  70652. (function (BABYLON) {
  70653. var AssetTaskState;
  70654. (function (AssetTaskState) {
  70655. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  70656. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  70657. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  70658. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  70659. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  70660. var AbstractAssetTask = (function () {
  70661. function AbstractAssetTask() {
  70662. this.isCompleted = false;
  70663. this.taskState = AssetTaskState.INIT;
  70664. }
  70665. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70666. var _this = this;
  70667. this.taskState = AssetTaskState.RUNNING;
  70668. this.runTask(scene, function () {
  70669. _this.onDoneCallback(onSuccess, onError);
  70670. }, function (msg, exception) {
  70671. _this.onErrorCallback(onError, msg, exception);
  70672. });
  70673. };
  70674. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70675. throw new Error("runTask is not implemented");
  70676. };
  70677. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  70678. this.taskState = AssetTaskState.ERROR;
  70679. this.errorObject = {
  70680. message: message,
  70681. exception: exception
  70682. };
  70683. if (this.onError) {
  70684. this.onError(this, message, exception);
  70685. }
  70686. onError();
  70687. };
  70688. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  70689. try {
  70690. this.taskState = AssetTaskState.DONE;
  70691. this.isCompleted = true;
  70692. if (this.onSuccess) {
  70693. this.onSuccess(this);
  70694. }
  70695. onSuccess();
  70696. }
  70697. catch (e) {
  70698. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  70699. }
  70700. };
  70701. return AbstractAssetTask;
  70702. }());
  70703. BABYLON.AbstractAssetTask = AbstractAssetTask;
  70704. var MeshAssetTask = (function (_super) {
  70705. __extends(MeshAssetTask, _super);
  70706. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  70707. var _this = _super.call(this) || this;
  70708. _this.name = name;
  70709. _this.meshesNames = meshesNames;
  70710. _this.rootUrl = rootUrl;
  70711. _this.sceneFilename = sceneFilename;
  70712. return _this;
  70713. }
  70714. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70715. var _this = this;
  70716. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  70717. _this.loadedMeshes = meshes;
  70718. _this.loadedParticleSystems = particleSystems;
  70719. _this.loadedSkeletons = skeletons;
  70720. onSuccess();
  70721. }, null, function (scene, message, exception) {
  70722. onError(message, exception);
  70723. });
  70724. };
  70725. return MeshAssetTask;
  70726. }(AbstractAssetTask));
  70727. BABYLON.MeshAssetTask = MeshAssetTask;
  70728. var TextFileAssetTask = (function (_super) {
  70729. __extends(TextFileAssetTask, _super);
  70730. function TextFileAssetTask(name, url) {
  70731. var _this = _super.call(this) || this;
  70732. _this.name = name;
  70733. _this.url = url;
  70734. return _this;
  70735. }
  70736. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70737. var _this = this;
  70738. BABYLON.Tools.LoadFile(this.url, function (data) {
  70739. _this.text = data;
  70740. onSuccess();
  70741. }, null, scene.database, false, function (request, exception) {
  70742. onError(request.status + " " + request.statusText, exception);
  70743. });
  70744. };
  70745. return TextFileAssetTask;
  70746. }(AbstractAssetTask));
  70747. BABYLON.TextFileAssetTask = TextFileAssetTask;
  70748. var BinaryFileAssetTask = (function (_super) {
  70749. __extends(BinaryFileAssetTask, _super);
  70750. function BinaryFileAssetTask(name, url) {
  70751. var _this = _super.call(this) || this;
  70752. _this.name = name;
  70753. _this.url = url;
  70754. return _this;
  70755. }
  70756. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70757. var _this = this;
  70758. BABYLON.Tools.LoadFile(this.url, function (data) {
  70759. _this.data = data;
  70760. onSuccess();
  70761. }, null, scene.database, true, function (request, exception) {
  70762. onError(request.status + " " + request.statusText, exception);
  70763. });
  70764. };
  70765. return BinaryFileAssetTask;
  70766. }(AbstractAssetTask));
  70767. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  70768. var ImageAssetTask = (function (_super) {
  70769. __extends(ImageAssetTask, _super);
  70770. function ImageAssetTask(name, url) {
  70771. var _this = _super.call(this) || this;
  70772. _this.name = name;
  70773. _this.url = url;
  70774. return _this;
  70775. }
  70776. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70777. var _this = this;
  70778. var img = new Image();
  70779. BABYLON.Tools.SetCorsBehavior(this.url, img);
  70780. img.onload = function () {
  70781. _this.image = img;
  70782. onSuccess();
  70783. };
  70784. img.onerror = function (err) {
  70785. onError("Error loading image", err);
  70786. };
  70787. img.src = this.url;
  70788. };
  70789. return ImageAssetTask;
  70790. }(AbstractAssetTask));
  70791. BABYLON.ImageAssetTask = ImageAssetTask;
  70792. var TextureAssetTask = (function (_super) {
  70793. __extends(TextureAssetTask, _super);
  70794. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  70795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70796. var _this = _super.call(this) || this;
  70797. _this.name = name;
  70798. _this.url = url;
  70799. _this.noMipmap = noMipmap;
  70800. _this.invertY = invertY;
  70801. _this.samplingMode = samplingMode;
  70802. return _this;
  70803. }
  70804. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70805. var onload = function () {
  70806. onSuccess();
  70807. };
  70808. var onerror = function (msg, exception) {
  70809. onError(msg, exception);
  70810. };
  70811. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  70812. };
  70813. return TextureAssetTask;
  70814. }(AbstractAssetTask));
  70815. BABYLON.TextureAssetTask = TextureAssetTask;
  70816. var CubeTextureAssetTask = (function (_super) {
  70817. __extends(CubeTextureAssetTask, _super);
  70818. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  70819. var _this = _super.call(this) || this;
  70820. _this.name = name;
  70821. _this.url = url;
  70822. _this.extensions = extensions;
  70823. _this.noMipmap = noMipmap;
  70824. _this.files = files;
  70825. return _this;
  70826. }
  70827. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70828. var onload = function () {
  70829. onSuccess();
  70830. };
  70831. var onerror = function (msg, exception) {
  70832. onError(msg, exception);
  70833. };
  70834. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  70835. };
  70836. return CubeTextureAssetTask;
  70837. }(AbstractAssetTask));
  70838. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  70839. var HDRCubeTextureAssetTask = (function (_super) {
  70840. __extends(HDRCubeTextureAssetTask, _super);
  70841. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70842. if (noMipmap === void 0) { noMipmap = false; }
  70843. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70844. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70845. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70846. var _this = _super.call(this) || this;
  70847. _this.name = name;
  70848. _this.url = url;
  70849. _this.size = size;
  70850. _this.noMipmap = noMipmap;
  70851. _this.generateHarmonics = generateHarmonics;
  70852. _this.useInGammaSpace = useInGammaSpace;
  70853. _this.usePMREMGenerator = usePMREMGenerator;
  70854. return _this;
  70855. }
  70856. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70857. var onload = function () {
  70858. onSuccess();
  70859. };
  70860. var onerror = function (message, exception) {
  70861. onError(message, exception);
  70862. };
  70863. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  70864. };
  70865. return HDRCubeTextureAssetTask;
  70866. }(AbstractAssetTask));
  70867. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  70868. var AssetsManager = (function () {
  70869. function AssetsManager(scene) {
  70870. this.tasks = new Array();
  70871. this.waitingTasksCount = 0;
  70872. //Observables
  70873. this.onTaskSuccessObservable = new BABYLON.Observable();
  70874. this.onTaskErrorObservable = new BABYLON.Observable();
  70875. this.onTasksDoneObservable = new BABYLON.Observable();
  70876. this.useDefaultLoadingScreen = true;
  70877. this._scene = scene;
  70878. }
  70879. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  70880. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  70881. this.tasks.push(task);
  70882. return task;
  70883. };
  70884. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  70885. var task = new TextFileAssetTask(taskName, url);
  70886. this.tasks.push(task);
  70887. return task;
  70888. };
  70889. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  70890. var task = new BinaryFileAssetTask(taskName, url);
  70891. this.tasks.push(task);
  70892. return task;
  70893. };
  70894. AssetsManager.prototype.addImageTask = function (taskName, url) {
  70895. var task = new ImageAssetTask(taskName, url);
  70896. this.tasks.push(task);
  70897. return task;
  70898. };
  70899. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  70900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70901. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  70902. this.tasks.push(task);
  70903. return task;
  70904. };
  70905. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  70906. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  70907. this.tasks.push(task);
  70908. return task;
  70909. };
  70910. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70911. if (noMipmap === void 0) { noMipmap = false; }
  70912. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70913. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70914. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70915. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  70916. this.tasks.push(task);
  70917. return task;
  70918. };
  70919. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  70920. this.waitingTasksCount--;
  70921. if (this.waitingTasksCount === 0) {
  70922. try {
  70923. if (this.onFinish) {
  70924. this.onFinish(this.tasks);
  70925. }
  70926. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70927. }
  70928. catch (e) {
  70929. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  70930. console.log(e);
  70931. }
  70932. this._scene.getEngine().hideLoadingUI();
  70933. }
  70934. };
  70935. AssetsManager.prototype._runTask = function (task) {
  70936. var _this = this;
  70937. var done = function () {
  70938. try {
  70939. if (_this.onTaskSuccess) {
  70940. _this.onTaskSuccess(task);
  70941. }
  70942. _this.onTaskSuccessObservable.notifyObservers(task);
  70943. _this._decreaseWaitingTasksCount();
  70944. }
  70945. catch (e) {
  70946. error("Error executing task success callbacks", e);
  70947. }
  70948. };
  70949. var error = function (message, exception) {
  70950. task.errorObject = task.errorObject || {
  70951. message: message,
  70952. exception: exception
  70953. };
  70954. if (_this.onTaskError) {
  70955. _this.onTaskError(task);
  70956. }
  70957. _this.onTaskErrorObservable.notifyObservers(task);
  70958. _this._decreaseWaitingTasksCount();
  70959. };
  70960. task.run(this._scene, done, error);
  70961. };
  70962. AssetsManager.prototype.reset = function () {
  70963. this.tasks = new Array();
  70964. return this;
  70965. };
  70966. AssetsManager.prototype.load = function () {
  70967. this.waitingTasksCount = this.tasks.length;
  70968. if (this.waitingTasksCount === 0) {
  70969. if (this.onFinish) {
  70970. this.onFinish(this.tasks);
  70971. }
  70972. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70973. return this;
  70974. }
  70975. if (this.useDefaultLoadingScreen) {
  70976. this._scene.getEngine().displayLoadingUI();
  70977. }
  70978. for (var index = 0; index < this.tasks.length; index++) {
  70979. var task = this.tasks[index];
  70980. this._runTask(task);
  70981. }
  70982. return this;
  70983. };
  70984. return AssetsManager;
  70985. }());
  70986. BABYLON.AssetsManager = AssetsManager;
  70987. })(BABYLON || (BABYLON = {}));
  70988. //# sourceMappingURL=babylon.assetsManager.js.map
  70989. var BABYLON;
  70990. (function (BABYLON) {
  70991. var MapTexture = (function (_super) {
  70992. __extends(MapTexture, _super);
  70993. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  70994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70995. if (useMipMap === void 0) { useMipMap = false; }
  70996. if (margin === void 0) { margin = 0; }
  70997. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  70998. _this.name = name;
  70999. _this._size = size;
  71000. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71001. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71002. // Create the rectPackMap that will allocate portion of the texture
  71003. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  71004. // Create the texture that will store the content
  71005. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  71006. return _this;
  71007. }
  71008. /**
  71009. * Allocate a rectangle of a given size in the texture map
  71010. * @param size the size of the rectangle to allocation
  71011. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  71012. */
  71013. MapTexture.prototype.allocateRect = function (size) {
  71014. return this._rectPackingMap.addRect(size);
  71015. };
  71016. /**
  71017. * Free a given rectangle from the texture map
  71018. * @param rectInfo the instance corresponding to the rect to free.
  71019. */
  71020. MapTexture.prototype.freeRect = function (rectInfo) {
  71021. if (rectInfo) {
  71022. rectInfo.freeContent();
  71023. }
  71024. };
  71025. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  71026. /**
  71027. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  71028. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  71029. * @returns {}
  71030. */
  71031. get: function () {
  71032. return this._rectPackingMap.freeSpace;
  71033. },
  71034. enumerable: true,
  71035. configurable: true
  71036. });
  71037. /**
  71038. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  71039. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  71040. * Don't forget to call unbindTexture when you're done rendering
  71041. * @param rect the zone to render to
  71042. * @param clear true to clear the portion's color/depth data
  71043. */
  71044. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  71045. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  71046. };
  71047. /**
  71048. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  71049. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  71050. * Don't forget to call unbindTexture when you're done rendering
  71051. * @param pos the position into the texture
  71052. * @param size the portion to fit the clip space to
  71053. * @param clear true to clear the portion's color/depth data
  71054. */
  71055. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  71056. var engine = this.getScene().getEngine();
  71057. engine.bindFramebuffer(this._texture);
  71058. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  71059. if (clear) {
  71060. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  71061. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  71062. }
  71063. };
  71064. /**
  71065. * Unbind the texture map from the rendering engine.
  71066. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  71067. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  71068. */
  71069. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  71070. // Dump ?
  71071. if (dumpForDebug) {
  71072. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  71073. }
  71074. var engine = this.getScene().getEngine();
  71075. if (this._replacedViewport) {
  71076. engine.setViewport(this._replacedViewport);
  71077. this._replacedViewport = null;
  71078. }
  71079. engine.unBindFramebuffer(this._texture);
  71080. };
  71081. Object.defineProperty(MapTexture.prototype, "canRescale", {
  71082. get: function () {
  71083. return false;
  71084. },
  71085. enumerable: true,
  71086. configurable: true
  71087. });
  71088. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  71089. // Anyway, there's not much point to use this method for this kind of texture I guess
  71090. MapTexture.prototype.clone = function () {
  71091. return null;
  71092. };
  71093. return MapTexture;
  71094. }(BABYLON.Texture));
  71095. BABYLON.MapTexture = MapTexture;
  71096. })(BABYLON || (BABYLON = {}));
  71097. //# sourceMappingURL=babylon.mapTexture.js.map
  71098. var BABYLON;
  71099. (function (BABYLON) {
  71100. /**
  71101. * This class describe a rectangle that were added to the map.
  71102. * You have access to its coordinates either in pixel or normalized (UV)
  71103. */
  71104. var PackedRect = (function () {
  71105. function PackedRect(root, parent, pos, size) {
  71106. this._pos = pos;
  71107. this._size = size;
  71108. this._root = root;
  71109. this._parent = parent;
  71110. this._contentSize = null;
  71111. this._bottomNode = null;
  71112. this._leftNode = null;
  71113. this._initialSize = null;
  71114. this._rightNode = null;
  71115. }
  71116. Object.defineProperty(PackedRect.prototype, "pos", {
  71117. /**
  71118. * @returns the position of this node into the map
  71119. */
  71120. get: function () {
  71121. return this._pos;
  71122. },
  71123. enumerable: true,
  71124. configurable: true
  71125. });
  71126. Object.defineProperty(PackedRect.prototype, "contentSize", {
  71127. /**
  71128. * @returns the size of the rectangle this node handles
  71129. */
  71130. get: function () {
  71131. return this._contentSize;
  71132. },
  71133. enumerable: true,
  71134. configurable: true
  71135. });
  71136. /**
  71137. * Retrieve the inner position (considering the margin) and stores it into the res object
  71138. * @param res must be a valid Vector2 that will contain the inner position after this call
  71139. */
  71140. PackedRect.prototype.getInnerPosToRef = function (res) {
  71141. var m = this._root._margin;
  71142. res.x = this._pos.x + m;
  71143. res.y = this._pos.y + m;
  71144. };
  71145. /**
  71146. * Retrieve the inner size (considering the margin) and stores it into the res object
  71147. * @param res must be a valid Size that will contain the inner size after this call
  71148. */
  71149. PackedRect.prototype.getInnerSizeToRef = function (res) {
  71150. var m = this._root._margin;
  71151. res.width = this._contentSize.width - (m * 2);
  71152. res.height = this._contentSize.height - (m * 2);
  71153. };
  71154. Object.defineProperty(PackedRect.prototype, "UVs", {
  71155. /**
  71156. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  71157. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  71158. */
  71159. get: function () {
  71160. if (!this._contentSize) {
  71161. throw new Error("Can't compute UVs for this object because it's nor allocated");
  71162. }
  71163. return this.getUVsForCustomSize(this._contentSize);
  71164. },
  71165. enumerable: true,
  71166. configurable: true
  71167. });
  71168. /**
  71169. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  71170. * and then using only a part of the PackRect.
  71171. * This method will return the UVs for this part by given the custom size of what you really use
  71172. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  71173. */
  71174. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  71175. var mainWidth = this._root._size.width;
  71176. var mainHeight = this._root._size.height;
  71177. var margin = this._root._margin;
  71178. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  71179. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  71180. var uvs = new Array();
  71181. uvs.push(topLeft);
  71182. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  71183. uvs.push(rightBottom);
  71184. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  71185. return uvs;
  71186. };
  71187. /**
  71188. * Free this rectangle from the map.
  71189. * Call this method when you no longer need the rectangle to be in the map.
  71190. */
  71191. PackedRect.prototype.freeContent = function () {
  71192. if (!this.contentSize) {
  71193. return;
  71194. }
  71195. this._contentSize = null;
  71196. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  71197. this.attemptDefrag();
  71198. };
  71199. Object.defineProperty(PackedRect.prototype, "isUsed", {
  71200. get: function () {
  71201. return this._contentSize != null || this._leftNode != null;
  71202. },
  71203. enumerable: true,
  71204. configurable: true
  71205. });
  71206. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  71207. var node = this.findNode(contentSize);
  71208. // Not enough space...
  71209. if (!node) {
  71210. return null;
  71211. }
  71212. node.splitNode(contentSize);
  71213. return node;
  71214. };
  71215. PackedRect.prototype.findNode = function (size) {
  71216. var resNode = null;
  71217. var margin = this._root._margin * 2;
  71218. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  71219. if (this.isUsed) {
  71220. if (this._leftNode) {
  71221. resNode = this._leftNode.findNode(size);
  71222. }
  71223. if (!resNode && this._rightNode) {
  71224. resNode = this._rightNode.findNode(size);
  71225. }
  71226. if (!resNode && this._bottomNode) {
  71227. resNode = this._bottomNode.findNode(size);
  71228. }
  71229. }
  71230. else if (this._initialSize) {
  71231. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  71232. resNode = this;
  71233. }
  71234. else {
  71235. return null;
  71236. }
  71237. }
  71238. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  71239. resNode = this;
  71240. }
  71241. return resNode;
  71242. };
  71243. PackedRect.prototype.splitNode = function (contentSize) {
  71244. var cs = PackedRect.TpsSize;
  71245. var margin = this._root._margin * 2;
  71246. cs.copyFrom(contentSize);
  71247. cs.width += margin;
  71248. cs.height += margin;
  71249. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  71250. if (!this._contentSize && this._initialSize) {
  71251. this._contentSize = cs.clone();
  71252. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  71253. return this._leftNode.splitNode(contentSize);
  71254. }
  71255. else {
  71256. this._contentSize = cs.clone();
  71257. this._initialSize = cs.clone();
  71258. if (cs.width !== this._size.width) {
  71259. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  71260. }
  71261. if (cs.height !== this._size.height) {
  71262. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  71263. }
  71264. return this;
  71265. }
  71266. };
  71267. PackedRect.prototype.attemptDefrag = function () {
  71268. if (!this.isUsed && this.isRecursiveFree) {
  71269. this.clearNode();
  71270. if (this._parent) {
  71271. this._parent.attemptDefrag();
  71272. }
  71273. }
  71274. };
  71275. PackedRect.prototype.clearNode = function () {
  71276. this._initialSize = null;
  71277. this._rightNode = null;
  71278. this._bottomNode = null;
  71279. };
  71280. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  71281. get: function () {
  71282. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  71283. },
  71284. enumerable: true,
  71285. configurable: true
  71286. });
  71287. PackedRect.prototype.evalFreeSize = function (size) {
  71288. var levelSize = 0;
  71289. if (!this.isUsed) {
  71290. var margin = this._root._margin;
  71291. var is = this._initialSize;
  71292. if (is) {
  71293. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  71294. }
  71295. else {
  71296. var size_1 = this._size;
  71297. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  71298. }
  71299. }
  71300. if (this._rightNode) {
  71301. levelSize += this._rightNode.evalFreeSize(0);
  71302. }
  71303. if (this._bottomNode) {
  71304. levelSize += this._bottomNode.evalFreeSize(0);
  71305. }
  71306. return levelSize + size;
  71307. };
  71308. PackedRect.TpsSize = BABYLON.Size.Zero();
  71309. return PackedRect;
  71310. }());
  71311. BABYLON.PackedRect = PackedRect;
  71312. /**
  71313. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  71314. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  71315. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  71316. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  71317. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  71318. */
  71319. var RectPackingMap = (function (_super) {
  71320. __extends(RectPackingMap, _super);
  71321. /**
  71322. * Create an instance of the object with a dimension using the given size
  71323. * @param size The dimension of the rectangle that will contain all the sub ones.
  71324. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  71325. */
  71326. function RectPackingMap(size, margin) {
  71327. if (margin === void 0) { margin = 0; }
  71328. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  71329. _this._margin = margin;
  71330. _this._root = _this;
  71331. return _this;
  71332. }
  71333. /**
  71334. * Add a rectangle, finding the best location to store it into the map
  71335. * @param size the dimension of the rectangle to store
  71336. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  71337. */
  71338. RectPackingMap.prototype.addRect = function (size) {
  71339. var node = this.findAndSplitNode(size);
  71340. return node;
  71341. };
  71342. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  71343. /**
  71344. * Return the current space free normalized between [0;1]
  71345. * @returns {}
  71346. */
  71347. get: function () {
  71348. var freeSize = 0;
  71349. freeSize = this.evalFreeSize(freeSize);
  71350. return freeSize / (this._size.width * this._size.height);
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. return RectPackingMap;
  71356. }(PackedRect));
  71357. BABYLON.RectPackingMap = RectPackingMap;
  71358. })(BABYLON || (BABYLON = {}));
  71359. //# sourceMappingURL=babylon.rectPackingMap.js.map
  71360. var BABYLON;
  71361. (function (BABYLON) {
  71362. var serializedGeometries = [];
  71363. var serializeGeometry = function (geometry, serializationGeometries) {
  71364. if (serializedGeometries[geometry.id]) {
  71365. return;
  71366. }
  71367. if (geometry.doNotSerialize) {
  71368. return;
  71369. }
  71370. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  71371. serializationGeometries.boxes.push(geometry.serialize());
  71372. }
  71373. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71374. serializationGeometries.spheres.push(geometry.serialize());
  71375. }
  71376. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71377. serializationGeometries.cylinders.push(geometry.serialize());
  71378. }
  71379. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71380. serializationGeometries.toruses.push(geometry.serialize());
  71381. }
  71382. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71383. serializationGeometries.grounds.push(geometry.serialize());
  71384. }
  71385. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71386. serializationGeometries.planes.push(geometry.serialize());
  71387. }
  71388. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71389. serializationGeometries.torusKnots.push(geometry.serialize());
  71390. }
  71391. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71392. throw new Error("Unknown primitive type");
  71393. }
  71394. else {
  71395. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71396. }
  71397. serializedGeometries[geometry.id] = true;
  71398. };
  71399. var serializeMesh = function (mesh, serializationScene) {
  71400. var serializationObject = {};
  71401. // Geometry
  71402. var geometry = mesh._geometry;
  71403. if (geometry) {
  71404. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71405. // 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
  71406. serializeGeometry(geometry, serializationScene.geometries);
  71407. }
  71408. }
  71409. // Custom
  71410. if (mesh.serialize) {
  71411. mesh.serialize(serializationObject);
  71412. }
  71413. return serializationObject;
  71414. };
  71415. var finalizeSingleMesh = function (mesh, serializationObject) {
  71416. //only works if the mesh is already loaded
  71417. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71418. //serialize material
  71419. if (mesh.material) {
  71420. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71421. serializationObject.materials = serializationObject.materials || [];
  71422. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71423. serializationObject.materials.push(mesh.material.serialize());
  71424. }
  71425. }
  71426. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71427. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71428. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71429. serializationObject.multiMaterials.push(mesh.material.serialize());
  71430. }
  71431. }
  71432. }
  71433. //serialize geometry
  71434. var geometry = mesh._geometry;
  71435. if (geometry) {
  71436. if (!serializationObject.geometries) {
  71437. serializationObject.geometries = {};
  71438. serializationObject.geometries.boxes = [];
  71439. serializationObject.geometries.spheres = [];
  71440. serializationObject.geometries.cylinders = [];
  71441. serializationObject.geometries.toruses = [];
  71442. serializationObject.geometries.grounds = [];
  71443. serializationObject.geometries.planes = [];
  71444. serializationObject.geometries.torusKnots = [];
  71445. serializationObject.geometries.vertexData = [];
  71446. }
  71447. serializeGeometry(geometry, serializationObject.geometries);
  71448. }
  71449. // Skeletons
  71450. if (mesh.skeleton) {
  71451. serializationObject.skeletons = serializationObject.skeletons || [];
  71452. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71453. }
  71454. //serialize the actual mesh
  71455. serializationObject.meshes = serializationObject.meshes || [];
  71456. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71457. }
  71458. };
  71459. var SceneSerializer = (function () {
  71460. function SceneSerializer() {
  71461. }
  71462. SceneSerializer.ClearCache = function () {
  71463. serializedGeometries = [];
  71464. };
  71465. SceneSerializer.Serialize = function (scene) {
  71466. var serializationObject = {};
  71467. SceneSerializer.ClearCache();
  71468. // Scene
  71469. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71470. serializationObject.autoClear = scene.autoClear;
  71471. serializationObject.clearColor = scene.clearColor.asArray();
  71472. serializationObject.ambientColor = scene.ambientColor.asArray();
  71473. serializationObject.gravity = scene.gravity.asArray();
  71474. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71475. serializationObject.workerCollisions = scene.workerCollisions;
  71476. // Fog
  71477. if (scene.fogMode && scene.fogMode !== 0) {
  71478. serializationObject.fogMode = scene.fogMode;
  71479. serializationObject.fogColor = scene.fogColor.asArray();
  71480. serializationObject.fogStart = scene.fogStart;
  71481. serializationObject.fogEnd = scene.fogEnd;
  71482. serializationObject.fogDensity = scene.fogDensity;
  71483. }
  71484. //Physics
  71485. if (scene.isPhysicsEnabled()) {
  71486. serializationObject.physicsEnabled = true;
  71487. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  71488. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  71489. }
  71490. // Metadata
  71491. if (scene.metadata) {
  71492. serializationObject.metadata = scene.metadata;
  71493. }
  71494. // Morph targets
  71495. serializationObject.morphTargetManagers = [];
  71496. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71497. var abstractMesh = _a[_i];
  71498. var manager = abstractMesh.morphTargetManager;
  71499. if (manager) {
  71500. serializationObject.morphTargetManagers.push(manager.serialize());
  71501. }
  71502. }
  71503. // Lights
  71504. serializationObject.lights = [];
  71505. var index;
  71506. var light;
  71507. for (index = 0; index < scene.lights.length; index++) {
  71508. light = scene.lights[index];
  71509. if (!light.doNotSerialize) {
  71510. serializationObject.lights.push(light.serialize());
  71511. }
  71512. }
  71513. // Cameras
  71514. serializationObject.cameras = [];
  71515. for (index = 0; index < scene.cameras.length; index++) {
  71516. var camera = scene.cameras[index];
  71517. if (!camera.doNotSerialize) {
  71518. serializationObject.cameras.push(camera.serialize());
  71519. }
  71520. }
  71521. if (scene.activeCamera) {
  71522. serializationObject.activeCameraID = scene.activeCamera.id;
  71523. }
  71524. // Animations
  71525. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71526. // Materials
  71527. serializationObject.materials = [];
  71528. serializationObject.multiMaterials = [];
  71529. var material;
  71530. for (index = 0; index < scene.materials.length; index++) {
  71531. material = scene.materials[index];
  71532. if (!material.doNotSerialize) {
  71533. serializationObject.materials.push(material.serialize());
  71534. }
  71535. }
  71536. // MultiMaterials
  71537. serializationObject.multiMaterials = [];
  71538. for (index = 0; index < scene.multiMaterials.length; index++) {
  71539. var multiMaterial = scene.multiMaterials[index];
  71540. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71541. }
  71542. // Skeletons
  71543. serializationObject.skeletons = [];
  71544. for (index = 0; index < scene.skeletons.length; index++) {
  71545. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71546. }
  71547. // Geometries
  71548. serializationObject.geometries = {};
  71549. serializationObject.geometries.boxes = [];
  71550. serializationObject.geometries.spheres = [];
  71551. serializationObject.geometries.cylinders = [];
  71552. serializationObject.geometries.toruses = [];
  71553. serializationObject.geometries.grounds = [];
  71554. serializationObject.geometries.planes = [];
  71555. serializationObject.geometries.torusKnots = [];
  71556. serializationObject.geometries.vertexData = [];
  71557. serializedGeometries = [];
  71558. var geometries = scene.getGeometries();
  71559. for (index = 0; index < geometries.length; index++) {
  71560. var geometry = geometries[index];
  71561. if (geometry.isReady()) {
  71562. serializeGeometry(geometry, serializationObject.geometries);
  71563. }
  71564. }
  71565. // Meshes
  71566. serializationObject.meshes = [];
  71567. for (index = 0; index < scene.meshes.length; index++) {
  71568. var abstractMesh = scene.meshes[index];
  71569. if (abstractMesh instanceof BABYLON.Mesh) {
  71570. var mesh = abstractMesh;
  71571. if (!mesh.doNotSerialize) {
  71572. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71573. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71574. }
  71575. }
  71576. }
  71577. }
  71578. // Particles Systems
  71579. serializationObject.particleSystems = [];
  71580. for (index = 0; index < scene.particleSystems.length; index++) {
  71581. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71582. }
  71583. // Lens flares
  71584. serializationObject.lensFlareSystems = [];
  71585. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71586. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71587. }
  71588. // Shadows
  71589. serializationObject.shadowGenerators = [];
  71590. for (index = 0; index < scene.lights.length; index++) {
  71591. light = scene.lights[index];
  71592. var shadowGenerator = light.getShadowGenerator();
  71593. if (shadowGenerator) {
  71594. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71595. }
  71596. }
  71597. // Action Manager
  71598. if (scene.actionManager) {
  71599. serializationObject.actions = scene.actionManager.serialize("scene");
  71600. }
  71601. // Audio
  71602. serializationObject.sounds = [];
  71603. for (index = 0; index < scene.soundTracks.length; index++) {
  71604. var soundtrack = scene.soundTracks[index];
  71605. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71606. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71607. }
  71608. }
  71609. return serializationObject;
  71610. };
  71611. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  71612. if (withParents === void 0) { withParents = false; }
  71613. if (withChildren === void 0) { withChildren = false; }
  71614. var serializationObject = {};
  71615. SceneSerializer.ClearCache();
  71616. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  71617. if (withParents || withChildren) {
  71618. //deliberate for loop! not for each, appended should be processed as well.
  71619. for (var i = 0; i < toSerialize.length; ++i) {
  71620. if (withChildren) {
  71621. toSerialize[i].getDescendants().forEach(function (node) {
  71622. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  71623. toSerialize.push(node);
  71624. }
  71625. });
  71626. }
  71627. //make sure the array doesn't contain the object already
  71628. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  71629. toSerialize.push(toSerialize[i].parent);
  71630. }
  71631. }
  71632. }
  71633. toSerialize.forEach(function (mesh) {
  71634. finalizeSingleMesh(mesh, serializationObject);
  71635. });
  71636. return serializationObject;
  71637. };
  71638. return SceneSerializer;
  71639. }());
  71640. BABYLON.SceneSerializer = SceneSerializer;
  71641. })(BABYLON || (BABYLON = {}));
  71642. //# sourceMappingURL=babylon.sceneSerializer.js.map
  71643. var BABYLON;
  71644. (function (BABYLON) {
  71645. var ReflectionProbe = (function () {
  71646. function ReflectionProbe(name, size, scene, generateMipMaps) {
  71647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71648. var _this = this;
  71649. this.name = name;
  71650. this._viewMatrix = BABYLON.Matrix.Identity();
  71651. this._target = BABYLON.Vector3.Zero();
  71652. this._add = BABYLON.Vector3.Zero();
  71653. this.invertYAxis = false;
  71654. this.position = BABYLON.Vector3.Zero();
  71655. this._scene = scene;
  71656. this._scene.reflectionProbes.push(this);
  71657. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  71658. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  71659. switch (faceIndex) {
  71660. case 0:
  71661. _this._add.copyFromFloats(1, 0, 0);
  71662. break;
  71663. case 1:
  71664. _this._add.copyFromFloats(-1, 0, 0);
  71665. break;
  71666. case 2:
  71667. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  71668. break;
  71669. case 3:
  71670. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  71671. break;
  71672. case 4:
  71673. _this._add.copyFromFloats(0, 0, 1);
  71674. break;
  71675. case 5:
  71676. _this._add.copyFromFloats(0, 0, -1);
  71677. break;
  71678. }
  71679. if (_this._attachedMesh) {
  71680. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  71681. }
  71682. _this.position.addToRef(_this._add, _this._target);
  71683. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71684. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71685. });
  71686. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71687. scene.updateTransformMatrix(true);
  71688. });
  71689. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71690. }
  71691. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71692. get: function () {
  71693. return this._renderTargetTexture.samples;
  71694. },
  71695. set: function (value) {
  71696. this._renderTargetTexture.samples = value;
  71697. },
  71698. enumerable: true,
  71699. configurable: true
  71700. });
  71701. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71702. get: function () {
  71703. return this._renderTargetTexture.refreshRate;
  71704. },
  71705. set: function (value) {
  71706. this._renderTargetTexture.refreshRate = value;
  71707. },
  71708. enumerable: true,
  71709. configurable: true
  71710. });
  71711. ReflectionProbe.prototype.getScene = function () {
  71712. return this._scene;
  71713. };
  71714. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71715. get: function () {
  71716. return this._renderTargetTexture;
  71717. },
  71718. enumerable: true,
  71719. configurable: true
  71720. });
  71721. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71722. get: function () {
  71723. return this._renderTargetTexture.renderList;
  71724. },
  71725. enumerable: true,
  71726. configurable: true
  71727. });
  71728. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71729. this._attachedMesh = mesh;
  71730. };
  71731. /**
  71732. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71733. *
  71734. * @param renderingGroupId The rendering group id corresponding to its index
  71735. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71736. */
  71737. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71738. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71739. };
  71740. ReflectionProbe.prototype.dispose = function () {
  71741. var index = this._scene.reflectionProbes.indexOf(this);
  71742. if (index !== -1) {
  71743. // Remove from the scene if found
  71744. this._scene.reflectionProbes.splice(index, 1);
  71745. }
  71746. if (this._renderTargetTexture) {
  71747. this._renderTargetTexture.dispose();
  71748. this._renderTargetTexture = null;
  71749. }
  71750. };
  71751. return ReflectionProbe;
  71752. }());
  71753. BABYLON.ReflectionProbe = ReflectionProbe;
  71754. })(BABYLON || (BABYLON = {}));
  71755. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71756. var BABYLON;
  71757. (function (BABYLON) {
  71758. var Layer = (function () {
  71759. function Layer(name, imgUrl, scene, isBackground, color) {
  71760. this.name = name;
  71761. this.scale = new BABYLON.Vector2(1, 1);
  71762. this.offset = new BABYLON.Vector2(0, 0);
  71763. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  71764. this.layerMask = 0x0FFFFFFF;
  71765. this._vertexBuffers = {};
  71766. // Events
  71767. /**
  71768. * An event triggered when the layer is disposed.
  71769. * @type {BABYLON.Observable}
  71770. */
  71771. this.onDisposeObservable = new BABYLON.Observable();
  71772. /**
  71773. * An event triggered before rendering the scene
  71774. * @type {BABYLON.Observable}
  71775. */
  71776. this.onBeforeRenderObservable = new BABYLON.Observable();
  71777. /**
  71778. * An event triggered after rendering the scene
  71779. * @type {BABYLON.Observable}
  71780. */
  71781. this.onAfterRenderObservable = new BABYLON.Observable();
  71782. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71783. this.isBackground = isBackground === undefined ? true : isBackground;
  71784. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71785. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71786. this._scene.layers.push(this);
  71787. var engine = this._scene.getEngine();
  71788. // VBO
  71789. var vertices = [];
  71790. vertices.push(1, 1);
  71791. vertices.push(-1, 1);
  71792. vertices.push(-1, -1);
  71793. vertices.push(1, -1);
  71794. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71796. this._createIndexBuffer();
  71797. // Effects
  71798. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71799. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71800. }
  71801. Object.defineProperty(Layer.prototype, "onDispose", {
  71802. set: function (callback) {
  71803. if (this._onDisposeObserver) {
  71804. this.onDisposeObservable.remove(this._onDisposeObserver);
  71805. }
  71806. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71807. },
  71808. enumerable: true,
  71809. configurable: true
  71810. });
  71811. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71812. set: function (callback) {
  71813. if (this._onBeforeRenderObserver) {
  71814. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71815. }
  71816. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71817. },
  71818. enumerable: true,
  71819. configurable: true
  71820. });
  71821. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71822. set: function (callback) {
  71823. if (this._onAfterRenderObserver) {
  71824. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71825. }
  71826. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71827. },
  71828. enumerable: true,
  71829. configurable: true
  71830. });
  71831. Layer.prototype._createIndexBuffer = function () {
  71832. var engine = this._scene.getEngine();
  71833. // Indices
  71834. var indices = [];
  71835. indices.push(0);
  71836. indices.push(1);
  71837. indices.push(2);
  71838. indices.push(0);
  71839. indices.push(2);
  71840. indices.push(3);
  71841. this._indexBuffer = engine.createIndexBuffer(indices);
  71842. };
  71843. Layer.prototype._rebuild = function () {
  71844. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71845. this._createIndexBuffer();
  71846. };
  71847. Layer.prototype.render = function () {
  71848. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71849. // Check
  71850. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71851. return;
  71852. var engine = this._scene.getEngine();
  71853. this.onBeforeRenderObservable.notifyObservers(this);
  71854. // Render
  71855. engine.enableEffect(currentEffect);
  71856. engine.setState(false);
  71857. // Texture
  71858. currentEffect.setTexture("textureSampler", this.texture);
  71859. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71860. // Color
  71861. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71862. // Scale / offset
  71863. currentEffect.setVector2("offset", this.offset);
  71864. currentEffect.setVector2("scale", this.scale);
  71865. // VBOs
  71866. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71867. // Draw order
  71868. if (!this.alphaTest) {
  71869. engine.setAlphaMode(this.alphaBlendingMode);
  71870. engine.draw(true, 0, 6);
  71871. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71872. }
  71873. else {
  71874. engine.draw(true, 0, 6);
  71875. }
  71876. this.onAfterRenderObservable.notifyObservers(this);
  71877. };
  71878. Layer.prototype.dispose = function () {
  71879. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71880. if (vertexBuffer) {
  71881. vertexBuffer.dispose();
  71882. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71883. }
  71884. if (this._indexBuffer) {
  71885. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71886. this._indexBuffer = null;
  71887. }
  71888. if (this.texture) {
  71889. this.texture.dispose();
  71890. this.texture = null;
  71891. }
  71892. // Remove from scene
  71893. var index = this._scene.layers.indexOf(this);
  71894. this._scene.layers.splice(index, 1);
  71895. // Callback
  71896. this.onDisposeObservable.notifyObservers(this);
  71897. this.onDisposeObservable.clear();
  71898. this.onAfterRenderObservable.clear();
  71899. this.onBeforeRenderObservable.clear();
  71900. };
  71901. return Layer;
  71902. }());
  71903. BABYLON.Layer = Layer;
  71904. })(BABYLON || (BABYLON = {}));
  71905. //# sourceMappingURL=babylon.layer.js.map
  71906. var BABYLON;
  71907. (function (BABYLON) {
  71908. var TextureTools = (function () {
  71909. function TextureTools() {
  71910. }
  71911. /**
  71912. * Uses the GPU to create a copy texture rescaled at a given size
  71913. * @param texture Texture to copy from
  71914. * @param width Desired width
  71915. * @param height Desired height
  71916. * @return Generated texture
  71917. */
  71918. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71919. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71920. var scene = texture.getScene();
  71921. var engine = scene.getEngine();
  71922. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71923. rtt.wrapU = texture.wrapU;
  71924. rtt.wrapV = texture.wrapV;
  71925. rtt.uOffset = texture.uOffset;
  71926. rtt.vOffset = texture.vOffset;
  71927. rtt.uScale = texture.uScale;
  71928. rtt.vScale = texture.vScale;
  71929. rtt.uAng = texture.uAng;
  71930. rtt.vAng = texture.vAng;
  71931. rtt.wAng = texture.wAng;
  71932. rtt.coordinatesIndex = texture.coordinatesIndex;
  71933. rtt.level = texture.level;
  71934. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71935. rtt._texture.isReady = false;
  71936. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71937. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71938. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71939. passPostProcess.getEffect().executeWhenCompiled(function () {
  71940. passPostProcess.onApply = function (effect) {
  71941. effect.setTexture("textureSampler", texture);
  71942. };
  71943. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71944. engine.unBindFramebuffer(rtt.getInternalTexture());
  71945. rtt.disposeFramebufferObjects();
  71946. passPostProcess.dispose();
  71947. rtt._texture.isReady = true;
  71948. });
  71949. return rtt;
  71950. };
  71951. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71952. if (!scene._environmentBRDFTexture) {
  71953. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71954. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71955. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71956. scene._environmentBRDFTexture = texture;
  71957. }
  71958. return scene._environmentBRDFTexture;
  71959. };
  71960. 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=";
  71961. return TextureTools;
  71962. }());
  71963. BABYLON.TextureTools = TextureTools;
  71964. })(BABYLON || (BABYLON = {}));
  71965. //# sourceMappingURL=babylon.textureTools.js.map
  71966. var BABYLON;
  71967. (function (BABYLON) {
  71968. var FramingBehavior = (function () {
  71969. function FramingBehavior() {
  71970. this._mode = FramingBehavior.FitFrustumSidesMode;
  71971. this._radiusScale = 1.0;
  71972. this._positionScale = 0.5;
  71973. this._defaultElevation = 0.3;
  71974. this._elevationReturnTime = 1500;
  71975. this._elevationReturnWaitTime = 1000;
  71976. this._zoomStopsAnimation = false;
  71977. this._framingTime = 1500;
  71978. this._isPointerDown = false;
  71979. this._lastFrameTime = null;
  71980. this._lastInteractionTime = -Infinity;
  71981. // Framing control
  71982. this._animatables = new Array();
  71983. this._betaIsAnimating = false;
  71984. this._lastFrameRadius = 0;
  71985. }
  71986. Object.defineProperty(FramingBehavior.prototype, "name", {
  71987. get: function () {
  71988. return "Framing";
  71989. },
  71990. enumerable: true,
  71991. configurable: true
  71992. });
  71993. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71994. /**
  71995. * Gets current mode used by the behavior.
  71996. */
  71997. get: function () {
  71998. return this._mode;
  71999. },
  72000. /**
  72001. * Sets the current mode used by the behavior
  72002. */
  72003. set: function (mode) {
  72004. this._mode = mode;
  72005. },
  72006. enumerable: true,
  72007. configurable: true
  72008. });
  72009. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  72010. /**
  72011. * Gets the scale applied to the radius
  72012. */
  72013. get: function () {
  72014. return this._radiusScale;
  72015. },
  72016. /**
  72017. * Sets the scale applied to the radius (1 by default)
  72018. */
  72019. set: function (radius) {
  72020. this._radiusScale = radius;
  72021. },
  72022. enumerable: true,
  72023. configurable: true
  72024. });
  72025. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  72026. /**
  72027. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72028. */
  72029. get: function () {
  72030. return this._positionScale;
  72031. },
  72032. /**
  72033. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  72034. */
  72035. set: function (scale) {
  72036. this._positionScale = scale;
  72037. },
  72038. enumerable: true,
  72039. configurable: true
  72040. });
  72041. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  72042. /**
  72043. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72044. * behaviour is triggered, in radians.
  72045. */
  72046. get: function () {
  72047. return this._defaultElevation;
  72048. },
  72049. /**
  72050. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72051. * behaviour is triggered, in radians.
  72052. */
  72053. set: function (elevation) {
  72054. this._defaultElevation = elevation;
  72055. },
  72056. enumerable: true,
  72057. configurable: true
  72058. });
  72059. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  72060. /**
  72061. * Gets the time (in milliseconds) taken to return to the default beta position.
  72062. * Negative value indicates camera should not return to default.
  72063. */
  72064. get: function () {
  72065. return this._elevationReturnTime;
  72066. },
  72067. /**
  72068. * Sets the time (in milliseconds) taken to return to the default beta position.
  72069. * Negative value indicates camera should not return to default.
  72070. */
  72071. set: function (speed) {
  72072. this._elevationReturnTime = speed;
  72073. },
  72074. enumerable: true,
  72075. configurable: true
  72076. });
  72077. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  72078. /**
  72079. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72080. */
  72081. get: function () {
  72082. return this._elevationReturnWaitTime;
  72083. },
  72084. /**
  72085. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72086. */
  72087. set: function (time) {
  72088. this._elevationReturnWaitTime = time;
  72089. },
  72090. enumerable: true,
  72091. configurable: true
  72092. });
  72093. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  72094. /**
  72095. * Gets the flag that indicates if user zooming should stop animation.
  72096. */
  72097. get: function () {
  72098. return this._zoomStopsAnimation;
  72099. },
  72100. /**
  72101. * Sets the flag that indicates if user zooming should stop animation.
  72102. */
  72103. set: function (flag) {
  72104. this._zoomStopsAnimation = flag;
  72105. },
  72106. enumerable: true,
  72107. configurable: true
  72108. });
  72109. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  72110. /**
  72111. * Gets the transition time when framing the mesh, in milliseconds
  72112. */
  72113. get: function () {
  72114. return this._framingTime;
  72115. },
  72116. /**
  72117. * Sets the transition time when framing the mesh, in milliseconds
  72118. */
  72119. set: function (time) {
  72120. this._framingTime = time;
  72121. },
  72122. enumerable: true,
  72123. configurable: true
  72124. });
  72125. FramingBehavior.prototype.attach = function (camera) {
  72126. var _this = this;
  72127. this._attachedCamera = camera;
  72128. var scene = this._attachedCamera.getScene();
  72129. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  72130. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72131. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72132. _this._isPointerDown = true;
  72133. return;
  72134. }
  72135. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72136. _this._isPointerDown = false;
  72137. }
  72138. });
  72139. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72140. if (mesh) {
  72141. _this.zoomOnMesh(mesh);
  72142. }
  72143. });
  72144. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72145. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72146. _this._applyUserInteraction();
  72147. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  72148. // back to the default position after a given timeout
  72149. _this._maintainCameraAboveGround();
  72150. });
  72151. };
  72152. FramingBehavior.prototype.detach = function () {
  72153. var scene = this._attachedCamera.getScene();
  72154. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72155. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72156. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72157. this._attachedCamera = null;
  72158. };
  72159. /**
  72160. * Targets the given mesh and updates zoom level accordingly.
  72161. * @param mesh The mesh to target.
  72162. * @param radius Optional. If a cached radius position already exists, overrides default.
  72163. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72164. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72165. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72166. */
  72167. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  72168. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72169. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72170. mesh.computeWorldMatrix(true);
  72171. var boundingBox = mesh.getBoundingInfo().boundingBox;
  72172. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  72173. };
  72174. /**
  72175. * Targets the given mesh and updates zoom level accordingly.
  72176. * @param mesh The mesh to target.
  72177. * @param radius Optional. If a cached radius position already exists, overrides default.
  72178. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72179. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72180. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72181. */
  72182. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  72183. var _this = this;
  72184. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72185. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72186. var zoomTarget;
  72187. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  72188. var bottom = minimumWorld.y;
  72189. var top = maximumWorld.y;
  72190. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  72191. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  72192. if (focusOnOriginXZ) {
  72193. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  72194. }
  72195. else {
  72196. var centerWorld = minimumWorld.add(radiusWorld);
  72197. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  72198. }
  72199. if (!this._vectorTransition) {
  72200. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  72201. }
  72202. this._betaIsAnimating = true;
  72203. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  72204. // sets the radius and lower radius bounds
  72205. // Small delta ensures camera is not always at lower zoom limit.
  72206. var delta = 0.1;
  72207. var radius = 0;
  72208. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  72209. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72210. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  72211. radius = position;
  72212. }
  72213. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72214. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72215. if (this._attachedCamera.lowerRadiusLimit === null) {
  72216. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  72217. }
  72218. }
  72219. // Set sensibilities
  72220. var extend = maximumWorld.subtract(minimumWorld).length();
  72221. this._attachedCamera.panningSensibility = 5000 / extend;
  72222. this._attachedCamera.wheelPrecision = 100 / radius;
  72223. // transition to new radius
  72224. if (!this._radiusTransition) {
  72225. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72226. }
  72227. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  72228. if (onAnimationEnd) {
  72229. onAnimationEnd();
  72230. }
  72231. _this._attachedCamera.storeState();
  72232. }));
  72233. };
  72234. /**
  72235. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  72236. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  72237. * frustum width.
  72238. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  72239. * to fully enclose the mesh in the viewing frustum.
  72240. */
  72241. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  72242. var size = maximumWorld.subtract(minimumWorld);
  72243. var boxVectorGlobalDiagonal = size.length();
  72244. var frustumSlope = this._getFrustumSlope();
  72245. // Formula for setting distance
  72246. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  72247. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  72248. // Horizon distance
  72249. var radius = radiusWithoutFraming * this._radiusScale;
  72250. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  72251. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  72252. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  72253. var camera = this._attachedCamera;
  72254. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72255. // Don't exceed the requested limit
  72256. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  72257. }
  72258. // Don't exceed the upper radius limit
  72259. if (camera.upperRadiusLimit) {
  72260. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  72261. }
  72262. return distance;
  72263. };
  72264. /**
  72265. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  72266. * is automatically returned to its default position (expected to be above ground plane).
  72267. */
  72268. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  72269. var _this = this;
  72270. if (this._elevationReturnTime < 0) {
  72271. return;
  72272. }
  72273. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  72274. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  72275. var limitBeta = Math.PI * 0.5;
  72276. // Bring the camera back up if below the ground plane
  72277. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  72278. this._betaIsAnimating = true;
  72279. //Transition to new position
  72280. this.stopAllAnimations();
  72281. if (!this._betaTransition) {
  72282. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72283. }
  72284. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  72285. _this._clearAnimationLocks();
  72286. _this.stopAllAnimations();
  72287. }));
  72288. }
  72289. };
  72290. /**
  72291. * Returns the frustum slope based on the canvas ratio and camera FOV
  72292. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  72293. */
  72294. FramingBehavior.prototype._getFrustumSlope = function () {
  72295. // Calculate the viewport ratio
  72296. // Aspect Ratio is Height/Width.
  72297. var camera = this._attachedCamera;
  72298. var engine = camera.getScene().getEngine();
  72299. var aspectRatio = engine.getAspectRatio(camera);
  72300. // Camera FOV is the vertical field of view (top-bottom) in radians.
  72301. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  72302. var frustumSlopeY = Math.tan(camera.fov / 2);
  72303. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  72304. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  72305. // along the forward vector.
  72306. var frustumSlopeX = frustumSlopeY * aspectRatio;
  72307. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  72308. };
  72309. /**
  72310. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  72311. */
  72312. FramingBehavior.prototype._clearAnimationLocks = function () {
  72313. this._betaIsAnimating = false;
  72314. };
  72315. /**
  72316. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72317. */
  72318. FramingBehavior.prototype._applyUserInteraction = function () {
  72319. if (this.isUserIsMoving) {
  72320. this._lastInteractionTime = BABYLON.Tools.Now;
  72321. this.stopAllAnimations();
  72322. this._clearAnimationLocks();
  72323. }
  72324. };
  72325. /**
  72326. * Stops and removes all animations that have been applied to the camera
  72327. */
  72328. FramingBehavior.prototype.stopAllAnimations = function () {
  72329. this._attachedCamera.animations = [];
  72330. while (this._animatables.length) {
  72331. if (this._animatables[0]) {
  72332. this._animatables[0].onAnimationEnd = null;
  72333. this._animatables[0].stop();
  72334. }
  72335. this._animatables.shift();
  72336. }
  72337. };
  72338. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  72339. /**
  72340. * Gets a value indicating if the user is moving the camera
  72341. */
  72342. get: function () {
  72343. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72344. this._attachedCamera.inertialBetaOffset !== 0 ||
  72345. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72346. this._attachedCamera.inertialPanningX !== 0 ||
  72347. this._attachedCamera.inertialPanningY !== 0 ||
  72348. this._isPointerDown;
  72349. },
  72350. enumerable: true,
  72351. configurable: true
  72352. });
  72353. /**
  72354. * The easing function used by animations
  72355. */
  72356. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  72357. /**
  72358. * The easing mode used by animations
  72359. */
  72360. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  72361. // Statics
  72362. /**
  72363. * The camera can move all the way towards the mesh.
  72364. */
  72365. FramingBehavior.IgnoreBoundsSizeMode = 0;
  72366. /**
  72367. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  72368. */
  72369. FramingBehavior.FitFrustumSidesMode = 1;
  72370. return FramingBehavior;
  72371. }());
  72372. BABYLON.FramingBehavior = FramingBehavior;
  72373. })(BABYLON || (BABYLON = {}));
  72374. //# sourceMappingURL=babylon.framingBehavior.js.map
  72375. var BABYLON;
  72376. (function (BABYLON) {
  72377. /**
  72378. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72379. */
  72380. var BouncingBehavior = (function () {
  72381. function BouncingBehavior() {
  72382. /**
  72383. * The duration of the animation, in milliseconds
  72384. */
  72385. this.transitionDuration = 450;
  72386. /**
  72387. * Length of the distance animated by the transition when lower radius is reached
  72388. */
  72389. this.lowerRadiusTransitionRange = 2;
  72390. /**
  72391. * Length of the distance animated by the transition when upper radius is reached
  72392. */
  72393. this.upperRadiusTransitionRange = -2;
  72394. this._autoTransitionRange = false;
  72395. // Animations
  72396. this._radiusIsAnimating = false;
  72397. this._radiusBounceTransition = null;
  72398. this._animatables = new Array();
  72399. }
  72400. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72401. get: function () {
  72402. return "Bouncing";
  72403. },
  72404. enumerable: true,
  72405. configurable: true
  72406. });
  72407. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72408. /**
  72409. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72410. */
  72411. get: function () {
  72412. return this._autoTransitionRange;
  72413. },
  72414. /**
  72415. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72416. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72417. */
  72418. set: function (value) {
  72419. var _this = this;
  72420. if (this._autoTransitionRange === value) {
  72421. return;
  72422. }
  72423. this._autoTransitionRange = value;
  72424. var camera = this._attachedCamera;
  72425. if (value) {
  72426. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72427. if (!mesh) {
  72428. return;
  72429. }
  72430. mesh.computeWorldMatrix(true);
  72431. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72432. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72433. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72434. });
  72435. }
  72436. else if (this._onMeshTargetChangedObserver) {
  72437. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72438. }
  72439. },
  72440. enumerable: true,
  72441. configurable: true
  72442. });
  72443. BouncingBehavior.prototype.attach = function (camera) {
  72444. var _this = this;
  72445. this._attachedCamera = camera;
  72446. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72447. // Add the bounce animation to the lower radius limit
  72448. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72449. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72450. }
  72451. // Add the bounce animation to the upper radius limit
  72452. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72453. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72454. }
  72455. });
  72456. };
  72457. BouncingBehavior.prototype.detach = function () {
  72458. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72459. if (this._onMeshTargetChangedObserver) {
  72460. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72461. }
  72462. this._attachedCamera = null;
  72463. };
  72464. /**
  72465. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72466. * @param radiusLimit The limit to check against.
  72467. * @return Bool to indicate if at limit.
  72468. */
  72469. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72470. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72471. return true;
  72472. }
  72473. return false;
  72474. };
  72475. /**
  72476. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72477. * @param radiusDelta The delta by which to animate to. Can be negative.
  72478. */
  72479. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72480. var _this = this;
  72481. if (!this._radiusBounceTransition) {
  72482. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72483. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72484. }
  72485. // Prevent zoom until bounce has completed
  72486. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72487. this._attachedCamera.wheelPrecision = Infinity;
  72488. this._attachedCamera.inertialRadiusOffset = 0;
  72489. // Animate to the radius limit
  72490. this.stopAllAnimations();
  72491. this._radiusIsAnimating = true;
  72492. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  72493. };
  72494. /**
  72495. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72496. */
  72497. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72498. this._radiusIsAnimating = false;
  72499. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72500. };
  72501. /**
  72502. * Stops and removes all animations that have been applied to the camera
  72503. */
  72504. BouncingBehavior.prototype.stopAllAnimations = function () {
  72505. this._attachedCamera.animations = [];
  72506. while (this._animatables.length) {
  72507. this._animatables[0].onAnimationEnd = null;
  72508. this._animatables[0].stop();
  72509. this._animatables.shift();
  72510. }
  72511. };
  72512. /**
  72513. * The easing function used by animations
  72514. */
  72515. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72516. /**
  72517. * The easing mode used by animations
  72518. */
  72519. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72520. return BouncingBehavior;
  72521. }());
  72522. BABYLON.BouncingBehavior = BouncingBehavior;
  72523. })(BABYLON || (BABYLON = {}));
  72524. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72525. var BABYLON;
  72526. (function (BABYLON) {
  72527. var AutoRotationBehavior = (function () {
  72528. function AutoRotationBehavior() {
  72529. this._zoomStopsAnimation = false;
  72530. this._idleRotationSpeed = 0.05;
  72531. this._idleRotationWaitTime = 2000;
  72532. this._idleRotationSpinupTime = 2000;
  72533. this._isPointerDown = false;
  72534. this._lastFrameTime = null;
  72535. this._lastInteractionTime = -Infinity;
  72536. this._cameraRotationSpeed = 0;
  72537. this._lastFrameRadius = 0;
  72538. }
  72539. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72540. get: function () {
  72541. return "AutoRotation";
  72542. },
  72543. enumerable: true,
  72544. configurable: true
  72545. });
  72546. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  72547. /**
  72548. * Gets the flag that indicates if user zooming should stop animation.
  72549. */
  72550. get: function () {
  72551. return this._zoomStopsAnimation;
  72552. },
  72553. /**
  72554. * Sets the flag that indicates if user zooming should stop animation.
  72555. */
  72556. set: function (flag) {
  72557. this._zoomStopsAnimation = flag;
  72558. },
  72559. enumerable: true,
  72560. configurable: true
  72561. });
  72562. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  72563. /**
  72564. * Gets the default speed at which the camera rotates around the model.
  72565. */
  72566. get: function () {
  72567. return this._idleRotationSpeed;
  72568. },
  72569. /**
  72570. * Sets the default speed at which the camera rotates around the model.
  72571. */
  72572. set: function (speed) {
  72573. this._idleRotationSpeed = speed;
  72574. },
  72575. enumerable: true,
  72576. configurable: true
  72577. });
  72578. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  72579. /**
  72580. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  72581. */
  72582. get: function () {
  72583. return this._idleRotationWaitTime;
  72584. },
  72585. /**
  72586. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  72587. */
  72588. set: function (time) {
  72589. this._idleRotationWaitTime = time;
  72590. },
  72591. enumerable: true,
  72592. configurable: true
  72593. });
  72594. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  72595. /**
  72596. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72597. */
  72598. get: function () {
  72599. return this._idleRotationSpinupTime;
  72600. },
  72601. /**
  72602. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72603. */
  72604. set: function (time) {
  72605. this._idleRotationSpinupTime = time;
  72606. },
  72607. enumerable: true,
  72608. configurable: true
  72609. });
  72610. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  72611. /**
  72612. * Gets a value indicating if the camera is currently rotating because of this behavior
  72613. */
  72614. get: function () {
  72615. return Math.abs(this._cameraRotationSpeed) > 0;
  72616. },
  72617. enumerable: true,
  72618. configurable: true
  72619. });
  72620. AutoRotationBehavior.prototype.attach = function (camera) {
  72621. var _this = this;
  72622. this._attachedCamera = camera;
  72623. var scene = this._attachedCamera.getScene();
  72624. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72625. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72626. _this._isPointerDown = true;
  72627. return;
  72628. }
  72629. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72630. _this._isPointerDown = false;
  72631. }
  72632. });
  72633. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72634. var now = BABYLON.Tools.Now;
  72635. var dt = 0;
  72636. if (_this._lastFrameTime != null) {
  72637. dt = now - _this._lastFrameTime;
  72638. }
  72639. _this._lastFrameTime = now;
  72640. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72641. _this._applyUserInteraction();
  72642. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  72643. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  72644. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  72645. // Step camera rotation by rotation speed
  72646. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  72647. });
  72648. };
  72649. AutoRotationBehavior.prototype.detach = function () {
  72650. var scene = this._attachedCamera.getScene();
  72651. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72652. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72653. this._attachedCamera = null;
  72654. };
  72655. /**
  72656. * Returns true if user is scrolling.
  72657. * @return true if user is scrolling.
  72658. */
  72659. AutoRotationBehavior.prototype._userIsZooming = function () {
  72660. return this._attachedCamera.inertialRadiusOffset !== 0;
  72661. };
  72662. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  72663. var zoomHasHitLimit = false;
  72664. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  72665. zoomHasHitLimit = true;
  72666. }
  72667. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  72668. this._lastFrameRadius = this._attachedCamera.radius;
  72669. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  72670. };
  72671. /**
  72672. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72673. */
  72674. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  72675. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  72676. this._lastInteractionTime = BABYLON.Tools.Now;
  72677. }
  72678. };
  72679. // Tools
  72680. AutoRotationBehavior.prototype._userIsMoving = function () {
  72681. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72682. this._attachedCamera.inertialBetaOffset !== 0 ||
  72683. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72684. this._attachedCamera.inertialPanningX !== 0 ||
  72685. this._attachedCamera.inertialPanningY !== 0 ||
  72686. this._isPointerDown;
  72687. };
  72688. return AutoRotationBehavior;
  72689. }());
  72690. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72691. })(BABYLON || (BABYLON = {}));
  72692. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72693. 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<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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\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\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<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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\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}"};
  72694. 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}\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\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\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;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\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(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#else\nshadow=1.;\n#endif\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","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};"};
  72695. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72696. var BABYLON;
  72697. (function (BABYLON) {
  72698. var GridMaterialDefines = (function (_super) {
  72699. __extends(GridMaterialDefines, _super);
  72700. function GridMaterialDefines() {
  72701. var _this = _super.call(this) || this;
  72702. _this.TRANSPARENT = false;
  72703. _this.FOG = false;
  72704. _this.PREMULTIPLYALPHA = false;
  72705. _this.rebuild();
  72706. return _this;
  72707. }
  72708. return GridMaterialDefines;
  72709. }(BABYLON.MaterialDefines));
  72710. /**
  72711. * The grid materials allows you to wrap any shape with a grid.
  72712. * Colors are customizable.
  72713. */
  72714. var GridMaterial = (function (_super) {
  72715. __extends(GridMaterial, _super);
  72716. /**
  72717. * constructor
  72718. * @param name The name given to the material in order to identify it afterwards.
  72719. * @param scene The scene the material is used in.
  72720. */
  72721. function GridMaterial(name, scene) {
  72722. var _this = _super.call(this, name, scene) || this;
  72723. /**
  72724. * Main color of the grid (e.g. between lines)
  72725. */
  72726. _this.mainColor = BABYLON.Color3.Black();
  72727. /**
  72728. * Color of the grid lines.
  72729. */
  72730. _this.lineColor = BABYLON.Color3.Teal();
  72731. /**
  72732. * The scale of the grid compared to unit.
  72733. */
  72734. _this.gridRatio = 1.0;
  72735. /**
  72736. * Allows setting an offset for the grid lines.
  72737. */
  72738. _this.gridOffset = BABYLON.Vector3.Zero();
  72739. /**
  72740. * The frequency of thicker lines.
  72741. */
  72742. _this.majorUnitFrequency = 10;
  72743. /**
  72744. * The visibility of minor units in the grid.
  72745. */
  72746. _this.minorUnitVisibility = 0.33;
  72747. /**
  72748. * The grid opacity outside of the lines.
  72749. */
  72750. _this.opacity = 1.0;
  72751. /**
  72752. * Determine RBG output is premultiplied by alpha value.
  72753. */
  72754. _this.preMultiplyAlpha = false;
  72755. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  72756. return _this;
  72757. }
  72758. /**
  72759. * Returns wehter or not the grid requires alpha blending.
  72760. */
  72761. GridMaterial.prototype.needAlphaBlending = function () {
  72762. return this.opacity < 1.0;
  72763. };
  72764. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72765. if (this.isFrozen) {
  72766. if (this._wasPreviouslyReady && subMesh.effect) {
  72767. return true;
  72768. }
  72769. }
  72770. if (!subMesh._materialDefines) {
  72771. subMesh._materialDefines = new GridMaterialDefines();
  72772. }
  72773. var defines = subMesh._materialDefines;
  72774. var scene = this.getScene();
  72775. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  72776. if (this._renderId === scene.getRenderId()) {
  72777. return true;
  72778. }
  72779. }
  72780. var engine = scene.getEngine();
  72781. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  72782. defines.TRANSPARENT = !defines.TRANSPARENT;
  72783. defines.markAsUnprocessed();
  72784. }
  72785. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  72786. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  72787. defines.markAsUnprocessed();
  72788. }
  72789. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  72790. // Get correct effect
  72791. if (defines.isDirty) {
  72792. defines.markAsProcessed();
  72793. scene.resetCachedMaterial();
  72794. // Attributes
  72795. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72796. // Defines
  72797. var join = defines.toString();
  72798. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72799. }
  72800. if (!subMesh.effect.isReady()) {
  72801. return false;
  72802. }
  72803. this._renderId = scene.getRenderId();
  72804. this._wasPreviouslyReady = true;
  72805. return true;
  72806. };
  72807. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72808. var scene = this.getScene();
  72809. var defines = subMesh._materialDefines;
  72810. if (!defines) {
  72811. return;
  72812. }
  72813. var effect = subMesh.effect;
  72814. this._activeEffect = effect;
  72815. // Matrices
  72816. this.bindOnlyWorldMatrix(world);
  72817. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72818. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72819. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72820. // Uniforms
  72821. if (this._mustRebind(scene, effect)) {
  72822. this._activeEffect.setColor3("mainColor", this.mainColor);
  72823. this._activeEffect.setColor3("lineColor", this.lineColor);
  72824. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  72825. this._gridControl.x = this.gridRatio;
  72826. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72827. this._gridControl.z = this.minorUnitVisibility;
  72828. this._gridControl.w = this.opacity;
  72829. this._activeEffect.setVector4("gridControl", this._gridControl);
  72830. }
  72831. // Fog
  72832. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72833. this._afterBind(mesh, this._activeEffect);
  72834. };
  72835. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72836. _super.prototype.dispose.call(this, forceDisposeEffect);
  72837. };
  72838. GridMaterial.prototype.clone = function (name) {
  72839. var _this = this;
  72840. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72841. };
  72842. GridMaterial.prototype.serialize = function () {
  72843. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72844. serializationObject.customType = "BABYLON.GridMaterial";
  72845. return serializationObject;
  72846. };
  72847. GridMaterial.prototype.getClassName = function () {
  72848. return "GridMaterial";
  72849. };
  72850. GridMaterial.Parse = function (source, scene, rootUrl) {
  72851. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72852. };
  72853. __decorate([
  72854. BABYLON.serializeAsColor3()
  72855. ], GridMaterial.prototype, "mainColor", void 0);
  72856. __decorate([
  72857. BABYLON.serializeAsColor3()
  72858. ], GridMaterial.prototype, "lineColor", void 0);
  72859. __decorate([
  72860. BABYLON.serialize()
  72861. ], GridMaterial.prototype, "gridRatio", void 0);
  72862. __decorate([
  72863. BABYLON.serializeAsColor3()
  72864. ], GridMaterial.prototype, "gridOffset", void 0);
  72865. __decorate([
  72866. BABYLON.serialize()
  72867. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72868. __decorate([
  72869. BABYLON.serialize()
  72870. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72871. __decorate([
  72872. BABYLON.serialize()
  72873. ], GridMaterial.prototype, "opacity", void 0);
  72874. __decorate([
  72875. BABYLON.serialize()
  72876. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72877. return GridMaterial;
  72878. }(BABYLON.PushMaterial));
  72879. BABYLON.GridMaterial = GridMaterial;
  72880. })(BABYLON || (BABYLON = {}));
  72881. //# sourceMappingURL=babylon.gridmaterial.js.map
  72882. 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}";
  72883. 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}";
  72884. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72885. var BABYLON;
  72886. (function (BABYLON) {
  72887. var GLTFLoaderCoordinateSystemMode;
  72888. (function (GLTFLoaderCoordinateSystemMode) {
  72889. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72890. // 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.
  72891. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72892. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72893. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72894. // Sets the useRightHandedSystem flag on the scene.
  72895. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72896. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72897. var GLTFFileLoader = (function () {
  72898. function GLTFFileLoader() {
  72899. // V2 options
  72900. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72901. this.name = "gltf";
  72902. this.extensions = {
  72903. ".gltf": { isBinary: false },
  72904. ".glb": { isBinary: true }
  72905. };
  72906. }
  72907. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72908. var loaderData = GLTFFileLoader._parse(data, onError);
  72909. if (!loaderData) {
  72910. return;
  72911. }
  72912. if (this.onParsed) {
  72913. this.onParsed(loaderData);
  72914. }
  72915. var loader = this._getLoader(loaderData, onError);
  72916. if (!loader) {
  72917. return;
  72918. }
  72919. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72920. };
  72921. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72922. var loaderData = GLTFFileLoader._parse(data, onError);
  72923. if (!loaderData) {
  72924. return;
  72925. }
  72926. if (this.onParsed) {
  72927. this.onParsed(loaderData);
  72928. }
  72929. var loader = this._getLoader(loaderData, onError);
  72930. if (!loader) {
  72931. return;
  72932. }
  72933. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72934. };
  72935. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72936. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72937. };
  72938. GLTFFileLoader._parse = function (data, onError) {
  72939. try {
  72940. if (data instanceof ArrayBuffer) {
  72941. return GLTFFileLoader._parseBinary(data, onError);
  72942. }
  72943. return {
  72944. json: JSON.parse(data),
  72945. bin: null
  72946. };
  72947. }
  72948. catch (e) {
  72949. onError(e.message);
  72950. return null;
  72951. }
  72952. };
  72953. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72954. var loaderVersion = { major: 2, minor: 0 };
  72955. var asset = loaderData.json.asset || {};
  72956. var version = GLTFFileLoader._parseVersion(asset.version);
  72957. if (!version) {
  72958. onError("Invalid version: " + asset.version);
  72959. return null;
  72960. }
  72961. if (asset.minVersion !== undefined) {
  72962. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72963. if (!minVersion) {
  72964. onError("Invalid minimum version: " + asset.minVersion);
  72965. return null;
  72966. }
  72967. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72968. onError("Incompatible minimum version: " + asset.minVersion);
  72969. return null;
  72970. }
  72971. }
  72972. var createLoaders = {
  72973. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72974. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72975. };
  72976. var createLoader = createLoaders[version.major];
  72977. if (!createLoader) {
  72978. onError("Unsupported version: " + asset.version);
  72979. return null;
  72980. }
  72981. return createLoader(this);
  72982. };
  72983. GLTFFileLoader._parseBinary = function (data, onError) {
  72984. var Binary = {
  72985. Magic: 0x46546C67
  72986. };
  72987. var binaryReader = new BinaryReader(data);
  72988. var magic = binaryReader.readUint32();
  72989. if (magic !== Binary.Magic) {
  72990. onError("Unexpected magic: " + magic);
  72991. return null;
  72992. }
  72993. var version = binaryReader.readUint32();
  72994. switch (version) {
  72995. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72996. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72997. }
  72998. onError("Unsupported version: " + version);
  72999. return null;
  73000. };
  73001. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  73002. var ContentFormat = {
  73003. JSON: 0
  73004. };
  73005. var length = binaryReader.readUint32();
  73006. if (length != binaryReader.getLength()) {
  73007. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  73008. return null;
  73009. }
  73010. var contentLength = binaryReader.readUint32();
  73011. var contentFormat = binaryReader.readUint32();
  73012. var content;
  73013. switch (contentFormat) {
  73014. case ContentFormat.JSON:
  73015. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  73016. break;
  73017. default:
  73018. onError("Unexpected content format: " + contentFormat);
  73019. return null;
  73020. }
  73021. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  73022. var body = binaryReader.readUint8Array(bytesRemaining);
  73023. return {
  73024. json: content,
  73025. bin: body
  73026. };
  73027. };
  73028. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  73029. var ChunkFormat = {
  73030. JSON: 0x4E4F534A,
  73031. BIN: 0x004E4942
  73032. };
  73033. var length = binaryReader.readUint32();
  73034. if (length !== binaryReader.getLength()) {
  73035. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  73036. return null;
  73037. }
  73038. // JSON chunk
  73039. var chunkLength = binaryReader.readUint32();
  73040. var chunkFormat = binaryReader.readUint32();
  73041. if (chunkFormat !== ChunkFormat.JSON) {
  73042. onError("First chunk format is not JSON");
  73043. return null;
  73044. }
  73045. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  73046. // Look for BIN chunk
  73047. var bin = null;
  73048. while (binaryReader.getPosition() < binaryReader.getLength()) {
  73049. chunkLength = binaryReader.readUint32();
  73050. chunkFormat = binaryReader.readUint32();
  73051. switch (chunkFormat) {
  73052. case ChunkFormat.JSON:
  73053. onError("Unexpected JSON chunk");
  73054. return null;
  73055. case ChunkFormat.BIN:
  73056. bin = binaryReader.readUint8Array(chunkLength);
  73057. break;
  73058. default:
  73059. // ignore unrecognized chunkFormat
  73060. binaryReader.skipBytes(chunkLength);
  73061. break;
  73062. }
  73063. }
  73064. return {
  73065. json: json,
  73066. bin: bin
  73067. };
  73068. };
  73069. GLTFFileLoader._parseVersion = function (version) {
  73070. if (!version) {
  73071. return null;
  73072. }
  73073. var parts = version.split(".");
  73074. if (parts.length != 2) {
  73075. return null;
  73076. }
  73077. var major = +parts[0];
  73078. if (isNaN(major)) {
  73079. return null;
  73080. }
  73081. var minor = +parts[1];
  73082. if (isNaN(minor)) {
  73083. return null;
  73084. }
  73085. return {
  73086. major: major,
  73087. minor: minor
  73088. };
  73089. };
  73090. GLTFFileLoader._compareVersion = function (a, b) {
  73091. if (a.major > b.major)
  73092. return 1;
  73093. if (a.major < b.major)
  73094. return -1;
  73095. if (a.minor > b.minor)
  73096. return 1;
  73097. if (a.minor < b.minor)
  73098. return -1;
  73099. return 0;
  73100. };
  73101. GLTFFileLoader._decodeBufferToText = function (view) {
  73102. var result = "";
  73103. var length = view.byteLength;
  73104. for (var i = 0; i < length; ++i) {
  73105. result += String.fromCharCode(view[i]);
  73106. }
  73107. return result;
  73108. };
  73109. // V1 options
  73110. GLTFFileLoader.HomogeneousCoordinates = false;
  73111. GLTFFileLoader.IncrementalLoading = true;
  73112. return GLTFFileLoader;
  73113. }());
  73114. BABYLON.GLTFFileLoader = GLTFFileLoader;
  73115. var BinaryReader = (function () {
  73116. function BinaryReader(arrayBuffer) {
  73117. this._arrayBuffer = arrayBuffer;
  73118. this._dataView = new DataView(arrayBuffer);
  73119. this._byteOffset = 0;
  73120. }
  73121. BinaryReader.prototype.getPosition = function () {
  73122. return this._byteOffset;
  73123. };
  73124. BinaryReader.prototype.getLength = function () {
  73125. return this._arrayBuffer.byteLength;
  73126. };
  73127. BinaryReader.prototype.readUint32 = function () {
  73128. var value = this._dataView.getUint32(this._byteOffset, true);
  73129. this._byteOffset += 4;
  73130. return value;
  73131. };
  73132. BinaryReader.prototype.readUint8Array = function (length) {
  73133. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  73134. this._byteOffset += length;
  73135. return value;
  73136. };
  73137. BinaryReader.prototype.skipBytes = function (length) {
  73138. this._byteOffset += length;
  73139. };
  73140. return BinaryReader;
  73141. }());
  73142. if (BABYLON.SceneLoader) {
  73143. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  73144. }
  73145. })(BABYLON || (BABYLON = {}));
  73146. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  73147. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73148. var BABYLON;
  73149. (function (BABYLON) {
  73150. var GLTF1;
  73151. (function (GLTF1) {
  73152. /**
  73153. * Enums
  73154. */
  73155. var EComponentType;
  73156. (function (EComponentType) {
  73157. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  73158. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  73159. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  73160. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  73161. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  73162. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  73163. var EShaderType;
  73164. (function (EShaderType) {
  73165. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  73166. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  73167. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  73168. var EParameterType;
  73169. (function (EParameterType) {
  73170. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  73171. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  73172. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  73173. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  73174. EParameterType[EParameterType["INT"] = 5124] = "INT";
  73175. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  73176. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  73177. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  73178. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  73179. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  73180. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  73181. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  73182. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  73183. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  73184. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  73185. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  73186. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  73187. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  73188. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  73189. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  73190. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  73191. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  73192. var ETextureWrapMode;
  73193. (function (ETextureWrapMode) {
  73194. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  73195. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  73196. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  73197. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  73198. var ETextureFilterType;
  73199. (function (ETextureFilterType) {
  73200. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  73201. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  73202. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  73203. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  73204. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  73205. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  73206. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  73207. var ETextureFormat;
  73208. (function (ETextureFormat) {
  73209. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  73210. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  73211. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  73212. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  73213. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  73214. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  73215. var ECullingType;
  73216. (function (ECullingType) {
  73217. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  73218. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  73219. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  73220. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  73221. var EBlendingFunction;
  73222. (function (EBlendingFunction) {
  73223. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  73224. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  73225. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  73226. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  73227. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  73228. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  73229. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  73230. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  73231. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  73232. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  73233. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  73234. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  73235. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  73236. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  73237. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  73238. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  73239. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73240. })(BABYLON || (BABYLON = {}));
  73241. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  73242. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73243. var BABYLON;
  73244. (function (BABYLON) {
  73245. var GLTF1;
  73246. (function (GLTF1) {
  73247. /**
  73248. * Tokenizer. Used for shaders compatibility
  73249. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  73250. */
  73251. var ETokenType;
  73252. (function (ETokenType) {
  73253. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  73254. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  73255. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  73256. })(ETokenType || (ETokenType = {}));
  73257. var Tokenizer = (function () {
  73258. function Tokenizer(toParse) {
  73259. this._pos = 0;
  73260. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  73261. this._toParse = toParse;
  73262. this._maxPos = toParse.length;
  73263. }
  73264. Tokenizer.prototype.getNextToken = function () {
  73265. if (this.isEnd())
  73266. return ETokenType.END_OF_INPUT;
  73267. this.currentString = this.read();
  73268. this.currentToken = ETokenType.UNKNOWN;
  73269. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  73270. this.currentToken = ETokenType.IDENTIFIER;
  73271. this.currentIdentifier = this.currentString;
  73272. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  73273. this.currentIdentifier += this.currentString;
  73274. this.forward();
  73275. }
  73276. }
  73277. return this.currentToken;
  73278. };
  73279. Tokenizer.prototype.peek = function () {
  73280. return this._toParse[this._pos];
  73281. };
  73282. Tokenizer.prototype.read = function () {
  73283. return this._toParse[this._pos++];
  73284. };
  73285. Tokenizer.prototype.forward = function () {
  73286. this._pos++;
  73287. };
  73288. Tokenizer.prototype.isEnd = function () {
  73289. return this._pos >= this._maxPos;
  73290. };
  73291. return Tokenizer;
  73292. }());
  73293. /**
  73294. * Values
  73295. */
  73296. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  73297. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  73298. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  73299. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  73300. /**
  73301. * Parse
  73302. */
  73303. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  73304. for (var buf in parsedBuffers) {
  73305. var parsedBuffer = parsedBuffers[buf];
  73306. gltfRuntime.buffers[buf] = parsedBuffer;
  73307. gltfRuntime.buffersCount++;
  73308. }
  73309. };
  73310. var parseShaders = function (parsedShaders, gltfRuntime) {
  73311. for (var sha in parsedShaders) {
  73312. var parsedShader = parsedShaders[sha];
  73313. gltfRuntime.shaders[sha] = parsedShader;
  73314. gltfRuntime.shaderscount++;
  73315. }
  73316. };
  73317. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  73318. for (var object in parsedObjects) {
  73319. var parsedObject = parsedObjects[object];
  73320. gltfRuntime[runtimeProperty][object] = parsedObject;
  73321. }
  73322. };
  73323. /**
  73324. * Utils
  73325. */
  73326. var normalizeUVs = function (buffer) {
  73327. if (!buffer) {
  73328. return;
  73329. }
  73330. for (var i = 0; i < buffer.length / 2; i++) {
  73331. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  73332. }
  73333. };
  73334. var replaceInString = function (str, searchValue, replaceValue) {
  73335. while (str.indexOf(searchValue) !== -1) {
  73336. str = str.replace(searchValue, replaceValue);
  73337. }
  73338. return str;
  73339. };
  73340. var getAttribute = function (attributeParameter) {
  73341. if (attributeParameter.semantic === "NORMAL") {
  73342. return "normal";
  73343. }
  73344. else if (attributeParameter.semantic === "POSITION") {
  73345. return "position";
  73346. }
  73347. else if (attributeParameter.semantic === "JOINT") {
  73348. return "matricesIndices";
  73349. }
  73350. else if (attributeParameter.semantic === "WEIGHT") {
  73351. return "matricesWeights";
  73352. }
  73353. else if (attributeParameter.semantic === "COLOR") {
  73354. return "color";
  73355. }
  73356. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  73357. var channel = Number(attributeParameter.semantic.split("_")[1]);
  73358. return "uv" + (channel === 0 ? "" : channel + 1);
  73359. }
  73360. };
  73361. /**
  73362. * Returns the animation path (glTF -> Babylon)
  73363. */
  73364. var getAnimationPath = function (path) {
  73365. var index = glTFAnimationPaths.indexOf(path);
  73366. if (index !== -1) {
  73367. return babylonAnimationPaths[index];
  73368. }
  73369. return path;
  73370. };
  73371. /**
  73372. * Loads and creates animations
  73373. */
  73374. var loadAnimations = function (gltfRuntime) {
  73375. for (var anim in gltfRuntime.animations) {
  73376. var animation = gltfRuntime.animations[anim];
  73377. var lastAnimation = null;
  73378. for (var i = 0; i < animation.channels.length; i++) {
  73379. // Get parameters and load buffers
  73380. var channel = animation.channels[i];
  73381. var sampler = animation.samplers[channel.sampler];
  73382. if (!sampler) {
  73383. continue;
  73384. }
  73385. var inputData = null;
  73386. var outputData = null;
  73387. if (animation.parameters) {
  73388. inputData = animation.parameters[sampler.input];
  73389. outputData = animation.parameters[sampler.output];
  73390. }
  73391. else {
  73392. inputData = sampler.input;
  73393. outputData = sampler.output;
  73394. }
  73395. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  73396. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  73397. var targetID = channel.target.id;
  73398. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  73399. if (targetNode === null) {
  73400. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  73401. }
  73402. if (targetNode === null) {
  73403. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  73404. continue;
  73405. }
  73406. var isBone = targetNode instanceof BABYLON.Bone;
  73407. // Get target path (position, rotation or scaling)
  73408. var targetPath = channel.target.path;
  73409. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  73410. if (targetPathIndex !== -1) {
  73411. targetPath = babylonAnimationPaths[targetPathIndex];
  73412. }
  73413. // Determine animation type
  73414. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  73415. if (!isBone) {
  73416. if (targetPath === "rotationQuaternion") {
  73417. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  73418. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  73419. }
  73420. else {
  73421. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  73422. }
  73423. }
  73424. // Create animation and key frames
  73425. var babylonAnimation = null;
  73426. var keys = [];
  73427. var arrayOffset = 0;
  73428. var modifyKey = false;
  73429. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  73430. babylonAnimation = lastAnimation;
  73431. modifyKey = true;
  73432. }
  73433. if (!modifyKey) {
  73434. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73435. }
  73436. // For each frame
  73437. for (var j = 0; j < bufferInput.length; j++) {
  73438. var value = null;
  73439. if (targetPath === "rotationQuaternion") {
  73440. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  73441. arrayOffset += 4;
  73442. }
  73443. else {
  73444. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  73445. arrayOffset += 3;
  73446. }
  73447. if (isBone) {
  73448. var bone = targetNode;
  73449. var translation = BABYLON.Vector3.Zero();
  73450. var rotationQuaternion = new BABYLON.Quaternion();
  73451. var scaling = BABYLON.Vector3.Zero();
  73452. // Warning on decompose
  73453. var mat = bone.getBaseMatrix();
  73454. if (modifyKey) {
  73455. mat = lastAnimation.getKeys()[j].value;
  73456. }
  73457. mat.decompose(scaling, rotationQuaternion, translation);
  73458. if (targetPath === "position") {
  73459. translation = value;
  73460. }
  73461. else if (targetPath === "rotationQuaternion") {
  73462. rotationQuaternion = value;
  73463. }
  73464. else {
  73465. scaling = value;
  73466. }
  73467. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  73468. }
  73469. if (!modifyKey) {
  73470. keys.push({
  73471. frame: bufferInput[j],
  73472. value: value
  73473. });
  73474. }
  73475. else {
  73476. lastAnimation.getKeys()[j].value = value;
  73477. }
  73478. }
  73479. // Finish
  73480. if (!modifyKey) {
  73481. babylonAnimation.setKeys(keys);
  73482. targetNode.animations.push(babylonAnimation);
  73483. }
  73484. lastAnimation = babylonAnimation;
  73485. gltfRuntime.scene.stopAnimation(targetNode);
  73486. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  73487. }
  73488. }
  73489. };
  73490. /**
  73491. * Returns the bones transformation matrix
  73492. */
  73493. var configureBoneTransformation = function (node) {
  73494. var mat = null;
  73495. if (node.translation || node.rotation || node.scale) {
  73496. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  73497. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  73498. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  73499. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  73500. }
  73501. else {
  73502. mat = BABYLON.Matrix.FromArray(node.matrix);
  73503. }
  73504. return mat;
  73505. };
  73506. /**
  73507. * Returns the parent bone
  73508. */
  73509. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  73510. // Try to find
  73511. for (var i = 0; i < newSkeleton.bones.length; i++) {
  73512. if (newSkeleton.bones[i].name === jointName) {
  73513. return newSkeleton.bones[i];
  73514. }
  73515. }
  73516. // Not found, search in gltf nodes
  73517. var nodes = gltfRuntime.nodes;
  73518. for (var nde in nodes) {
  73519. var node = nodes[nde];
  73520. if (!node.jointName) {
  73521. continue;
  73522. }
  73523. var children = node.children;
  73524. for (var i = 0; i < children.length; i++) {
  73525. var child = gltfRuntime.nodes[children[i]];
  73526. if (!child.jointName) {
  73527. continue;
  73528. }
  73529. if (child.jointName === jointName) {
  73530. var mat = configureBoneTransformation(node);
  73531. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  73532. bone.id = nde;
  73533. return bone;
  73534. }
  73535. }
  73536. }
  73537. return null;
  73538. };
  73539. /**
  73540. * Returns the appropriate root node
  73541. */
  73542. var getNodeToRoot = function (nodesToRoot, id) {
  73543. for (var i = 0; i < nodesToRoot.length; i++) {
  73544. var nodeToRoot = nodesToRoot[i];
  73545. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  73546. var child = nodeToRoot.node.children[j];
  73547. if (child === id) {
  73548. return nodeToRoot.bone;
  73549. }
  73550. }
  73551. }
  73552. return null;
  73553. };
  73554. /**
  73555. * Returns the node with the joint name
  73556. */
  73557. var getJointNode = function (gltfRuntime, jointName) {
  73558. var nodes = gltfRuntime.nodes;
  73559. var node = nodes[jointName];
  73560. if (node) {
  73561. return {
  73562. node: node,
  73563. id: jointName
  73564. };
  73565. }
  73566. for (var nde in nodes) {
  73567. node = nodes[nde];
  73568. if (node.jointName === jointName) {
  73569. return {
  73570. node: node,
  73571. id: nde
  73572. };
  73573. }
  73574. }
  73575. return null;
  73576. };
  73577. /**
  73578. * Checks if a nodes is in joints
  73579. */
  73580. var nodeIsInJoints = function (skins, id) {
  73581. for (var i = 0; i < skins.jointNames.length; i++) {
  73582. if (skins.jointNames[i] === id) {
  73583. return true;
  73584. }
  73585. }
  73586. return false;
  73587. };
  73588. /**
  73589. * Fills the nodes to root for bones and builds hierarchy
  73590. */
  73591. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  73592. // Creates nodes for root
  73593. for (var nde in gltfRuntime.nodes) {
  73594. var node = gltfRuntime.nodes[nde];
  73595. var id = nde;
  73596. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  73597. continue;
  73598. }
  73599. // Create node to root bone
  73600. var mat = configureBoneTransformation(node);
  73601. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  73602. bone.id = id;
  73603. nodesToRoot.push({ bone: bone, node: node, id: id });
  73604. }
  73605. // Parenting
  73606. for (var i = 0; i < nodesToRoot.length; i++) {
  73607. var nodeToRoot = nodesToRoot[i];
  73608. var children = nodeToRoot.node.children;
  73609. for (var j = 0; j < children.length; j++) {
  73610. var child = null;
  73611. for (var k = 0; k < nodesToRoot.length; k++) {
  73612. if (nodesToRoot[k].id === children[j]) {
  73613. child = nodesToRoot[k];
  73614. break;
  73615. }
  73616. }
  73617. if (child) {
  73618. child.bone._parent = nodeToRoot.bone;
  73619. nodeToRoot.bone.children.push(child.bone);
  73620. }
  73621. }
  73622. }
  73623. };
  73624. var printMat = function (m) {
  73625. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  73626. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  73627. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  73628. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  73629. };
  73630. /**
  73631. * Imports a skeleton
  73632. */
  73633. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  73634. if (!newSkeleton) {
  73635. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  73636. }
  73637. if (!skins.babylonSkeleton) {
  73638. return newSkeleton;
  73639. }
  73640. // Matrices
  73641. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  73642. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73643. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  73644. // Find the root bones
  73645. var nodesToRoot = [];
  73646. var nodesToRootToAdd = [];
  73647. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  73648. newSkeleton.bones = [];
  73649. // Joints
  73650. for (var i = 0; i < skins.jointNames.length; i++) {
  73651. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73652. var node = jointNode.node;
  73653. if (!node) {
  73654. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  73655. continue;
  73656. }
  73657. var id = jointNode.id;
  73658. // Optimize, if the bone already exists...
  73659. var existingBone = gltfRuntime.scene.getBoneByID(id);
  73660. if (existingBone) {
  73661. newSkeleton.bones.push(existingBone);
  73662. continue;
  73663. }
  73664. // Search for parent bone
  73665. var foundBone = false;
  73666. var parentBone = null;
  73667. for (var j = 0; j < i; j++) {
  73668. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  73669. if (!joint) {
  73670. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  73671. continue;
  73672. }
  73673. var children = joint.children;
  73674. if (!children) {
  73675. continue;
  73676. }
  73677. foundBone = false;
  73678. for (var k = 0; k < children.length; k++) {
  73679. if (children[k] === id) {
  73680. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  73681. foundBone = true;
  73682. break;
  73683. }
  73684. }
  73685. if (foundBone) {
  73686. break;
  73687. }
  73688. }
  73689. // Create bone
  73690. var mat = configureBoneTransformation(node);
  73691. if (!parentBone && nodesToRoot.length > 0) {
  73692. parentBone = getNodeToRoot(nodesToRoot, id);
  73693. if (parentBone) {
  73694. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  73695. nodesToRootToAdd.push(parentBone);
  73696. }
  73697. }
  73698. }
  73699. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  73700. bone.id = id;
  73701. }
  73702. // Polish
  73703. var bones = newSkeleton.bones;
  73704. newSkeleton.bones = [];
  73705. for (var i = 0; i < skins.jointNames.length; i++) {
  73706. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73707. if (!jointNode) {
  73708. continue;
  73709. }
  73710. for (var j = 0; j < bones.length; j++) {
  73711. if (bones[j].id === jointNode.id) {
  73712. newSkeleton.bones.push(bones[j]);
  73713. break;
  73714. }
  73715. }
  73716. }
  73717. newSkeleton.prepare();
  73718. // Finish
  73719. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  73720. newSkeleton.bones.push(nodesToRootToAdd[i]);
  73721. }
  73722. return newSkeleton;
  73723. };
  73724. /**
  73725. * Imports a mesh and its geometries
  73726. */
  73727. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  73728. if (!newMesh) {
  73729. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73730. newMesh.id = id;
  73731. }
  73732. if (!node.babylonNode) {
  73733. return newMesh;
  73734. }
  73735. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  73736. if (!newMesh.material) {
  73737. newMesh.material = multiMat;
  73738. }
  73739. var vertexData = new BABYLON.VertexData();
  73740. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  73741. var verticesStarts = new Array();
  73742. var verticesCounts = new Array();
  73743. var indexStarts = new Array();
  73744. var indexCounts = new Array();
  73745. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73746. var meshID = meshes[meshIndex];
  73747. var mesh = gltfRuntime.meshes[meshID];
  73748. if (!mesh) {
  73749. continue;
  73750. }
  73751. // Positions, normals and UVs
  73752. for (var i = 0; i < mesh.primitives.length; i++) {
  73753. // Temporary vertex data
  73754. var tempVertexData = new BABYLON.VertexData();
  73755. var primitive = mesh.primitives[i];
  73756. if (primitive.mode !== 4) {
  73757. // continue;
  73758. }
  73759. var attributes = primitive.attributes;
  73760. var accessor = null;
  73761. var buffer = null;
  73762. // Set positions, normal and uvs
  73763. for (var semantic in attributes) {
  73764. // Link accessor and buffer view
  73765. accessor = gltfRuntime.accessors[attributes[semantic]];
  73766. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73767. if (semantic === "NORMAL") {
  73768. tempVertexData.normals = new Float32Array(buffer.length);
  73769. tempVertexData.normals.set(buffer);
  73770. }
  73771. else if (semantic === "POSITION") {
  73772. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  73773. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  73774. for (var j = 0; j < buffer.length; j += 4) {
  73775. tempVertexData.positions[j] = buffer[j];
  73776. tempVertexData.positions[j + 1] = buffer[j + 1];
  73777. tempVertexData.positions[j + 2] = buffer[j + 2];
  73778. }
  73779. }
  73780. else {
  73781. tempVertexData.positions = new Float32Array(buffer.length);
  73782. tempVertexData.positions.set(buffer);
  73783. }
  73784. verticesCounts.push(tempVertexData.positions.length);
  73785. }
  73786. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  73787. var channel = Number(semantic.split("_")[1]);
  73788. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  73789. var uvs = new Float32Array(buffer.length);
  73790. uvs.set(buffer);
  73791. normalizeUVs(uvs);
  73792. tempVertexData.set(uvs, uvKind);
  73793. }
  73794. else if (semantic === "JOINT") {
  73795. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  73796. tempVertexData.matricesIndices.set(buffer);
  73797. }
  73798. else if (semantic === "WEIGHT") {
  73799. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  73800. tempVertexData.matricesWeights.set(buffer);
  73801. }
  73802. else if (semantic === "COLOR") {
  73803. tempVertexData.colors = new Float32Array(buffer.length);
  73804. tempVertexData.colors.set(buffer);
  73805. }
  73806. }
  73807. // Indices
  73808. accessor = gltfRuntime.accessors[primitive.indices];
  73809. if (accessor) {
  73810. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73811. tempVertexData.indices = new Int32Array(buffer.length);
  73812. tempVertexData.indices.set(buffer);
  73813. indexCounts.push(tempVertexData.indices.length);
  73814. }
  73815. else {
  73816. // Set indices on the fly
  73817. var indices = [];
  73818. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73819. indices.push(j);
  73820. }
  73821. tempVertexData.indices = new Int32Array(indices);
  73822. indexCounts.push(tempVertexData.indices.length);
  73823. }
  73824. vertexData.merge(tempVertexData);
  73825. tempVertexData = undefined;
  73826. // Sub material
  73827. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73828. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73829. // Update vertices start and index start
  73830. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73831. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73832. }
  73833. }
  73834. // Apply geometry
  73835. geometry.setAllVerticesData(vertexData, false);
  73836. newMesh.computeWorldMatrix(true);
  73837. // Apply submeshes
  73838. newMesh.subMeshes = [];
  73839. var index = 0;
  73840. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73841. var meshID = meshes[meshIndex];
  73842. var mesh = gltfRuntime.meshes[meshID];
  73843. if (!mesh) {
  73844. continue;
  73845. }
  73846. for (var i = 0; i < mesh.primitives.length; i++) {
  73847. if (mesh.primitives[i].mode !== 4) {
  73848. //continue;
  73849. }
  73850. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73851. index++;
  73852. }
  73853. }
  73854. // Finish
  73855. return newMesh;
  73856. };
  73857. /**
  73858. * Configure node transformation from position, rotation and scaling
  73859. */
  73860. var configureNode = function (newNode, position, rotation, scaling) {
  73861. if (newNode.position) {
  73862. newNode.position = position;
  73863. }
  73864. if (newNode.rotationQuaternion || newNode.rotation) {
  73865. newNode.rotationQuaternion = rotation;
  73866. }
  73867. if (newNode.scaling) {
  73868. newNode.scaling = scaling;
  73869. }
  73870. };
  73871. /**
  73872. * Configures node from transformation matrix
  73873. */
  73874. var configureNodeFromMatrix = function (newNode, node, parent) {
  73875. if (node.matrix) {
  73876. var position = new BABYLON.Vector3(0, 0, 0);
  73877. var rotation = new BABYLON.Quaternion();
  73878. var scaling = new BABYLON.Vector3(0, 0, 0);
  73879. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73880. mat.decompose(scaling, rotation, position);
  73881. configureNode(newNode, position, rotation, scaling);
  73882. }
  73883. else {
  73884. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73885. }
  73886. newNode.computeWorldMatrix(true);
  73887. };
  73888. /**
  73889. * Imports a node
  73890. */
  73891. var importNode = function (gltfRuntime, node, id, parent) {
  73892. var lastNode = null;
  73893. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73894. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73895. return null;
  73896. }
  73897. }
  73898. // Meshes
  73899. if (node.skin) {
  73900. if (node.meshes) {
  73901. var skin = gltfRuntime.skins[node.skin];
  73902. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73903. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73904. if (newMesh.skeleton === null) {
  73905. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73906. if (!skin.babylonSkeleton) {
  73907. skin.babylonSkeleton = newMesh.skeleton;
  73908. }
  73909. }
  73910. lastNode = newMesh;
  73911. }
  73912. }
  73913. else if (node.meshes) {
  73914. /**
  73915. * Improve meshes property
  73916. */
  73917. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73918. lastNode = newMesh;
  73919. }
  73920. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73921. var light = gltfRuntime.lights[node.light];
  73922. if (light) {
  73923. if (light.type === "ambient") {
  73924. var ambienLight = light[light.type];
  73925. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73926. hemiLight.name = node.name;
  73927. if (ambienLight.color) {
  73928. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73929. }
  73930. lastNode = hemiLight;
  73931. }
  73932. else if (light.type === "directional") {
  73933. var directionalLight = light[light.type];
  73934. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73935. dirLight.name = node.name;
  73936. if (directionalLight.color) {
  73937. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73938. }
  73939. lastNode = dirLight;
  73940. }
  73941. else if (light.type === "point") {
  73942. var pointLight = light[light.type];
  73943. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73944. ptLight.name = node.name;
  73945. if (pointLight.color) {
  73946. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73947. }
  73948. lastNode = ptLight;
  73949. }
  73950. else if (light.type === "spot") {
  73951. var spotLight = light[light.type];
  73952. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73953. spLight.name = node.name;
  73954. if (spotLight.color) {
  73955. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73956. }
  73957. if (spotLight.fallOfAngle) {
  73958. spLight.angle = spotLight.fallOfAngle;
  73959. }
  73960. if (spotLight.fallOffExponent) {
  73961. spLight.exponent = spotLight.fallOffExponent;
  73962. }
  73963. lastNode = spLight;
  73964. }
  73965. }
  73966. }
  73967. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73968. var camera = gltfRuntime.cameras[node.camera];
  73969. if (camera) {
  73970. if (camera.type === "orthographic") {
  73971. var orthographicCamera = camera[camera.type];
  73972. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73973. orthoCamera.name = node.name;
  73974. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73975. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73976. lastNode = orthoCamera;
  73977. }
  73978. else if (camera.type === "perspective") {
  73979. var perspectiveCamera = camera[camera.type];
  73980. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73981. persCamera.name = node.name;
  73982. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73983. if (!perspectiveCamera.aspectRatio) {
  73984. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73985. }
  73986. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73987. persCamera.maxZ = perspectiveCamera.zfar;
  73988. persCamera.minZ = perspectiveCamera.znear;
  73989. }
  73990. lastNode = persCamera;
  73991. }
  73992. }
  73993. }
  73994. // Empty node
  73995. if (!node.jointName) {
  73996. if (node.babylonNode) {
  73997. return node.babylonNode;
  73998. }
  73999. else if (lastNode === null) {
  74000. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  74001. node.babylonNode = dummy;
  74002. lastNode = dummy;
  74003. }
  74004. }
  74005. if (lastNode !== null) {
  74006. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  74007. configureNodeFromMatrix(lastNode, node, parent);
  74008. }
  74009. else {
  74010. var translation = node.translation || [0, 0, 0];
  74011. var rotation = node.rotation || [0, 0, 0, 1];
  74012. var scale = node.scale || [1, 1, 1];
  74013. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  74014. }
  74015. lastNode.updateCache(true);
  74016. node.babylonNode = lastNode;
  74017. }
  74018. return lastNode;
  74019. };
  74020. /**
  74021. * Traverses nodes and creates them
  74022. */
  74023. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  74024. var node = gltfRuntime.nodes[id];
  74025. var newNode = null;
  74026. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  74027. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  74028. meshIncluded = true;
  74029. }
  74030. else {
  74031. meshIncluded = false;
  74032. }
  74033. }
  74034. else {
  74035. meshIncluded = true;
  74036. }
  74037. if (!node.jointName && meshIncluded) {
  74038. newNode = importNode(gltfRuntime, node, id, parent);
  74039. if (newNode !== null) {
  74040. newNode.id = id;
  74041. newNode.parent = parent;
  74042. }
  74043. }
  74044. if (node.children) {
  74045. for (var i = 0; i < node.children.length; i++) {
  74046. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  74047. }
  74048. }
  74049. };
  74050. /**
  74051. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  74052. */
  74053. var postLoad = function (gltfRuntime) {
  74054. // Nodes
  74055. var currentScene = gltfRuntime.currentScene;
  74056. if (currentScene) {
  74057. for (var i = 0; i < currentScene.nodes.length; i++) {
  74058. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74059. }
  74060. }
  74061. else {
  74062. for (var thing in gltfRuntime.scenes) {
  74063. currentScene = gltfRuntime.scenes[thing];
  74064. for (var i = 0; i < currentScene.nodes.length; i++) {
  74065. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74066. }
  74067. }
  74068. }
  74069. // Set animations
  74070. loadAnimations(gltfRuntime);
  74071. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  74072. var skeleton = gltfRuntime.scene.skeletons[i];
  74073. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  74074. }
  74075. };
  74076. /**
  74077. * onBind shaderrs callback to set uniforms and matrices
  74078. */
  74079. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  74080. var materialValues = material.values || technique.parameters;
  74081. for (var unif in unTreatedUniforms) {
  74082. var uniform = unTreatedUniforms[unif];
  74083. var type = uniform.type;
  74084. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  74085. if (uniform.semantic && !uniform.source && !uniform.node) {
  74086. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  74087. }
  74088. else if (uniform.semantic && (uniform.source || uniform.node)) {
  74089. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  74090. if (source === null) {
  74091. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  74092. }
  74093. if (source === null) {
  74094. continue;
  74095. }
  74096. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  74097. }
  74098. }
  74099. else {
  74100. var value = materialValues[technique.uniforms[unif]];
  74101. if (!value) {
  74102. continue;
  74103. }
  74104. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  74105. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  74106. if (texture === null || texture === undefined) {
  74107. continue;
  74108. }
  74109. shaderMaterial.getEffect().setTexture(unif, texture);
  74110. }
  74111. else {
  74112. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  74113. }
  74114. }
  74115. }
  74116. onSuccess(shaderMaterial);
  74117. };
  74118. /**
  74119. * Prepare uniforms to send the only one time
  74120. * Loads the appropriate textures
  74121. */
  74122. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  74123. var materialValues = material.values || technique.parameters;
  74124. var techniqueUniforms = technique.uniforms;
  74125. /**
  74126. * Prepare values here (not matrices)
  74127. */
  74128. for (var unif in unTreatedUniforms) {
  74129. var uniform = unTreatedUniforms[unif];
  74130. var type = uniform.type;
  74131. var value = materialValues[techniqueUniforms[unif]];
  74132. if (value === undefined) {
  74133. // In case the value is the same for all materials
  74134. value = uniform.value;
  74135. }
  74136. if (!value) {
  74137. continue;
  74138. }
  74139. var onLoadTexture = function (uniformName) {
  74140. return function (texture) {
  74141. if (uniform.value) {
  74142. // Static uniform
  74143. shaderMaterial.setTexture(uniformName, texture);
  74144. delete unTreatedUniforms[uniformName];
  74145. }
  74146. };
  74147. };
  74148. // Texture (sampler2D)
  74149. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  74150. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  74151. }
  74152. else {
  74153. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  74154. // Static uniform
  74155. delete unTreatedUniforms[unif];
  74156. }
  74157. }
  74158. }
  74159. };
  74160. /**
  74161. * Shader compilation failed
  74162. */
  74163. var onShaderCompileError = function (program, shaderMaterial, onError) {
  74164. return function (effect, error) {
  74165. shaderMaterial.dispose(true);
  74166. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  74167. };
  74168. };
  74169. /**
  74170. * Shader compilation success
  74171. */
  74172. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  74173. return function (_) {
  74174. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  74175. shaderMaterial.onBind = function (mesh) {
  74176. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  74177. };
  74178. };
  74179. };
  74180. /**
  74181. * Returns the appropriate uniform if already handled by babylon
  74182. */
  74183. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  74184. for (var unif in technique.uniforms) {
  74185. var uniform = technique.uniforms[unif];
  74186. var uniformParameter = technique.parameters[uniform];
  74187. if (tokenizer.currentIdentifier === unif) {
  74188. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  74189. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74190. if (transformIndex !== -1) {
  74191. delete unTreatedUniforms[unif];
  74192. return babylonTransforms[transformIndex];
  74193. }
  74194. }
  74195. }
  74196. }
  74197. return tokenizer.currentIdentifier;
  74198. };
  74199. /**
  74200. * All shaders loaded. Create materials one by one
  74201. */
  74202. var importMaterials = function (gltfRuntime) {
  74203. // Create materials
  74204. for (var mat in gltfRuntime.materials) {
  74205. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  74206. }
  74207. };
  74208. /**
  74209. * Implementation of the base glTF spec
  74210. */
  74211. var GLTFLoaderBase = (function () {
  74212. function GLTFLoaderBase() {
  74213. }
  74214. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  74215. var gltfRuntime = {
  74216. extensions: {},
  74217. accessors: {},
  74218. buffers: {},
  74219. bufferViews: {},
  74220. meshes: {},
  74221. lights: {},
  74222. cameras: {},
  74223. nodes: {},
  74224. images: {},
  74225. textures: {},
  74226. shaders: {},
  74227. programs: {},
  74228. samplers: {},
  74229. techniques: {},
  74230. materials: {},
  74231. animations: {},
  74232. skins: {},
  74233. extensionsUsed: [],
  74234. scenes: {},
  74235. buffersCount: 0,
  74236. shaderscount: 0,
  74237. scene: scene,
  74238. rootUrl: rootUrl,
  74239. loadedBufferCount: 0,
  74240. loadedBufferViews: {},
  74241. loadedShaderCount: 0,
  74242. importOnlyMeshes: false,
  74243. dummyNodes: []
  74244. };
  74245. // Parse
  74246. if (parsedData.extensions) {
  74247. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  74248. }
  74249. if (parsedData.extensionsUsed) {
  74250. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  74251. }
  74252. if (parsedData.buffers) {
  74253. parseBuffers(parsedData.buffers, gltfRuntime);
  74254. }
  74255. if (parsedData.bufferViews) {
  74256. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  74257. }
  74258. if (parsedData.accessors) {
  74259. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  74260. }
  74261. if (parsedData.meshes) {
  74262. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  74263. }
  74264. if (parsedData.lights) {
  74265. parseObject(parsedData.lights, "lights", gltfRuntime);
  74266. }
  74267. if (parsedData.cameras) {
  74268. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  74269. }
  74270. if (parsedData.nodes) {
  74271. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  74272. }
  74273. if (parsedData.images) {
  74274. parseObject(parsedData.images, "images", gltfRuntime);
  74275. }
  74276. if (parsedData.textures) {
  74277. parseObject(parsedData.textures, "textures", gltfRuntime);
  74278. }
  74279. if (parsedData.shaders) {
  74280. parseShaders(parsedData.shaders, gltfRuntime);
  74281. }
  74282. if (parsedData.programs) {
  74283. parseObject(parsedData.programs, "programs", gltfRuntime);
  74284. }
  74285. if (parsedData.samplers) {
  74286. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  74287. }
  74288. if (parsedData.techniques) {
  74289. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  74290. }
  74291. if (parsedData.materials) {
  74292. parseObject(parsedData.materials, "materials", gltfRuntime);
  74293. }
  74294. if (parsedData.animations) {
  74295. parseObject(parsedData.animations, "animations", gltfRuntime);
  74296. }
  74297. if (parsedData.skins) {
  74298. parseObject(parsedData.skins, "skins", gltfRuntime);
  74299. }
  74300. if (parsedData.scenes) {
  74301. gltfRuntime.scenes = parsedData.scenes;
  74302. }
  74303. if (parsedData.scene && parsedData.scenes) {
  74304. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  74305. }
  74306. return gltfRuntime;
  74307. };
  74308. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74309. var buffer = gltfRuntime.buffers[id];
  74310. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  74311. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  74312. }
  74313. else {
  74314. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  74315. onError(request.status + " " + request.statusText);
  74316. });
  74317. }
  74318. };
  74319. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74320. var texture = gltfRuntime.textures[id];
  74321. if (!texture || !texture.source) {
  74322. onError(null);
  74323. return;
  74324. }
  74325. if (texture.babylonTexture) {
  74326. onSuccess(null);
  74327. return;
  74328. }
  74329. var source = gltfRuntime.images[texture.source];
  74330. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  74331. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  74332. }
  74333. else {
  74334. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  74335. onError(request.status + " " + request.statusText);
  74336. });
  74337. }
  74338. };
  74339. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74340. var texture = gltfRuntime.textures[id];
  74341. if (texture.babylonTexture) {
  74342. onSuccess(texture.babylonTexture);
  74343. return;
  74344. }
  74345. var sampler = gltfRuntime.samplers[texture.sampler];
  74346. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  74347. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  74348. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  74349. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  74350. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74351. var blob = new Blob([buffer]);
  74352. var blobURL = URL.createObjectURL(blob);
  74353. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  74354. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  74355. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  74356. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  74357. newTexture.name = id;
  74358. texture.babylonTexture = newTexture;
  74359. onSuccess(newTexture);
  74360. };
  74361. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74362. var shader = gltfRuntime.shaders[id];
  74363. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  74364. var shaderString = atob(shader.uri.split(",")[1]);
  74365. onSuccess(shaderString);
  74366. }
  74367. else {
  74368. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  74369. onError(request.status + " " + request.statusText);
  74370. });
  74371. }
  74372. };
  74373. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74374. var material = gltfRuntime.materials[id];
  74375. var technique = gltfRuntime.techniques[material.technique];
  74376. if (!technique) {
  74377. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74378. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  74379. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74380. onSuccess(defaultMaterial);
  74381. return;
  74382. }
  74383. var program = gltfRuntime.programs[technique.program];
  74384. var states = technique.states;
  74385. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  74386. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  74387. var newVertexShader = "";
  74388. var newPixelShader = "";
  74389. var vertexTokenizer = new Tokenizer(vertexShader);
  74390. var pixelTokenizer = new Tokenizer(pixelShader);
  74391. var unTreatedUniforms = {};
  74392. var uniforms = [];
  74393. var attributes = [];
  74394. var samplers = [];
  74395. // Fill uniform, sampler2D and attributes
  74396. for (var unif in technique.uniforms) {
  74397. var uniform = technique.uniforms[unif];
  74398. var uniformParameter = technique.parameters[uniform];
  74399. unTreatedUniforms[unif] = uniformParameter;
  74400. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  74401. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74402. if (transformIndex !== -1) {
  74403. uniforms.push(babylonTransforms[transformIndex]);
  74404. delete unTreatedUniforms[unif];
  74405. }
  74406. else {
  74407. uniforms.push(unif);
  74408. }
  74409. }
  74410. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  74411. samplers.push(unif);
  74412. }
  74413. else {
  74414. uniforms.push(unif);
  74415. }
  74416. }
  74417. for (var attr in technique.attributes) {
  74418. var attribute = technique.attributes[attr];
  74419. var attributeParameter = technique.parameters[attribute];
  74420. if (attributeParameter.semantic) {
  74421. attributes.push(getAttribute(attributeParameter));
  74422. }
  74423. }
  74424. // Configure vertex shader
  74425. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  74426. var tokenType = vertexTokenizer.currentToken;
  74427. if (tokenType !== ETokenType.IDENTIFIER) {
  74428. newVertexShader += vertexTokenizer.currentString;
  74429. continue;
  74430. }
  74431. var foundAttribute = false;
  74432. for (var attr in technique.attributes) {
  74433. var attribute = technique.attributes[attr];
  74434. var attributeParameter = technique.parameters[attribute];
  74435. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  74436. newVertexShader += getAttribute(attributeParameter);
  74437. foundAttribute = true;
  74438. break;
  74439. }
  74440. }
  74441. if (foundAttribute) {
  74442. continue;
  74443. }
  74444. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  74445. }
  74446. // Configure pixel shader
  74447. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  74448. var tokenType = pixelTokenizer.currentToken;
  74449. if (tokenType !== ETokenType.IDENTIFIER) {
  74450. newPixelShader += pixelTokenizer.currentString;
  74451. continue;
  74452. }
  74453. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  74454. }
  74455. // Create shader material
  74456. var shaderPath = {
  74457. vertex: program.vertexShader + id,
  74458. fragment: program.fragmentShader + id
  74459. };
  74460. var options = {
  74461. attributes: attributes,
  74462. uniforms: uniforms,
  74463. samplers: samplers,
  74464. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  74465. };
  74466. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  74467. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  74468. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  74469. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  74470. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  74471. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74472. if (states && states.functions) {
  74473. var functions = states.functions;
  74474. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  74475. shaderMaterial.backFaceCulling = false;
  74476. }
  74477. var blendFunc = functions.blendFuncSeparate;
  74478. if (blendFunc) {
  74479. 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) {
  74480. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  74481. }
  74482. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74483. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74484. }
  74485. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74486. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  74487. }
  74488. 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) {
  74489. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  74490. }
  74491. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74492. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  74493. }
  74494. 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) {
  74495. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  74496. }
  74497. }
  74498. }
  74499. };
  74500. return GLTFLoaderBase;
  74501. }());
  74502. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  74503. /**
  74504. * glTF V1 Loader
  74505. */
  74506. var GLTFLoader = (function () {
  74507. function GLTFLoader() {
  74508. }
  74509. GLTFLoader.RegisterExtension = function (extension) {
  74510. if (GLTFLoader.Extensions[extension.name]) {
  74511. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  74512. return;
  74513. }
  74514. GLTFLoader.Extensions[extension.name] = extension;
  74515. };
  74516. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74517. var _this = this;
  74518. scene.useRightHandedSystem = true;
  74519. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74520. gltfRuntime.importOnlyMeshes = true;
  74521. if (meshesNames === "") {
  74522. gltfRuntime.importMeshesNames = [];
  74523. }
  74524. else if (typeof meshesNames === "string") {
  74525. gltfRuntime.importMeshesNames = [meshesNames];
  74526. }
  74527. else if (meshesNames && !(meshesNames instanceof Array)) {
  74528. gltfRuntime.importMeshesNames = [meshesNames];
  74529. }
  74530. else {
  74531. gltfRuntime.importMeshesNames = [];
  74532. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  74533. }
  74534. // Create nodes
  74535. _this._createNodes(gltfRuntime);
  74536. var meshes = new Array();
  74537. var skeletons = new Array();
  74538. // Fill arrays of meshes and skeletons
  74539. for (var nde in gltfRuntime.nodes) {
  74540. var node = gltfRuntime.nodes[nde];
  74541. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  74542. meshes.push(node.babylonNode);
  74543. }
  74544. }
  74545. for (var skl in gltfRuntime.skins) {
  74546. var skin = gltfRuntime.skins[skl];
  74547. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74548. skeletons.push(skin.babylonSkeleton);
  74549. }
  74550. }
  74551. // Load buffers, shaders, materials, etc.
  74552. _this._loadBuffersAsync(gltfRuntime, function () {
  74553. _this._loadShadersAsync(gltfRuntime, function () {
  74554. importMaterials(gltfRuntime);
  74555. postLoad(gltfRuntime);
  74556. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74557. onSuccess(meshes, null, skeletons);
  74558. }
  74559. });
  74560. }, onProgress);
  74561. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74562. onSuccess(meshes, null, skeletons);
  74563. }
  74564. }, onError);
  74565. return true;
  74566. };
  74567. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74568. var _this = this;
  74569. scene.useRightHandedSystem = true;
  74570. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74571. // Load runtime extensios
  74572. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  74573. // Create nodes
  74574. _this._createNodes(gltfRuntime);
  74575. // Load buffers, shaders, materials, etc.
  74576. _this._loadBuffersAsync(gltfRuntime, function () {
  74577. _this._loadShadersAsync(gltfRuntime, function () {
  74578. importMaterials(gltfRuntime);
  74579. postLoad(gltfRuntime);
  74580. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  74581. onSuccess();
  74582. }
  74583. });
  74584. });
  74585. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  74586. onSuccess();
  74587. }
  74588. }, onError);
  74589. }, onError);
  74590. };
  74591. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  74592. var hasShaders = false;
  74593. var processShader = function (sha, shader) {
  74594. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  74595. gltfRuntime.loadedShaderCount++;
  74596. if (shaderString) {
  74597. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  74598. }
  74599. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  74600. onload();
  74601. }
  74602. }, function () {
  74603. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  74604. });
  74605. };
  74606. for (var sha in gltfRuntime.shaders) {
  74607. hasShaders = true;
  74608. var shader = gltfRuntime.shaders[sha];
  74609. if (shader) {
  74610. processShader.bind(this, sha, shader)();
  74611. }
  74612. else {
  74613. BABYLON.Tools.Error("No shader named: " + sha);
  74614. }
  74615. }
  74616. if (!hasShaders) {
  74617. onload();
  74618. }
  74619. };
  74620. ;
  74621. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  74622. var hasBuffers = false;
  74623. var processBuffer = function (buf, buffer) {
  74624. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  74625. gltfRuntime.loadedBufferCount++;
  74626. if (bufferView) {
  74627. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  74628. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  74629. }
  74630. gltfRuntime.loadedBufferViews[buf] = bufferView;
  74631. }
  74632. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  74633. onLoad();
  74634. }
  74635. }, function () {
  74636. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  74637. });
  74638. };
  74639. for (var buf in gltfRuntime.buffers) {
  74640. hasBuffers = true;
  74641. var buffer = gltfRuntime.buffers[buf];
  74642. if (buffer) {
  74643. processBuffer.bind(this, buf, buffer)();
  74644. }
  74645. else {
  74646. BABYLON.Tools.Error("No buffer named: " + buf);
  74647. }
  74648. }
  74649. if (!hasBuffers) {
  74650. onLoad();
  74651. }
  74652. };
  74653. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  74654. var currentScene = gltfRuntime.currentScene;
  74655. if (currentScene) {
  74656. // Only one scene even if multiple scenes are defined
  74657. for (var i = 0; i < currentScene.nodes.length; i++) {
  74658. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74659. }
  74660. }
  74661. else {
  74662. // Load all scenes
  74663. for (var thing in gltfRuntime.scenes) {
  74664. currentScene = gltfRuntime.scenes[thing];
  74665. for (var i = 0; i < currentScene.nodes.length; i++) {
  74666. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74667. }
  74668. }
  74669. }
  74670. };
  74671. GLTFLoader.Extensions = {};
  74672. return GLTFLoader;
  74673. }());
  74674. GLTF1.GLTFLoader = GLTFLoader;
  74675. ;
  74676. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  74677. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74678. })(BABYLON || (BABYLON = {}));
  74679. //# sourceMappingURL=babylon.glTFLoader.js.map
  74680. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74681. var BABYLON;
  74682. (function (BABYLON) {
  74683. var GLTF1;
  74684. (function (GLTF1) {
  74685. /**
  74686. * Utils functions for GLTF
  74687. */
  74688. var GLTFUtils = (function () {
  74689. function GLTFUtils() {
  74690. }
  74691. /**
  74692. * Sets the given "parameter" matrix
  74693. * @param scene: the {BABYLON.Scene} object
  74694. * @param source: the source node where to pick the matrix
  74695. * @param parameter: the GLTF technique parameter
  74696. * @param uniformName: the name of the shader's uniform
  74697. * @param shaderMaterial: the shader material
  74698. */
  74699. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  74700. var mat = null;
  74701. if (parameter.semantic === "MODEL") {
  74702. mat = source.getWorldMatrix();
  74703. }
  74704. else if (parameter.semantic === "PROJECTION") {
  74705. mat = scene.getProjectionMatrix();
  74706. }
  74707. else if (parameter.semantic === "VIEW") {
  74708. mat = scene.getViewMatrix();
  74709. }
  74710. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  74711. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  74712. }
  74713. else if (parameter.semantic === "MODELVIEW") {
  74714. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  74715. }
  74716. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  74717. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  74718. }
  74719. else if (parameter.semantic === "MODELINVERSE") {
  74720. mat = source.getWorldMatrix().invert();
  74721. }
  74722. else if (parameter.semantic === "VIEWINVERSE") {
  74723. mat = scene.getViewMatrix().invert();
  74724. }
  74725. else if (parameter.semantic === "PROJECTIONINVERSE") {
  74726. mat = scene.getProjectionMatrix().invert();
  74727. }
  74728. else if (parameter.semantic === "MODELVIEWINVERSE") {
  74729. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  74730. }
  74731. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  74732. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  74733. }
  74734. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  74735. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  74736. }
  74737. else {
  74738. debugger;
  74739. }
  74740. switch (parameter.type) {
  74741. case GLTF1.EParameterType.FLOAT_MAT2:
  74742. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  74743. break;
  74744. case GLTF1.EParameterType.FLOAT_MAT3:
  74745. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  74746. break;
  74747. case GLTF1.EParameterType.FLOAT_MAT4:
  74748. shaderMaterial.setMatrix(uniformName, mat);
  74749. break;
  74750. default: break;
  74751. }
  74752. };
  74753. /**
  74754. * Sets the given "parameter" matrix
  74755. * @param shaderMaterial: the shader material
  74756. * @param uniform: the name of the shader's uniform
  74757. * @param value: the value of the uniform
  74758. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  74759. */
  74760. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  74761. switch (type) {
  74762. case GLTF1.EParameterType.FLOAT:
  74763. shaderMaterial.setFloat(uniform, value);
  74764. return true;
  74765. case GLTF1.EParameterType.FLOAT_VEC2:
  74766. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  74767. return true;
  74768. case GLTF1.EParameterType.FLOAT_VEC3:
  74769. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  74770. return true;
  74771. case GLTF1.EParameterType.FLOAT_VEC4:
  74772. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  74773. return true;
  74774. default: return false;
  74775. }
  74776. };
  74777. /**
  74778. * If the uri is a base64 string
  74779. * @param uri: the uri to test
  74780. */
  74781. GLTFUtils.IsBase64 = function (uri) {
  74782. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74783. };
  74784. /**
  74785. * Decode the base64 uri
  74786. * @param uri: the uri to decode
  74787. */
  74788. GLTFUtils.DecodeBase64 = function (uri) {
  74789. var decodedString = atob(uri.split(",")[1]);
  74790. var bufferLength = decodedString.length;
  74791. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74792. for (var i = 0; i < bufferLength; i++) {
  74793. bufferView[i] = decodedString.charCodeAt(i);
  74794. }
  74795. return bufferView.buffer;
  74796. };
  74797. /**
  74798. * Returns the wrap mode of the texture
  74799. * @param mode: the mode value
  74800. */
  74801. GLTFUtils.GetWrapMode = function (mode) {
  74802. switch (mode) {
  74803. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74804. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74805. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74806. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74807. }
  74808. };
  74809. /**
  74810. * Returns the byte stride giving an accessor
  74811. * @param accessor: the GLTF accessor objet
  74812. */
  74813. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74814. // Needs this function since "byteStride" isn't requiered in glTF format
  74815. var type = accessor.type;
  74816. switch (type) {
  74817. case "VEC2": return 2;
  74818. case "VEC3": return 3;
  74819. case "VEC4": return 4;
  74820. case "MAT2": return 4;
  74821. case "MAT3": return 9;
  74822. case "MAT4": return 16;
  74823. default: return 1;
  74824. }
  74825. };
  74826. /**
  74827. * Returns the texture filter mode giving a mode value
  74828. * @param mode: the filter mode value
  74829. */
  74830. GLTFUtils.GetTextureFilterMode = function (mode) {
  74831. switch (mode) {
  74832. case GLTF1.ETextureFilterType.LINEAR:
  74833. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74834. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74835. case GLTF1.ETextureFilterType.NEAREST:
  74836. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74837. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74838. }
  74839. };
  74840. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74841. var byteOffset = bufferView.byteOffset + byteOffset;
  74842. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74843. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74844. throw new Error("Buffer access is out of range");
  74845. }
  74846. var buffer = loadedBufferView.buffer;
  74847. byteOffset += loadedBufferView.byteOffset;
  74848. switch (componentType) {
  74849. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74850. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74851. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74852. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74853. default: return new Float32Array(buffer, byteOffset, byteLength);
  74854. }
  74855. };
  74856. /**
  74857. * Returns a buffer from its accessor
  74858. * @param gltfRuntime: the GLTF runtime
  74859. * @param accessor: the GLTF accessor
  74860. */
  74861. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74862. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74863. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74864. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74865. };
  74866. /**
  74867. * Decodes a buffer view into a string
  74868. * @param view: the buffer view
  74869. */
  74870. GLTFUtils.DecodeBufferToText = function (view) {
  74871. var result = "";
  74872. var length = view.byteLength;
  74873. for (var i = 0; i < length; ++i) {
  74874. result += String.fromCharCode(view[i]);
  74875. }
  74876. return result;
  74877. };
  74878. /**
  74879. * Returns the default material of gltf. Related to
  74880. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74881. * @param scene: the Babylon.js scene
  74882. */
  74883. GLTFUtils.GetDefaultMaterial = function (scene) {
  74884. if (!GLTFUtils._DefaultMaterial) {
  74885. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74886. "precision highp float;",
  74887. "",
  74888. "uniform mat4 worldView;",
  74889. "uniform mat4 projection;",
  74890. "",
  74891. "attribute vec3 position;",
  74892. "",
  74893. "void main(void)",
  74894. "{",
  74895. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74896. "}"
  74897. ].join("\n");
  74898. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74899. "precision highp float;",
  74900. "",
  74901. "uniform vec4 u_emission;",
  74902. "",
  74903. "void main(void)",
  74904. "{",
  74905. " gl_FragColor = u_emission;",
  74906. "}"
  74907. ].join("\n");
  74908. var shaderPath = {
  74909. vertex: "GLTFDefaultMaterial",
  74910. fragment: "GLTFDefaultMaterial"
  74911. };
  74912. var options = {
  74913. attributes: ["position"],
  74914. uniforms: ["worldView", "projection", "u_emission"],
  74915. samplers: new Array(),
  74916. needAlphaBlending: false
  74917. };
  74918. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74919. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74920. }
  74921. return GLTFUtils._DefaultMaterial;
  74922. };
  74923. // The GLTF default material
  74924. GLTFUtils._DefaultMaterial = null;
  74925. return GLTFUtils;
  74926. }());
  74927. GLTF1.GLTFUtils = GLTFUtils;
  74928. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74929. })(BABYLON || (BABYLON = {}));
  74930. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74931. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74932. var BABYLON;
  74933. (function (BABYLON) {
  74934. var GLTF1;
  74935. (function (GLTF1) {
  74936. var GLTFLoaderExtension = (function () {
  74937. function GLTFLoaderExtension(name) {
  74938. this._name = name;
  74939. }
  74940. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74941. get: function () {
  74942. return this._name;
  74943. },
  74944. enumerable: true,
  74945. configurable: true
  74946. });
  74947. /**
  74948. * Defines an override for loading the runtime
  74949. * Return true to stop further extensions from loading the runtime
  74950. */
  74951. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74952. return false;
  74953. };
  74954. /**
  74955. * Defines an onverride for creating gltf runtime
  74956. * Return true to stop further extensions from creating the runtime
  74957. */
  74958. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74959. return false;
  74960. };
  74961. /**
  74962. * Defines an override for loading buffers
  74963. * Return true to stop further extensions from loading this buffer
  74964. */
  74965. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74966. return false;
  74967. };
  74968. /**
  74969. * Defines an override for loading texture buffers
  74970. * Return true to stop further extensions from loading this texture data
  74971. */
  74972. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74973. return false;
  74974. };
  74975. /**
  74976. * Defines an override for creating textures
  74977. * Return true to stop further extensions from loading this texture
  74978. */
  74979. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74980. return false;
  74981. };
  74982. /**
  74983. * Defines an override for loading shader strings
  74984. * Return true to stop further extensions from loading this shader data
  74985. */
  74986. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74987. return false;
  74988. };
  74989. /**
  74990. * Defines an override for loading materials
  74991. * Return true to stop further extensions from loading this material
  74992. */
  74993. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74994. return false;
  74995. };
  74996. // ---------
  74997. // Utilities
  74998. // ---------
  74999. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  75000. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75001. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  75002. }, function () {
  75003. setTimeout(function () {
  75004. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  75005. });
  75006. });
  75007. };
  75008. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  75009. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75010. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  75011. }, function () {
  75012. setTimeout(function () {
  75013. onSuccess();
  75014. });
  75015. });
  75016. };
  75017. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  75018. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75019. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  75020. }, function () {
  75021. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  75022. });
  75023. };
  75024. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  75025. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  75026. };
  75027. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  75028. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75029. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  75030. }, function () {
  75031. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  75032. });
  75033. };
  75034. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  75035. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75036. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  75037. }, function () {
  75038. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  75039. });
  75040. };
  75041. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75042. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75043. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  75044. }, function () {
  75045. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  75046. });
  75047. };
  75048. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  75049. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75050. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  75051. }, function () {
  75052. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  75053. });
  75054. };
  75055. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  75056. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  75057. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  75058. if (func(loaderExtension)) {
  75059. return;
  75060. }
  75061. }
  75062. defaultFunc();
  75063. };
  75064. return GLTFLoaderExtension;
  75065. }());
  75066. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  75067. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75068. })(BABYLON || (BABYLON = {}));
  75069. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  75070. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75071. var BABYLON;
  75072. (function (BABYLON) {
  75073. var GLTF1;
  75074. (function (GLTF1) {
  75075. var BinaryExtensionBufferName = "binary_glTF";
  75076. var EContentFormat;
  75077. (function (EContentFormat) {
  75078. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  75079. })(EContentFormat || (EContentFormat = {}));
  75080. ;
  75081. ;
  75082. ;
  75083. var GLTFBinaryExtension = (function (_super) {
  75084. __extends(GLTFBinaryExtension, _super);
  75085. function GLTFBinaryExtension() {
  75086. return _super.call(this, "KHR_binary_glTF") || this;
  75087. }
  75088. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  75089. var extensionsUsed = data.json.extensionsUsed;
  75090. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  75091. return false;
  75092. }
  75093. this._bin = data.bin;
  75094. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  75095. return true;
  75096. };
  75097. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75098. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  75099. return false;
  75100. }
  75101. if (id !== BinaryExtensionBufferName) {
  75102. return false;
  75103. }
  75104. onSuccess(this._bin);
  75105. return true;
  75106. };
  75107. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75108. var texture = gltfRuntime.textures[id];
  75109. var source = gltfRuntime.images[texture.source];
  75110. if (!source.extensions || !(this.name in source.extensions)) {
  75111. return false;
  75112. }
  75113. var sourceExt = source.extensions[this.name];
  75114. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  75115. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  75116. onSuccess(buffer);
  75117. return true;
  75118. };
  75119. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  75120. var shader = gltfRuntime.shaders[id];
  75121. if (!shader.extensions || !(this.name in shader.extensions)) {
  75122. return false;
  75123. }
  75124. var binaryExtensionShader = shader.extensions[this.name];
  75125. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  75126. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  75127. setTimeout(function () {
  75128. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  75129. onSuccess(shaderString);
  75130. });
  75131. return true;
  75132. };
  75133. return GLTFBinaryExtension;
  75134. }(GLTF1.GLTFLoaderExtension));
  75135. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  75136. var BinaryReader = (function () {
  75137. function BinaryReader(arrayBuffer) {
  75138. this._arrayBuffer = arrayBuffer;
  75139. this._dataView = new DataView(arrayBuffer);
  75140. this._byteOffset = 0;
  75141. }
  75142. BinaryReader.prototype.getUint32 = function () {
  75143. var value = this._dataView.getUint32(this._byteOffset, true);
  75144. this._byteOffset += 4;
  75145. return value;
  75146. };
  75147. BinaryReader.prototype.getUint8Array = function (length) {
  75148. if (!length) {
  75149. length = this._arrayBuffer.byteLength - this._byteOffset;
  75150. }
  75151. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75152. this._byteOffset += length;
  75153. return value;
  75154. };
  75155. return BinaryReader;
  75156. }());
  75157. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  75158. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75159. })(BABYLON || (BABYLON = {}));
  75160. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  75161. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75162. var BABYLON;
  75163. (function (BABYLON) {
  75164. var GLTF1;
  75165. (function (GLTF1) {
  75166. ;
  75167. ;
  75168. ;
  75169. var GLTFMaterialsCommonExtension = (function (_super) {
  75170. __extends(GLTFMaterialsCommonExtension, _super);
  75171. function GLTFMaterialsCommonExtension() {
  75172. return _super.call(this, "KHR_materials_common") || this;
  75173. }
  75174. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  75175. if (!gltfRuntime.extensions)
  75176. return false;
  75177. var extension = gltfRuntime.extensions[this.name];
  75178. if (!extension)
  75179. return false;
  75180. // Create lights
  75181. var lights = extension.lights;
  75182. if (lights) {
  75183. for (var thing in lights) {
  75184. var light = lights[thing];
  75185. switch (light.type) {
  75186. case "ambient":
  75187. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  75188. var ambient = light.ambient;
  75189. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  75190. break;
  75191. case "point":
  75192. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  75193. var point = light.point;
  75194. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  75195. break;
  75196. case "directional":
  75197. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  75198. var directional = light.directional;
  75199. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  75200. break;
  75201. case "spot":
  75202. var spot = light.spot;
  75203. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  75204. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  75205. break;
  75206. default:
  75207. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  75208. break;
  75209. }
  75210. }
  75211. }
  75212. return false;
  75213. };
  75214. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  75215. var material = gltfRuntime.materials[id];
  75216. if (!material || !material.extensions)
  75217. return false;
  75218. var extension = material.extensions[this.name];
  75219. if (!extension)
  75220. return false;
  75221. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  75222. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75223. if (extension.technique === "CONSTANT") {
  75224. standardMaterial.disableLighting = true;
  75225. }
  75226. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  75227. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  75228. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  75229. // Ambient
  75230. if (typeof extension.values.ambient === "string") {
  75231. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  75232. }
  75233. else {
  75234. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  75235. }
  75236. // Diffuse
  75237. if (typeof extension.values.diffuse === "string") {
  75238. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  75239. }
  75240. else {
  75241. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  75242. }
  75243. // Emission
  75244. if (typeof extension.values.emission === "string") {
  75245. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  75246. }
  75247. else {
  75248. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  75249. }
  75250. // Specular
  75251. if (typeof extension.values.specular === "string") {
  75252. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  75253. }
  75254. else {
  75255. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  75256. }
  75257. return true;
  75258. };
  75259. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  75260. // Create buffer from texture url
  75261. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  75262. // Create texture from buffer
  75263. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  75264. }, onError);
  75265. };
  75266. return GLTFMaterialsCommonExtension;
  75267. }(GLTF1.GLTFLoaderExtension));
  75268. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  75269. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  75270. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75271. })(BABYLON || (BABYLON = {}));
  75272. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  75273. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75274. var BABYLON;
  75275. (function (BABYLON) {
  75276. var GLTF2;
  75277. (function (GLTF2) {
  75278. /**
  75279. * Enums
  75280. */
  75281. var EComponentType;
  75282. (function (EComponentType) {
  75283. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75284. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75285. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75286. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75287. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75288. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75289. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  75290. var EMeshPrimitiveMode;
  75291. (function (EMeshPrimitiveMode) {
  75292. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  75293. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  75294. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  75295. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  75296. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  75297. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  75298. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  75299. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  75300. var ETextureMagFilter;
  75301. (function (ETextureMagFilter) {
  75302. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  75303. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  75304. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  75305. var ETextureMinFilter;
  75306. (function (ETextureMinFilter) {
  75307. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  75308. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  75309. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75310. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75311. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75312. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75313. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  75314. var ETextureWrapMode;
  75315. (function (ETextureWrapMode) {
  75316. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75317. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75318. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75319. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  75320. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75321. })(BABYLON || (BABYLON = {}));
  75322. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75323. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75324. var BABYLON;
  75325. (function (BABYLON) {
  75326. var GLTF2;
  75327. (function (GLTF2) {
  75328. var GLTFLoaderTracker = (function () {
  75329. function GLTFLoaderTracker(onComplete) {
  75330. this._pendingCount = 0;
  75331. this._callback = onComplete;
  75332. }
  75333. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  75334. this._pendingCount++;
  75335. };
  75336. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  75337. if (--this._pendingCount === 0) {
  75338. this._callback();
  75339. }
  75340. };
  75341. return GLTFLoaderTracker;
  75342. }());
  75343. var GLTFLoader = (function () {
  75344. function GLTFLoader(parent) {
  75345. this._renderReady = false;
  75346. this._disposed = false;
  75347. this._renderReadyObservable = new BABYLON.Observable();
  75348. // Count of pending work that needs to complete before the asset is rendered.
  75349. this._renderPendingCount = 0;
  75350. // Count of pending work that needs to complete before the loader is disposed.
  75351. this._loaderPendingCount = 0;
  75352. this._loaderTrackers = new Array();
  75353. this._parent = parent;
  75354. }
  75355. GLTFLoader.RegisterExtension = function (extension) {
  75356. if (GLTFLoader.Extensions[extension.name]) {
  75357. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  75358. return;
  75359. }
  75360. GLTFLoader.Extensions[extension.name] = extension;
  75361. // Keep the order of registration so that extensions registered first are called first.
  75362. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  75363. };
  75364. GLTFLoader.prototype.dispose = function () {
  75365. if (this._disposed) {
  75366. return;
  75367. }
  75368. this._disposed = true;
  75369. // Revoke object urls created during load
  75370. if (this._gltf.textures) {
  75371. this._gltf.textures.forEach(function (texture) {
  75372. if (texture.url) {
  75373. URL.revokeObjectURL(texture.url);
  75374. }
  75375. });
  75376. }
  75377. this._gltf = undefined;
  75378. this._babylonScene = undefined;
  75379. this._rootUrl = undefined;
  75380. this._defaultMaterial = undefined;
  75381. this._successCallback = undefined;
  75382. this._errorCallback = undefined;
  75383. this._renderReady = false;
  75384. this._renderReadyObservable.clear();
  75385. this._renderPendingCount = 0;
  75386. this._loaderPendingCount = 0;
  75387. };
  75388. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75389. var _this = this;
  75390. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  75391. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  75392. }, onProgress, onError);
  75393. };
  75394. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75395. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  75396. };
  75397. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75398. var _this = this;
  75399. this._tryCatchOnError(function () {
  75400. _this._loadData(data);
  75401. _this._babylonScene = scene;
  75402. _this._rootUrl = rootUrl;
  75403. _this._successCallback = onSuccess;
  75404. _this._progressCallback = onProgress;
  75405. _this._errorCallback = onError;
  75406. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  75407. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  75408. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  75409. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  75410. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  75411. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  75412. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  75413. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  75414. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  75415. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  75416. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  75417. _this._addPendingData(_this);
  75418. _this._loadDefaultScene(nodeNames);
  75419. _this._loadAnimations();
  75420. _this._removePendingData(_this);
  75421. });
  75422. };
  75423. GLTFLoader.prototype._onError = function (message) {
  75424. if (this._disposed) {
  75425. return;
  75426. }
  75427. BABYLON.Tools.Error("glTF Loader: " + message);
  75428. if (this._errorCallback) {
  75429. this._errorCallback(message);
  75430. }
  75431. this.dispose();
  75432. };
  75433. GLTFLoader.prototype._onProgress = function (event) {
  75434. if (this._disposed) {
  75435. return;
  75436. }
  75437. if (this._progressCallback) {
  75438. this._progressCallback(event);
  75439. }
  75440. };
  75441. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  75442. if (this._renderReady) {
  75443. func();
  75444. }
  75445. else {
  75446. this._renderReadyObservable.add(func);
  75447. }
  75448. };
  75449. GLTFLoader.prototype._onRenderReady = function () {
  75450. this._rootNode.babylonMesh.setEnabled(true);
  75451. this._startAnimations();
  75452. this._successCallback();
  75453. this._renderReadyObservable.notifyObservers(this);
  75454. if (this._parent.onReady) {
  75455. this._parent.onReady();
  75456. }
  75457. };
  75458. GLTFLoader.prototype._onComplete = function () {
  75459. if (this._parent.onComplete) {
  75460. this._parent.onComplete();
  75461. }
  75462. this.dispose();
  75463. };
  75464. GLTFLoader.prototype._loadData = function (data) {
  75465. this._gltf = data.json;
  75466. if (data.bin) {
  75467. var buffers = this._gltf.buffers;
  75468. if (buffers && buffers[0] && !buffers[0].uri) {
  75469. var binaryBuffer = buffers[0];
  75470. if (binaryBuffer.byteLength != data.bin.byteLength) {
  75471. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  75472. }
  75473. binaryBuffer.loadedData = data.bin;
  75474. }
  75475. else {
  75476. BABYLON.Tools.Warn("Unexpected BIN chunk");
  75477. }
  75478. }
  75479. };
  75480. GLTFLoader.prototype._getMeshes = function () {
  75481. var meshes = [this._rootNode.babylonMesh];
  75482. var nodes = this._gltf.nodes;
  75483. if (nodes) {
  75484. nodes.forEach(function (node) {
  75485. if (node.babylonMesh) {
  75486. meshes.push(node.babylonMesh);
  75487. }
  75488. });
  75489. }
  75490. return meshes;
  75491. };
  75492. GLTFLoader.prototype._getSkeletons = function () {
  75493. var skeletons = new Array();
  75494. var skins = this._gltf.skins;
  75495. if (skins) {
  75496. skins.forEach(function (skin) {
  75497. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  75498. skeletons.push(skin.babylonSkeleton);
  75499. }
  75500. });
  75501. }
  75502. return skeletons;
  75503. };
  75504. GLTFLoader.prototype._getAnimationTargets = function () {
  75505. var targets = new Array();
  75506. var animations = this._gltf.animations;
  75507. if (animations) {
  75508. animations.forEach(function (animation) {
  75509. targets.push.apply(targets, animation.targets);
  75510. });
  75511. }
  75512. return targets;
  75513. };
  75514. GLTFLoader.prototype._startAnimations = function () {
  75515. var _this = this;
  75516. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  75517. };
  75518. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  75519. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  75520. if (!scene) {
  75521. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  75522. }
  75523. this._loadScene("scenes[" + scene.index + "]", scene, nodeNames);
  75524. };
  75525. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  75526. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  75527. switch (this._parent.coordinateSystemMode) {
  75528. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  75529. if (!this._babylonScene.useRightHandedSystem) {
  75530. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  75531. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  75532. }
  75533. break;
  75534. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  75535. // do nothing
  75536. break;
  75537. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  75538. this._babylonScene.useRightHandedSystem = true;
  75539. break;
  75540. default:
  75541. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  75542. return;
  75543. }
  75544. var nodeIndices = scene.nodes;
  75545. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  75546. node.parent = parentNode;
  75547. return true;
  75548. }, this._rootNode);
  75549. if (nodeNames) {
  75550. if (!(nodeNames instanceof Array)) {
  75551. nodeNames = [nodeNames];
  75552. }
  75553. var filteredNodeIndices = new Array();
  75554. this._traverseNodes(context, nodeIndices, function (node) {
  75555. if (nodeNames.indexOf(node.name) !== -1) {
  75556. filteredNodeIndices.push(node.index);
  75557. return false;
  75558. }
  75559. return true;
  75560. }, this._rootNode);
  75561. nodeIndices = filteredNodeIndices;
  75562. }
  75563. for (var i = 0; i < nodeIndices.length; i++) {
  75564. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  75565. if (!node) {
  75566. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  75567. }
  75568. this._loadNode("nodes[" + nodeIndices[i] + "]", node);
  75569. }
  75570. // Disable the root mesh until the asset is ready to render.
  75571. this._rootNode.babylonMesh.setEnabled(false);
  75572. };
  75573. GLTFLoader.prototype._loadNode = function (context, node) {
  75574. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  75575. return;
  75576. }
  75577. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  75578. this._loadTransform(node);
  75579. if (node.mesh != null) {
  75580. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  75581. if (!mesh) {
  75582. throw new Error(context + ": Failed to find mesh " + node.mesh);
  75583. }
  75584. this._loadMesh("meshes[" + node.mesh + "]", node, mesh);
  75585. }
  75586. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  75587. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75588. node.babylonAnimationTargets.push(node.babylonMesh);
  75589. if (node.skin != null) {
  75590. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  75591. if (!skin) {
  75592. throw new Error(context + ": Failed to find skin " + node.skin);
  75593. }
  75594. node.babylonMesh.skeleton = this._loadSkin("skins[" + node.skin + "]", skin);
  75595. }
  75596. if (node.camera != null) {
  75597. // TODO: handle cameras
  75598. }
  75599. if (node.children) {
  75600. for (var i = 0; i < node.children.length; i++) {
  75601. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  75602. if (!childNode) {
  75603. throw new Error(context + ": Failed to find child node " + node.children[i]);
  75604. }
  75605. this._loadNode("nodes[" + node.children[i] + "]", childNode);
  75606. }
  75607. }
  75608. };
  75609. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  75610. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  75611. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  75612. node.babylonMesh.material = babylonMultiMaterial;
  75613. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  75614. var vertexData = new BABYLON.VertexData();
  75615. vertexData.positions = [];
  75616. vertexData.indices = [];
  75617. var subMeshInfos = [];
  75618. var numRemainingPrimitives = mesh.primitives.length;
  75619. for (var index = 0; index < mesh.primitives.length; index++) {
  75620. var primitive = mesh.primitives[index];
  75621. this._loadPrimitive(context + "/primitives[" + index + "]", node, mesh, primitive, function (subVertexData, loadMaterial) {
  75622. subMeshInfos.push({
  75623. verticesStart: vertexData.positions.length,
  75624. verticesCount: subVertexData.positions.length,
  75625. indicesStart: vertexData.indices.length,
  75626. indicesCount: subVertexData.indices.length,
  75627. loadMaterial: loadMaterial
  75628. });
  75629. vertexData.merge(subVertexData);
  75630. if (--numRemainingPrimitives === 0) {
  75631. geometry.setAllVerticesData(vertexData, false);
  75632. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  75633. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  75634. node.babylonMesh.subMeshes = [];
  75635. for (var index = 0; index < subMeshInfos.length; index++) {
  75636. var info = subMeshInfos[index];
  75637. new BABYLON.SubMesh(index, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh);
  75638. info.loadMaterial(index);
  75639. }
  75640. }
  75641. });
  75642. }
  75643. };
  75644. GLTFLoader.prototype._loadPrimitive = function (context, node, mesh, primitive, onSuccess) {
  75645. var _this = this;
  75646. var subMaterials = node.babylonMesh.material.subMaterials;
  75647. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  75648. // TODO: handle other primitive modes
  75649. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  75650. }
  75651. this._createMorphTargets(node, mesh, primitive);
  75652. this._loadVertexDataAsync(context, mesh, primitive, function (vertexData) {
  75653. _this._loadMorphTargetsData(context, mesh, primitive, vertexData, node.babylonMesh);
  75654. var loadMaterial = function (index) {
  75655. if (primitive.material == null) {
  75656. subMaterials[index] = _this._getDefaultMaterial();
  75657. }
  75658. else {
  75659. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  75660. if (!material) {
  75661. throw new Error(context + ": Failed to find material " + primitive.material);
  75662. }
  75663. _this._loadMaterial("materials[" + material.index + "]", material, function (babylonMaterial, isNew) {
  75664. if (isNew && _this._parent.onMaterialLoaded) {
  75665. _this._parent.onMaterialLoaded(babylonMaterial);
  75666. }
  75667. if (_this._parent.onBeforeMaterialReadyAsync) {
  75668. _this._addLoaderPendingData(material);
  75669. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  75670. subMaterials[index] = babylonMaterial;
  75671. _this._removeLoaderPendingData(material);
  75672. });
  75673. }
  75674. else {
  75675. subMaterials[index] = babylonMaterial;
  75676. }
  75677. });
  75678. }
  75679. };
  75680. onSuccess(vertexData, loadMaterial);
  75681. });
  75682. };
  75683. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  75684. var _this = this;
  75685. var attributes = primitive.attributes;
  75686. if (!attributes) {
  75687. throw new Error(context + ": Attributes are missing");
  75688. }
  75689. var vertexData = new BABYLON.VertexData();
  75690. var numRemainingAttributes = Object.keys(attributes).length;
  75691. var _loop_1 = function (attribute) {
  75692. accessor = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.accessors, attributes[attribute]);
  75693. if (!accessor) {
  75694. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75695. }
  75696. this_1._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75697. switch (attribute) {
  75698. case "NORMAL":
  75699. vertexData.normals = data;
  75700. break;
  75701. case "POSITION":
  75702. vertexData.positions = data;
  75703. break;
  75704. case "TANGENT":
  75705. vertexData.tangents = data;
  75706. break;
  75707. case "TEXCOORD_0":
  75708. vertexData.uvs = data;
  75709. break;
  75710. case "TEXCOORD_1":
  75711. vertexData.uvs2 = data;
  75712. break;
  75713. case "JOINTS_0":
  75714. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  75715. break;
  75716. case "WEIGHTS_0":
  75717. vertexData.matricesWeights = data;
  75718. break;
  75719. case "COLOR_0":
  75720. vertexData.colors = data;
  75721. break;
  75722. default:
  75723. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75724. break;
  75725. }
  75726. if (--numRemainingAttributes === 0) {
  75727. if (primitive.indices == null) {
  75728. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  75729. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  75730. onSuccess(vertexData);
  75731. }
  75732. else {
  75733. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  75734. if (!indicesAccessor) {
  75735. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  75736. }
  75737. _this._loadAccessorAsync("accessors[" + indicesAccessor.index + "]", indicesAccessor, function (data) {
  75738. vertexData.indices = data;
  75739. onSuccess(vertexData);
  75740. });
  75741. }
  75742. }
  75743. });
  75744. };
  75745. var this_1 = this, accessor;
  75746. for (var attribute in attributes) {
  75747. _loop_1(attribute);
  75748. }
  75749. };
  75750. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive) {
  75751. var targets = primitive.targets;
  75752. if (!targets) {
  75753. return;
  75754. }
  75755. if (!node.babylonMesh.morphTargetManager) {
  75756. node.babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  75757. }
  75758. for (var index = 0; index < targets.length; index++) {
  75759. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  75760. node.babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  75761. }
  75762. };
  75763. GLTFLoader.prototype._loadMorphTargetsData = function (context, mesh, primitive, vertexData, babylonMesh) {
  75764. var targets = primitive.targets;
  75765. if (!targets) {
  75766. return;
  75767. }
  75768. var _loop_2 = function () {
  75769. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  75770. attributes = targets[index];
  75771. var _loop_3 = function (attribute) {
  75772. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  75773. if (!accessor) {
  75774. throw new Error(context + "/targets[" + index + "]: Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75775. }
  75776. this_2._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75777. if (accessor.name) {
  75778. babylonMorphTarget.name = accessor.name;
  75779. }
  75780. // glTF stores morph target information as deltas while babylon.js expects the final data.
  75781. // As a result we have to add the original data to the delta to calculate the final data.
  75782. var values = data;
  75783. switch (attribute) {
  75784. case "NORMAL":
  75785. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  75786. babylonMorphTarget.setNormals(values);
  75787. break;
  75788. case "POSITION":
  75789. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  75790. babylonMorphTarget.setPositions(values);
  75791. break;
  75792. case "TANGENT":
  75793. // Tangent data for morph targets is stored as xyz delta.
  75794. // The vertexData.tangent is stored as xyzw.
  75795. // So we need to skip every fourth vertexData.tangent.
  75796. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75797. values[i] += vertexData.tangents[j];
  75798. if ((i + 1) % 3 == 0) {
  75799. j++;
  75800. }
  75801. }
  75802. babylonMorphTarget.setTangents(values);
  75803. break;
  75804. default:
  75805. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75806. break;
  75807. }
  75808. });
  75809. };
  75810. for (var attribute in attributes) {
  75811. _loop_3(attribute);
  75812. }
  75813. };
  75814. var this_2 = this, attributes, accessor;
  75815. for (var index = 0; index < targets.length; index++) {
  75816. _loop_2();
  75817. }
  75818. };
  75819. GLTFLoader.prototype._loadTransform = function (node) {
  75820. var position = BABYLON.Vector3.Zero();
  75821. var rotation = BABYLON.Quaternion.Identity();
  75822. var scaling = BABYLON.Vector3.One();
  75823. if (node.matrix) {
  75824. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75825. mat.decompose(scaling, rotation, position);
  75826. }
  75827. else {
  75828. if (node.translation)
  75829. position = BABYLON.Vector3.FromArray(node.translation);
  75830. if (node.rotation)
  75831. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75832. if (node.scale)
  75833. scaling = BABYLON.Vector3.FromArray(node.scale);
  75834. }
  75835. node.babylonMesh.position = position;
  75836. node.babylonMesh.rotationQuaternion = rotation;
  75837. node.babylonMesh.scaling = scaling;
  75838. };
  75839. GLTFLoader.prototype._loadSkin = function (context, skin) {
  75840. var _this = this;
  75841. var skeletonId = "skeleton" + skin.index;
  75842. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  75843. if (skin.inverseBindMatrices == null) {
  75844. this._loadBones(context, skin, null);
  75845. }
  75846. else {
  75847. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  75848. if (!accessor) {
  75849. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  75850. }
  75851. this._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75852. _this._loadBones(context, skin, data);
  75853. });
  75854. }
  75855. return skin.babylonSkeleton;
  75856. };
  75857. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  75858. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  75859. node.babylonBones = node.babylonBones || {};
  75860. node.babylonBones[skin.index] = babylonBone;
  75861. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75862. node.babylonAnimationTargets.push(babylonBone);
  75863. return babylonBone;
  75864. };
  75865. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  75866. var babylonBones = {};
  75867. for (var i = 0; i < skin.joints.length; i++) {
  75868. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  75869. if (!node) {
  75870. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  75871. }
  75872. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  75873. }
  75874. };
  75875. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  75876. var babylonBone = babylonBones[node.index];
  75877. if (babylonBone) {
  75878. return babylonBone;
  75879. }
  75880. var boneIndex = skin.joints.indexOf(node.index);
  75881. var baseMatrix = BABYLON.Matrix.Identity();
  75882. if (inverseBindMatrixData && boneIndex !== -1) {
  75883. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  75884. baseMatrix.invertToRef(baseMatrix);
  75885. }
  75886. var babylonParentBone;
  75887. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  75888. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  75889. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  75890. }
  75891. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  75892. babylonBones[node.index] = babylonBone;
  75893. return babylonBone;
  75894. };
  75895. GLTFLoader.prototype._getNodeMatrix = function (node) {
  75896. return node.matrix ?
  75897. BABYLON.Matrix.FromArray(node.matrix) :
  75898. 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());
  75899. };
  75900. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  75901. if (parentNode === void 0) { parentNode = null; }
  75902. for (var i = 0; i < indices.length; i++) {
  75903. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  75904. if (!node) {
  75905. throw new Error(context + ": Failed to find node " + indices[i]);
  75906. }
  75907. this._traverseNode(context, node, action, parentNode);
  75908. }
  75909. };
  75910. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  75911. if (parentNode === void 0) { parentNode = null; }
  75912. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  75913. return;
  75914. }
  75915. if (!action(node, parentNode)) {
  75916. return;
  75917. }
  75918. if (node.children) {
  75919. this._traverseNodes(context, node.children, action, node);
  75920. }
  75921. };
  75922. GLTFLoader.prototype._loadAnimations = function () {
  75923. var animations = this._gltf.animations;
  75924. if (!animations) {
  75925. return;
  75926. }
  75927. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75928. var animation = animations[animationIndex];
  75929. var context = "animations[" + animationIndex + "]";
  75930. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75931. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  75932. if (!channel) {
  75933. throw new Error(context + ": Failed to find channel " + channelIndex);
  75934. }
  75935. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  75936. if (!sampler) {
  75937. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  75938. }
  75939. this._loadAnimationChannel(animation, context + "/channels[" + channelIndex + "]", channel, context + "/samplers[" + channel.sampler + "]", sampler);
  75940. }
  75941. }
  75942. };
  75943. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  75944. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  75945. if (!targetNode) {
  75946. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  75947. }
  75948. var conversion = {
  75949. "translation": "position",
  75950. "rotation": "rotationQuaternion",
  75951. "scale": "scaling",
  75952. "weights": "influence"
  75953. };
  75954. var targetPath = conversion[channel.target.path];
  75955. if (!targetPath) {
  75956. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  75957. }
  75958. var animationConvertion = {
  75959. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75960. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75961. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75962. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75963. };
  75964. var animationType = animationConvertion[targetPath];
  75965. var inputData;
  75966. var outputData;
  75967. var checkSuccess = function () {
  75968. if (!inputData || !outputData) {
  75969. return;
  75970. }
  75971. var outputBufferOffset = 0;
  75972. var nextOutputConversion = {
  75973. "position": function () {
  75974. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75975. outputBufferOffset += 3;
  75976. return value;
  75977. },
  75978. "rotationQuaternion": function () {
  75979. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75980. outputBufferOffset += 4;
  75981. return value;
  75982. },
  75983. "scaling": function () {
  75984. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75985. outputBufferOffset += 3;
  75986. return value;
  75987. },
  75988. "influence": function () {
  75989. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75990. var value = new Array(numTargets);
  75991. for (var i = 0; i < numTargets; i++) {
  75992. value[i] = outputData[outputBufferOffset++];
  75993. }
  75994. return value;
  75995. },
  75996. };
  75997. var getNextOutputValue = nextOutputConversion[targetPath];
  75998. var nextKeyConversion = {
  75999. "LINEAR": function (frameIndex) { return ({
  76000. frame: inputData[frameIndex],
  76001. value: getNextOutputValue()
  76002. }); },
  76003. "CUBICSPLINE": function (frameIndex) { return ({
  76004. frame: inputData[frameIndex],
  76005. inTangent: getNextOutputValue(),
  76006. value: getNextOutputValue(),
  76007. outTangent: getNextOutputValue()
  76008. }); },
  76009. };
  76010. var getNextKey = nextKeyConversion[sampler.interpolation];
  76011. if (!getNextKey) {
  76012. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  76013. }
  76014. var keys = new Array(inputData.length);
  76015. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  76016. keys[frameIndex] = getNextKey(frameIndex);
  76017. }
  76018. animation.targets = animation.targets || [];
  76019. if (targetPath === "influence") {
  76020. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  76021. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  76022. var morphTarget = morphTargetManager.getTarget(targetIndex);
  76023. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  76024. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  76025. babylonAnimation.setKeys(keys.map(function (key) { return ({
  76026. frame: key.frame,
  76027. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  76028. value: key.value[targetIndex],
  76029. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  76030. }); }));
  76031. morphTarget.animations.push(babylonAnimation);
  76032. animation.targets.push(morphTarget);
  76033. }
  76034. }
  76035. else {
  76036. var animationName = animation.name || "anim" + animation.index;
  76037. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  76038. babylonAnimation.setKeys(keys);
  76039. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  76040. var target = targetNode.babylonAnimationTargets[i];
  76041. target.animations.push(babylonAnimation.clone());
  76042. animation.targets.push(target);
  76043. }
  76044. }
  76045. };
  76046. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  76047. if (!inputAccessor) {
  76048. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  76049. }
  76050. this._loadAccessorAsync("accessors[" + inputAccessor.index + "]", inputAccessor, function (data) {
  76051. inputData = data;
  76052. checkSuccess();
  76053. });
  76054. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  76055. if (!outputAccessor) {
  76056. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  76057. }
  76058. this._loadAccessorAsync("accessors[" + outputAccessor.index + "]", outputAccessor, function (data) {
  76059. outputData = data;
  76060. checkSuccess();
  76061. });
  76062. };
  76063. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  76064. var _this = this;
  76065. this._addPendingData(buffer);
  76066. if (buffer.loadedData) {
  76067. onSuccess(buffer.loadedData);
  76068. this._removePendingData(buffer);
  76069. }
  76070. else if (buffer.loadedObservable) {
  76071. buffer.loadedObservable.add(function (buffer) {
  76072. onSuccess(buffer.loadedData);
  76073. _this._removePendingData(buffer);
  76074. });
  76075. }
  76076. else {
  76077. if (!buffer.uri) {
  76078. throw new Error(context + ": Uri is missing");
  76079. }
  76080. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  76081. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  76082. buffer.loadedData = new Uint8Array(data);
  76083. onSuccess(buffer.loadedData);
  76084. this._removePendingData(buffer);
  76085. }
  76086. else {
  76087. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  76088. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  76089. }
  76090. buffer.loadedObservable = new BABYLON.Observable();
  76091. buffer.loadedObservable.add(function (buffer) {
  76092. onSuccess(buffer.loadedData);
  76093. _this._removePendingData(buffer);
  76094. });
  76095. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  76096. _this._tryCatchOnError(function () {
  76097. buffer.loadedData = new Uint8Array(data);
  76098. buffer.loadedObservable.notifyObservers(buffer);
  76099. buffer.loadedObservable = null;
  76100. });
  76101. }, function (event) {
  76102. _this._tryCatchOnError(function () {
  76103. _this._onProgress(event);
  76104. });
  76105. }, this._babylonScene.database, true, function (request) {
  76106. _this._tryCatchOnError(function () {
  76107. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  76108. });
  76109. });
  76110. }
  76111. }
  76112. };
  76113. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  76114. var _this = this;
  76115. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  76116. if (!buffer) {
  76117. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  76118. }
  76119. this._loadBufferAsync("buffers[" + buffer.index + "]", buffer, function (bufferData) {
  76120. if (_this._disposed) {
  76121. return;
  76122. }
  76123. try {
  76124. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  76125. }
  76126. catch (e) {
  76127. throw new Error(context + ": " + e.message);
  76128. }
  76129. onSuccess(data);
  76130. });
  76131. };
  76132. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  76133. var _this = this;
  76134. if (accessor.sparse) {
  76135. throw new Error(context + ": Sparse accessors are not currently supported");
  76136. }
  76137. if (accessor.normalized) {
  76138. throw new Error(context + ": Normalized accessors are not currently supported");
  76139. }
  76140. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  76141. if (!bufferView) {
  76142. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  76143. }
  76144. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, function (bufferViewData) {
  76145. var numComponents = _this._getNumComponentsOfType(accessor.type);
  76146. if (numComponents === 0) {
  76147. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  76148. }
  76149. var data;
  76150. switch (accessor.componentType) {
  76151. case GLTF2.EComponentType.BYTE:
  76152. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76153. break;
  76154. case GLTF2.EComponentType.UNSIGNED_BYTE:
  76155. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76156. break;
  76157. case GLTF2.EComponentType.SHORT:
  76158. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76159. break;
  76160. case GLTF2.EComponentType.UNSIGNED_SHORT:
  76161. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76162. break;
  76163. case GLTF2.EComponentType.UNSIGNED_INT:
  76164. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76165. break;
  76166. case GLTF2.EComponentType.FLOAT:
  76167. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76168. break;
  76169. default:
  76170. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  76171. }
  76172. onSuccess(data);
  76173. });
  76174. };
  76175. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  76176. switch (type) {
  76177. case "SCALAR": return 1;
  76178. case "VEC2": return 2;
  76179. case "VEC3": return 3;
  76180. case "VEC4": return 4;
  76181. case "MAT2": return 4;
  76182. case "MAT3": return 9;
  76183. case "MAT4": return 16;
  76184. }
  76185. return 0;
  76186. };
  76187. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  76188. try {
  76189. var byteOffset = data.byteOffset + (byteOffset || 0);
  76190. var targetLength = count * numComponents;
  76191. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  76192. return new typedArray(data.buffer, byteOffset, targetLength);
  76193. }
  76194. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  76195. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  76196. var targetBuffer = new typedArray(targetLength);
  76197. var sourceIndex = 0;
  76198. var targetIndex = 0;
  76199. while (targetIndex < targetLength) {
  76200. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  76201. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  76202. targetIndex++;
  76203. }
  76204. sourceIndex += elementStride;
  76205. }
  76206. return targetBuffer;
  76207. }
  76208. catch (e) {
  76209. throw new Error(context + ": " + e);
  76210. }
  76211. };
  76212. GLTFLoader.prototype._addPendingData = function (data) {
  76213. if (!this._renderReady) {
  76214. this._renderPendingCount++;
  76215. }
  76216. this._addLoaderPendingData(data);
  76217. };
  76218. GLTFLoader.prototype._removePendingData = function (data) {
  76219. if (!this._renderReady) {
  76220. if (--this._renderPendingCount === 0) {
  76221. this._renderReady = true;
  76222. this._onRenderReady();
  76223. }
  76224. }
  76225. this._removeLoaderPendingData(data);
  76226. };
  76227. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  76228. this._loaderPendingCount++;
  76229. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  76230. };
  76231. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  76232. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  76233. if (--this._loaderPendingCount === 0) {
  76234. this._onComplete();
  76235. }
  76236. };
  76237. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  76238. var _this = this;
  76239. var tracker = new GLTFLoaderTracker(function () {
  76240. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  76241. onComplete();
  76242. });
  76243. this._loaderTrackers.push(tracker);
  76244. this._addLoaderPendingData(tracker);
  76245. action();
  76246. this._removeLoaderPendingData(tracker);
  76247. };
  76248. GLTFLoader.prototype._getDefaultMaterial = function () {
  76249. if (!this._defaultMaterial) {
  76250. var id = "__gltf_default";
  76251. var material = this._babylonScene.getMaterialByName(id);
  76252. if (!material) {
  76253. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  76254. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76255. material.metallic = 1;
  76256. material.roughness = 1;
  76257. }
  76258. this._defaultMaterial = material;
  76259. }
  76260. return this._defaultMaterial;
  76261. };
  76262. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  76263. var babylonMaterial = material.babylonMaterial;
  76264. // Ensure metallic workflow
  76265. babylonMaterial.metallic = 1;
  76266. babylonMaterial.roughness = 1;
  76267. var properties = material.pbrMetallicRoughness;
  76268. if (!properties) {
  76269. return;
  76270. }
  76271. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  76272. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  76273. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  76274. if (properties.baseColorTexture) {
  76275. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  76276. if (!texture) {
  76277. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  76278. }
  76279. babylonMaterial.albedoTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.baseColorTexture.texCoord);
  76280. }
  76281. if (properties.metallicRoughnessTexture) {
  76282. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  76283. if (!texture) {
  76284. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  76285. }
  76286. babylonMaterial.metallicTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.metallicRoughnessTexture.texCoord);
  76287. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  76288. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  76289. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  76290. }
  76291. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  76292. };
  76293. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  76294. if (material.babylonMaterial) {
  76295. assign(material.babylonMaterial, false);
  76296. return;
  76297. }
  76298. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  76299. return;
  76300. }
  76301. this._createPbrMaterial(material);
  76302. this._loadMaterialBaseProperties(context, material);
  76303. this._loadMaterialMetallicRoughnessProperties(context, material);
  76304. assign(material.babylonMaterial, true);
  76305. };
  76306. GLTFLoader.prototype._createPbrMaterial = function (material) {
  76307. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  76308. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76309. material.babylonMaterial = babylonMaterial;
  76310. };
  76311. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  76312. var babylonMaterial = material.babylonMaterial;
  76313. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  76314. if (material.doubleSided) {
  76315. babylonMaterial.backFaceCulling = false;
  76316. babylonMaterial.twoSidedLighting = true;
  76317. }
  76318. if (material.normalTexture) {
  76319. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  76320. if (!texture) {
  76321. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  76322. }
  76323. babylonMaterial.bumpTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.normalTexture.texCoord);
  76324. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  76325. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  76326. if (material.normalTexture.scale != null) {
  76327. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  76328. }
  76329. }
  76330. if (material.occlusionTexture) {
  76331. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  76332. if (!texture) {
  76333. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  76334. }
  76335. babylonMaterial.ambientTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.occlusionTexture.texCoord);
  76336. babylonMaterial.useAmbientInGrayScale = true;
  76337. if (material.occlusionTexture.strength != null) {
  76338. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  76339. }
  76340. }
  76341. if (material.emissiveTexture) {
  76342. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  76343. if (!texture) {
  76344. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  76345. }
  76346. babylonMaterial.emissiveTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.emissiveTexture.texCoord);
  76347. }
  76348. };
  76349. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  76350. var babylonMaterial = material.babylonMaterial;
  76351. var alphaMode = material.alphaMode || "OPAQUE";
  76352. switch (alphaMode) {
  76353. case "OPAQUE":
  76354. // default is opaque
  76355. break;
  76356. case "MASK":
  76357. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  76358. if (colorFactor) {
  76359. if (colorFactor[3] == 0) {
  76360. babylonMaterial.alphaCutOff = 1;
  76361. }
  76362. else {
  76363. babylonMaterial.alphaCutOff /= colorFactor[3];
  76364. }
  76365. }
  76366. if (babylonMaterial.albedoTexture) {
  76367. babylonMaterial.albedoTexture.hasAlpha = true;
  76368. }
  76369. break;
  76370. case "BLEND":
  76371. if (colorFactor) {
  76372. babylonMaterial.alpha = colorFactor[3];
  76373. }
  76374. if (babylonMaterial.albedoTexture) {
  76375. babylonMaterial.albedoTexture.hasAlpha = true;
  76376. babylonMaterial.useAlphaFromAlbedoTexture = true;
  76377. }
  76378. break;
  76379. default:
  76380. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  76381. }
  76382. };
  76383. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  76384. var _this = this;
  76385. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  76386. if (!sampler) {
  76387. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  76388. }
  76389. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  76390. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  76391. this._addPendingData(texture);
  76392. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  76393. _this._tryCatchOnError(function () {
  76394. _this._removePendingData(texture);
  76395. });
  76396. }, function (message) {
  76397. _this._tryCatchOnError(function () {
  76398. throw new Error(context + ": " + message);
  76399. });
  76400. });
  76401. if (texture.url) {
  76402. babylonTexture.updateURL(texture.url);
  76403. }
  76404. else if (texture.dataReadyObservable) {
  76405. texture.dataReadyObservable.add(function (texture) {
  76406. babylonTexture.updateURL(texture.url);
  76407. });
  76408. }
  76409. else {
  76410. texture.dataReadyObservable = new BABYLON.Observable();
  76411. texture.dataReadyObservable.add(function (texture) {
  76412. babylonTexture.updateURL(texture.url);
  76413. });
  76414. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  76415. if (!image) {
  76416. throw new Error(context + ": Failed to find source " + texture.source);
  76417. }
  76418. this._loadImage("images[" + image.index + "]", image, function (data) {
  76419. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  76420. texture.dataReadyObservable.notifyObservers(texture);
  76421. });
  76422. }
  76423. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  76424. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  76425. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  76426. babylonTexture.name = texture.name || "texture" + texture.index;
  76427. if (this._parent.onTextureLoaded) {
  76428. this._parent.onTextureLoaded(babylonTexture);
  76429. }
  76430. return babylonTexture;
  76431. };
  76432. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  76433. var _this = this;
  76434. if (image.uri) {
  76435. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  76436. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  76437. }
  76438. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  76439. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  76440. }
  76441. else {
  76442. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  76443. _this._tryCatchOnError(function () {
  76444. onSuccess(data);
  76445. });
  76446. }, function (event) {
  76447. _this._tryCatchOnError(function () {
  76448. _this._onProgress(event);
  76449. });
  76450. }, this._babylonScene.database, true, function (request) {
  76451. _this._tryCatchOnError(function () {
  76452. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  76453. });
  76454. });
  76455. }
  76456. }
  76457. else {
  76458. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  76459. if (!bufferView) {
  76460. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  76461. }
  76462. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, onSuccess);
  76463. }
  76464. };
  76465. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  76466. try {
  76467. handler();
  76468. }
  76469. catch (e) {
  76470. this._onError(e.message);
  76471. }
  76472. };
  76473. GLTFLoader.Extensions = {};
  76474. return GLTFLoader;
  76475. }());
  76476. GLTF2.GLTFLoader = GLTFLoader;
  76477. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  76478. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76479. })(BABYLON || (BABYLON = {}));
  76480. //# sourceMappingURL=babylon.glTFLoader.js.map
  76481. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76482. var BABYLON;
  76483. (function (BABYLON) {
  76484. var GLTF2;
  76485. (function (GLTF2) {
  76486. /**
  76487. * Utils functions for GLTF
  76488. */
  76489. var GLTFUtils = (function () {
  76490. function GLTFUtils() {
  76491. }
  76492. /**
  76493. * If the uri is a base64 string
  76494. * @param uri: the uri to test
  76495. */
  76496. GLTFUtils.IsBase64 = function (uri) {
  76497. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  76498. };
  76499. /**
  76500. * Decode the base64 uri
  76501. * @param uri: the uri to decode
  76502. */
  76503. GLTFUtils.DecodeBase64 = function (uri) {
  76504. var decodedString = atob(uri.split(",")[1]);
  76505. var bufferLength = decodedString.length;
  76506. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  76507. for (var i = 0; i < bufferLength; i++) {
  76508. bufferView[i] = decodedString.charCodeAt(i);
  76509. }
  76510. return bufferView.buffer;
  76511. };
  76512. GLTFUtils.ForEach = function (view, func) {
  76513. for (var index = 0; index < view.length; index++) {
  76514. func(view[index], index);
  76515. }
  76516. };
  76517. GLTFUtils.ValidateUri = function (uri) {
  76518. return (uri.indexOf("..") === -1);
  76519. };
  76520. GLTFUtils.AssignIndices = function (array) {
  76521. if (array) {
  76522. for (var index = 0; index < array.length; index++) {
  76523. array[index].index = index;
  76524. }
  76525. }
  76526. };
  76527. GLTFUtils.GetArrayItem = function (array, index) {
  76528. if (!array || !array[index]) {
  76529. return null;
  76530. }
  76531. return array[index];
  76532. };
  76533. GLTFUtils.GetTextureWrapMode = function (mode) {
  76534. // Set defaults if undefined
  76535. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  76536. switch (mode) {
  76537. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  76538. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  76539. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76540. default:
  76541. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  76542. return BABYLON.Texture.WRAP_ADDRESSMODE;
  76543. }
  76544. };
  76545. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  76546. // Set defaults if undefined
  76547. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  76548. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  76549. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  76550. switch (minFilter) {
  76551. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  76552. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  76553. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  76554. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  76555. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  76556. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76557. default:
  76558. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76559. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76560. }
  76561. }
  76562. else {
  76563. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  76564. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  76565. }
  76566. switch (minFilter) {
  76567. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  76568. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  76569. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76570. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  76571. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  76572. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  76573. default:
  76574. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76575. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76576. }
  76577. }
  76578. };
  76579. /**
  76580. * Decodes a buffer view into a string
  76581. * @param view: the buffer view
  76582. */
  76583. GLTFUtils.DecodeBufferToText = function (view) {
  76584. var result = "";
  76585. var length = view.byteLength;
  76586. for (var i = 0; i < length; ++i) {
  76587. result += String.fromCharCode(view[i]);
  76588. }
  76589. return result;
  76590. };
  76591. return GLTFUtils;
  76592. }());
  76593. GLTF2.GLTFUtils = GLTFUtils;
  76594. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76595. })(BABYLON || (BABYLON = {}));
  76596. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  76597. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76598. var BABYLON;
  76599. (function (BABYLON) {
  76600. var GLTF2;
  76601. (function (GLTF2) {
  76602. var GLTFLoaderExtension = (function () {
  76603. function GLTFLoaderExtension() {
  76604. this.enabled = true;
  76605. }
  76606. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  76607. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  76608. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  76609. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  76610. var _this = this;
  76611. if (!property.extensions) {
  76612. return false;
  76613. }
  76614. var extension = property.extensions[this.name];
  76615. if (!extension) {
  76616. return false;
  76617. }
  76618. // Clear out the extension before executing the action to avoid recursing into the same property.
  76619. property.extensions[this.name] = undefined;
  76620. action(extension, function () {
  76621. // Restore the extension after completing the action.
  76622. property.extensions[_this.name] = extension;
  76623. });
  76624. return true;
  76625. };
  76626. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  76627. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  76628. };
  76629. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  76630. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  76631. };
  76632. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  76633. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  76634. };
  76635. GLTFLoaderExtension._ApplyExtensions = function (action) {
  76636. var extensions = GLTFLoaderExtension._Extensions;
  76637. if (!extensions) {
  76638. return;
  76639. }
  76640. for (var i = 0; i < extensions.length; i++) {
  76641. var extension = extensions[i];
  76642. if (extension.enabled && action(extension)) {
  76643. return true;
  76644. }
  76645. }
  76646. return false;
  76647. };
  76648. //
  76649. // Utilities
  76650. //
  76651. GLTFLoaderExtension._Extensions = [];
  76652. return GLTFLoaderExtension;
  76653. }());
  76654. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  76655. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76656. })(BABYLON || (BABYLON = {}));
  76657. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  76658. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76659. var BABYLON;
  76660. (function (BABYLON) {
  76661. var GLTF2;
  76662. (function (GLTF2) {
  76663. var Extensions;
  76664. (function (Extensions) {
  76665. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  76666. var MSFTLOD = (function (_super) {
  76667. __extends(MSFTLOD, _super);
  76668. function MSFTLOD() {
  76669. return _super !== null && _super.apply(this, arguments) || this;
  76670. }
  76671. Object.defineProperty(MSFTLOD.prototype, "name", {
  76672. get: function () {
  76673. return "MSFT_lod";
  76674. },
  76675. enumerable: true,
  76676. configurable: true
  76677. });
  76678. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  76679. return this._loadExtension(node, function (extension, onComplete) {
  76680. for (var i = extension.ids.length - 1; i >= 0; i--) {
  76681. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  76682. if (!lodNode) {
  76683. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  76684. }
  76685. loader._traverseNode(context, lodNode, action, parentNode);
  76686. }
  76687. loader._traverseNode(context, node, action, parentNode);
  76688. onComplete();
  76689. });
  76690. };
  76691. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  76692. var _this = this;
  76693. return this._loadExtension(node, function (extension, onComplete) {
  76694. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  76695. loader._addLoaderPendingData(node);
  76696. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  76697. loader._removeLoaderPendingData(node);
  76698. onComplete();
  76699. });
  76700. });
  76701. };
  76702. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  76703. var _this = this;
  76704. loader._whenAction(function () {
  76705. loader._loadNode(context, nodes[index]);
  76706. }, function () {
  76707. if (index !== nodes.length - 1) {
  76708. var previousNode = nodes[index + 1];
  76709. previousNode.babylonMesh.setEnabled(false);
  76710. }
  76711. if (index === 0) {
  76712. onComplete();
  76713. return;
  76714. }
  76715. setTimeout(function () {
  76716. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  76717. }, MSFTLOD.MinimalLODDelay);
  76718. });
  76719. };
  76720. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  76721. var _this = this;
  76722. return this._loadExtension(material, function (extension, onComplete) {
  76723. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  76724. loader._addLoaderPendingData(material);
  76725. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  76726. material.extensions[_this.name] = extension;
  76727. loader._removeLoaderPendingData(material);
  76728. onComplete();
  76729. });
  76730. });
  76731. };
  76732. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  76733. var _this = this;
  76734. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  76735. assign(babylonMaterial, isNew);
  76736. if (index === 0) {
  76737. onComplete();
  76738. return;
  76739. }
  76740. // Load the next LOD when the loader is ready to render and
  76741. // all active material textures of the current LOD are loaded.
  76742. loader._executeWhenRenderReady(function () {
  76743. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  76744. setTimeout(function () {
  76745. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  76746. }, MSFTLOD.MinimalLODDelay);
  76747. });
  76748. });
  76749. });
  76750. };
  76751. /**
  76752. * Specify the minimal delay between LODs in ms (default = 250)
  76753. */
  76754. MSFTLOD.MinimalLODDelay = 250;
  76755. return MSFTLOD;
  76756. }(GLTF2.GLTFLoaderExtension));
  76757. Extensions.MSFTLOD = MSFTLOD;
  76758. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  76759. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76760. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76761. })(BABYLON || (BABYLON = {}));
  76762. //# sourceMappingURL=MSFT_lod.js.map
  76763. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76764. var BABYLON;
  76765. (function (BABYLON) {
  76766. var GLTF2;
  76767. (function (GLTF2) {
  76768. var Extensions;
  76769. (function (Extensions) {
  76770. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  76771. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  76772. function KHRMaterialsPbrSpecularGlossiness() {
  76773. return _super !== null && _super.apply(this, arguments) || this;
  76774. }
  76775. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  76776. get: function () {
  76777. return "KHR_materials_pbrSpecularGlossiness";
  76778. },
  76779. enumerable: true,
  76780. configurable: true
  76781. });
  76782. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  76783. var _this = this;
  76784. return this._loadExtension(material, function (extension, onComplete) {
  76785. loader._createPbrMaterial(material);
  76786. loader._loadMaterialBaseProperties(context, material);
  76787. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  76788. assign(material.babylonMaterial, true);
  76789. });
  76790. };
  76791. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  76792. var babylonMaterial = material.babylonMaterial;
  76793. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  76794. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  76795. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  76796. if (properties.diffuseTexture) {
  76797. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  76798. if (!texture) {
  76799. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  76800. }
  76801. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  76802. }
  76803. if (properties.specularGlossinessTexture) {
  76804. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  76805. if (!texture) {
  76806. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  76807. }
  76808. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  76809. babylonMaterial.reflectivityTexture.hasAlpha = true;
  76810. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  76811. }
  76812. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  76813. };
  76814. return KHRMaterialsPbrSpecularGlossiness;
  76815. }(GLTF2.GLTFLoaderExtension));
  76816. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  76817. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  76818. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76819. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76820. })(BABYLON || (BABYLON = {}));
  76821. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  76822. (function universalModuleDefinition(root, factory) {
  76823. if (root && root["BABYLON"]) {
  76824. return;
  76825. }
  76826. if(typeof exports === 'object' && typeof module === 'object')
  76827. module.exports = factory();
  76828. else if(typeof define === 'function' && define.amd)
  76829. define([], factory);
  76830. else if(typeof exports === 'object')
  76831. exports["BABYLON"] = factory();
  76832. else {
  76833. root["BABYLON"] = factory();
  76834. }
  76835. })(this, function() {
  76836. return BABYLON;
  76837. });